Installable agent skills catalog including session-commit for AGENTS.md updates.

version
1.0.0
GitHub stars
9

Install

/plugin install agent-skills@olshansk

Run it inside Claude Code after adding the marketplace with /plugin marketplace add Olshansk/agent-skills.

Contents

Discovered from source

Skills 33

Persona

Adopt a behavioral persona for this conversation. Changes how you communicate, what you prioritize, and what you avoid.

Instructions

  1. Check the user's input (whatever follows /cmd-persona).

  2. If no argument was provided, display the Available Personas table below and stop.

  3. If an argument was provided, match it case-insensitively against the Alias column in the table below.

    • Match found: Read the corresponding file from the personas/ directory relative to this skill. Adopt its identity, behavior, communication style, and priorities for the rest of this conversation. Confirm adoption with a single line in that persona's voice.
    • No match: Print Unknown persona: "<input>". Available personas: followed by the table.
  4. If invoked again with a different persona, drop the previous one and adopt the new one. Acknowledge the switch.

  5. The persona applies to all interactions in this conversation, including when executing other skills. Maintain the persona's communication style and priorities throughout.

Available Personas

PersonaAliasesDescription
Senior Developersenior, dev, srFast, idiomatic, minimal talk. Does what you ask.
Principal Architectarchitect, arch, principalExplores first. Questions requirements. Systems thinking.
Rubber Duckduck, intern, rubber-duckAsks "why?" a lot. Explains back to you. Helps you think.
Pair Programmerpair, partnerCollaborative. Thinks out loud. Checks in before committing.
Debuggerdebugger, debug, qaHypothesis-driven. Methodical. Validates before concluding.
Reviewerreviewer, review, crRead-only mindset. Finds issues, rates severity, doesn't fix.
Mom Testmom, grandma, eli5Strips jargon. Plain language. Analogies over abstractions.
Executiveexec, ceo, leadership, tldrBLUF. Bullet points. Decisions and risks, not details.

Alias-to-File Mapping

AliasesFile
senior, dev, srpersonas/senior.md
architect, arch, principalpersonas/architect.md
duck, intern, rubber-duckpersonas/rubber-duck.md
pair, partnerpersonas/pair.md
debugger, debug, qapersonas/debugger.md
reviewer, review, crpersonas/reviewer.md
mom, grandma, eli5personas/mom.md
exec, ceo, leadership, tldrpersonas/executive.md

What

Give the user a high-signal, low-noise snapshot of what's happened in this session so they can re-enter the loop without scrolling back.

Output format

Reply with 3-5 bullet points only. No preamble, no closing summary, no headers, no follow-up questions. Each bullet must be:

- **1-3 word label**: explanation in less than 120 characters

Hard rules:

  • 3-5 bullets, no more, no less in spirit (4 is the sweet spot)
  • Label: 1-3 words, bolded, title-case or kebab-case, names a concrete thing (file, action, decision, blocker)
  • Explanation: a single clause, < 120 characters including the label, present tense or past tense — never future tense ("will", "going to")
  • No nested bullets, no code fences, no links, no emoji unless one is genuinely load-bearing
  • Skip anything the user already knows from the last 1-2 turns — focus on what they'd miss if they just walked back to the terminal

What to include (in priority order)

  1. Current focus — what file/task is actively being worked on right now
  2. Most recent concrete change — what just got written, edited, run, or decided
  3. Blocker or open question — anything waiting on the user, or that's stuck
  4. Next step — the very next action the agent intends to take, if obvious
  5. Notable side effects — files created, branches touched, processes started, only if relevant

What to leave out

  • Restating the original user request verbatim
  • Tool-call narration ("I ran ls, then grep, then…")
  • Anything that happened more than ~10 turns ago unless it's still load-bearing
  • Hedging, qualifiers, or meta-commentary about the summary itself

Example

User: /cmd-what

Good response:

- **Editing**: refactoring `auth/session.py` to drop the legacy cookie path
- **Tests**: 14/16 passing, 2 failing on token refresh edge case
- **Blocked**: need to know if expired refresh tokens should silently re-auth or 401
- **Next**: wire the chosen behavior into `refresh_token()` once you decide

Bad response (too verbose, narrates tool calls, future-tense, missing labels):

- I started by reading the auth module and then I grepped for cookie usage
- I'm planning to refactor the session handling but first I want to check with you
- The tests will probably need updates too

Codex Review Plan

Use codex exec as an independent reviewer on the plan currently in scope. Codex sees only the plan (no conversation history), so its critique is a genuine outside perspective — useful right before exiting plan mode and switching to auto execution.

When to use

  • Right before approving "Yes, and use auto mode" on an ExitPlanMode prompt
  • Any time the user says "review plan with codex", "second opinion from codex", or /cmd-codex-review-plan
  • After a non-trivial plan has been drafted and the user wants an outside critique before execution

Instructions

1. Locate the plan

Use the most recent plan in conversation context — typically the body of the last ExitPlanMode call, or the latest plan markdown the user is reviewing. If multiple candidates exist, ask the user which one. Do not invent or summarize — pass the plan verbatim.

2. Write the plan to a tempfile

Codex reads from stdin reliably only if the input is a file or a piped heredoc. Use a tempfile to avoid quoting issues:

PLAN_FILE=$(mktemp -t codex-plan.XXXXXX.md)
OUT_FILE=$(mktemp -t codex-review.XXXXXX.md)

Write the plan verbatim into $PLAN_FILE using the Write tool.

3. Run codex in headless review mode

codex exec \
  --sandbox read-only \
  --skip-git-repo-check \
  --color never \
  --output-last-message "$OUT_FILE" \
  - < "$PLAN_FILE"

Pass the prompt from Codex prompt as the initial argument, and the plan via stdin. Concretely:

codex exec \
  --sandbox read-only \
  --skip-git-repo-check \
  --color never \
  --output-last-message "$OUT_FILE" \
  "$(cat <<'PROMPT'
You are reviewing an implementation plan written by another coding agent (Claude).
The plan follows in the <stdin> block.

Your job:
1. Identify GAPS — requirements, edge cases, failure modes, or dependencies the plan misses.
2. Identify RISKS — fragile assumptions, ordering hazards, breaking-change risks, test coverage holes.
3. Identify SIMPLIFICATIONS — anything over-engineered, premature abstraction, or scope that should be deferred.
4. Identify CONCRETE FIXES — for each issue, suggest the smallest change that addresses it.

Constraints:
- Do NOT rewrite the whole plan. Critique it.
- Do NOT execute commands or modify files. This is a read-only review.
- Be specific: cite file paths, phase numbers, or step numbers from the plan.
- If the plan is solid, say so. Do not invent issues.

Output format (markdown):

## Verdict
One sentence: ship-as-is | minor-tweaks | needs-rework

## Gaps
- [bullet per gap, with phase/file reference]

## Risks
- [bullet per risk, with phase/file reference and severity: high/medium/low]

## Simplifications
- [bullet per simplification opportunity]

## Concrete Suggestions
- [numbered list of specific actionable changes to apply to the plan]

## What's Good
- [1-3 bullets on what the plan gets right — keep this honest, not flattery]
PROMPT
)" < "$PLAN_FILE"

Stream codex's progress to the user as it runs (don't background it — the user wants to watch). Capture the final message from $OUT_FILE.

4. Present codex's raw feedback

Show the contents of $OUT_FILE to the user verbatim under a heading:

## Codex review

> Independent review from `codex exec` — no conversation context, plan only.

<contents of $OUT_FILE>

5. Synthesize a revised plan

Read codex's suggestions and decide, item by item, what to apply. Then produce:

  1. Revised plan — the original plan with codex's accepted suggestions integrated.
  2. Changelog — a table showing each codex suggestion and what you did with it.

Don't blindly accept everything codex says. If a suggestion is wrong, irrelevant, or misunderstands context Claude has and codex doesn't, mark it rejected and explain why.

6. Cleanup

rm -f "$PLAN_FILE" "$OUT_FILE"

Codex prompt

The exact prompt is embedded in step 3. Key requirements when adapting it:

  • Tell codex it's reviewing another agent's plan (sets expectations for tone)
  • Demand specific references (phase numbers, file paths) — vague critique is useless
  • Explicitly forbid command execution (read-only review)
  • Require a verdict line so the user can triage at a glance
  • Allow codex to say "looks good" — don't force it to manufacture issues

Output format

After codex returns, present the result as three sections in order:

1. Codex's raw review

Quoted verbatim under a ## Codex review heading. Don't paraphrase — the user wants codex's voice, not Claude's summary of codex.

2. Revised plan

Same shape as the original plan (phases, action items, risks, etc.) with accepted changes integrated. Mark new or modified items with a leading marker so they're easy to spot:

MarkerMeaning
🆕New item added based on codex feedback
✏️Existing item modified based on codex feedback
➖Item removed based on codex feedback

3. Changelog

Table with one row per codex suggestion:

SCodex SuggestionDecisionReason
🟢Add rollback step to phase 2AppliedValid — the migration can fail mid-write
🟡Split phase 1 into two phasesPartialKept as one phase, but added explicit checkpoints
🔴Use a feature flag for the renameRejectedOverkill — the function is internal and has 2 callers

🟢 Applied · 🟡 Partial / modified · 🔴 Rejected · ⚪ Deferred to follow-up

End with a one-line tl;dr of net changes (e.g., "Added 1 phase, modified 2 steps, rejected 1 suggestion.").

Notes

  • Codex needs auth — if codex exec errors with auth issues, tell the user to run codex login and stop.
  • Read-only sandbox — codex cannot modify files even if it tries. This is intentional.
  • --skip-git-repo-check — lets the skill work outside git repos (e.g., scratch dirs).
  • --output-last-message — gives a clean final message without progress event noise.
  • Don't loop — one codex review per invocation. If the user wants another pass after revisions, they re-run the skill.
  • Plan mode caveat — if invoked from plan mode, the only file edits available are via Write/Edit on the tempfiles, which is fine. The Bash call to codex exec is allowed; it's just running an external tool, not modifying repo files.

Codex Review Unstaged

Use codex exec as an independent reviewer on the working-tree changes Claude just made. Codex sees only the summary + diff (no conversation history), so its critique catches things Claude rationalized into "good enough" during implementation. The output is a prioritized iteration plan — what to fix now, what to defer, what to reject.

When to use

  • After Claude finishes a non-trivial implementation pass and before commit
  • When the user says "review my changes with codex", "have codex check what I just did", or /cmd-codex-review-unstaged
  • As an outside cross-check before opening a PR — complements cmd-pr-follow-up (Claude self-review) and cmd-pr-edgecase (edge-case sweep) by adding a fresh pair of eyes that didn't write the code

Instructions

1. Build Claude's implementation summary

Write a short summary of what was just implemented. Keep it factual, not promotional:

  • What was the goal?
  • What files changed and why?
  • What design decisions were made (and what was rejected)?
  • What was deliberately deferred (TODOs, follow-ups, scope cuts)?
  • What was tested manually vs. covered by automated tests?

This summary anchors codex's review — without it, codex will judge the diff against a generic standard instead of the actual intent.

2. Capture the diff

Default scope: git diff HEAD — captures both staged and unstaged working-tree changes since the last commit.

DIFF_FILE=$(mktemp -t codex-diff.XXXXXX.patch)
SUMMARY_FILE=$(mktemp -t codex-summary.XXXXXX.md)
OUT_FILE=$(mktemp -t codex-review.XXXXXX.md)

git diff HEAD > "$DIFF_FILE"
git status --short >> "$DIFF_FILE"

If the user explicitly asks for unstaged-only or branch diff, swap in:

  • Unstaged only: git diff
  • Branch vs main: git diff main...HEAD
  • Include untracked: append git ls-files --others --exclude-standard separately

Write the summary from step 1 verbatim to $SUMMARY_FILE using the Write tool.

Sanity check before invoking codex:

  • If $DIFF_FILE is empty (no changes), tell the user there's nothing to review and stop.
  • If the diff is enormous (>50k lines), warn the user — codex will still run but the review quality drops on huge surfaces. Suggest narrowing scope (e.g., per-file or per-phase review).

3. Run codex in headless review mode

codex exec \
  --sandbox read-only \
  --skip-git-repo-check \
  --color never \
  --output-last-message "$OUT_FILE" \
  "$(cat <<PROMPT
You are reviewing a working-tree diff produced by another coding agent (Claude).

You will receive two files:
- $SUMMARY_FILE — Claude's own summary of what it implemented and why
- $DIFF_FILE — the raw \`git diff HEAD\` output plus \`git status --short\`

Read both before reviewing.

You also have access to two skill methodology references (read them before forming your review — they describe what to look for):
- ~/.codex/skills/cmd-pr-follow-up/SKILL.md — post-implementation reflection methodology (incomplete tasks, idiomatic concerns, modularity, simplification, comments/prose)
- ~/.codex/skills/cmd-pr-edgecase/SKILL.md — edge case and failure mode methodology (test gaps, malformed inputs, integration risks)

Apply BOTH methodologies to this diff. Then go further: look for issues those skills do not cover.

Your job:
1. **Correctness bugs** — logic errors, off-by-ones, wrong conditionals, race conditions, incorrect API usage. Cite file:line.
2. **Test gaps** — code paths added without tests, edge cases not covered, regression risks. Cite which test file should exist or be extended.
3. **Edge cases & failure modes** — what happens with empty input, null, concurrent calls, malformed data, network failure, partial state.
4. **Adjacent improvements** — things the diff touches that could be cleaned up in the same pass (dead code nearby, stale comments, naming inconsistencies).
5. **Simplification opportunities** — over-engineering, premature abstraction, defensive code for impossible states, dead branches.
6. **Idiomatic / convention violations** — where the diff diverges from the project's patterns (look at surrounding files in the diff for the local convention).
7. **What Claude likely missed** — read the summary critically. Did Claude defer something that actually matters? Claim test coverage that isn't there? Skip a constraint?
8. **What's good** — 1-3 honest bullets on what the implementation gets right. No flattery.

Constraints:
- Do NOT modify files. This is a read-only review.
- Be specific: cite \`file_path:line_number\` for every finding. Vague critique is useless.
- Rank findings by severity (critical / high / medium / low).
- If the implementation is solid, say so. Do not invent issues.

Output format (markdown):

## Verdict
One sentence: ship-as-is | minor-tweaks | needs-rework | blocked

## Critical / High
[bullets — bugs, missing tests for risky paths, broken invariants — with file:line]

## Medium
[bullets — edge cases, simplification opportunities, idiomatic concerns — with file:line]

## Low / Adjacent
[bullets — nice-to-haves, follow-up TODOs, stale-comment cleanup — with file:line]

## What Claude Likely Missed
[bullets called out from reading the summary against the diff]

## What's Good
[1-3 honest bullets]
PROMPT
)" < /dev/null

Stream codex's progress to the user as it runs. Capture the final review from $OUT_FILE.

Note: the prompt references $SUMMARY_FILE and $DIFF_FILE by absolute path. Since codex runs read-only in the same working directory, it will read those tempfiles when instructed. Use full paths in the heredoc (substituted by the shell) so codex can locate them without ambiguity.

4. Present codex's raw feedback

Show the contents of $OUT_FILE to the user verbatim under a heading:

## Codex review

> Independent review from `codex exec` — diff + summary only, no conversation context.

<contents of $OUT_FILE>

Do NOT paraphrase. The user wants codex's voice.

5. Synthesize an iteration plan

Read codex's findings and convert them into a concrete iteration plan. For each finding, decide:

  • Apply now — fix in this iteration before commit
  • Defer with TODO — legitimate but out of scope; add a TODO_TECHDEBT / TODO_IDEA comment in the relevant file
  • Reject — wrong, irrelevant, or codex misunderstood context Claude has

Don't blindly accept everything. If a finding is wrong (codex missed context, misread the diff, or proposed something contrary to the project's conventions), mark it rejected and explain why.

6. Cleanup

rm -f "$DIFF_FILE" "$SUMMARY_FILE" "$OUT_FILE"

Codex prompt

The exact prompt is embedded in step 3. Key requirements when adapting it:

  • Tell codex it's reviewing another agent's diff (sets tone)
  • Point codex at the skill methodology files in ~/.codex/skills/ — those are symlinked to the repo and codex can read them in read-only mode
  • Demand file:line references — vague critique is useless
  • Force a verdict line for triage at a glance
  • Allow codex to say "looks good" — no manufactured issues

Output format

After codex returns, present the result as three sections in order:

1. Codex's raw review

Quoted verbatim under a ## Codex review heading.

2. Iteration plan

Prioritized checklist Claude will execute (or propose to execute) next. Group by decision:

**Apply now (P0):**
- [ ] `path/to/file.py:42` — fix off-by-one in pagination loop
- [ ] `path/to/test_file.py` — add test for empty-list case

**Apply now (P1):**
- [ ] `path/to/other.py:88` — extract duplicated normalization helper

**Defer with TODO:**
- [ ] `path/to/file.py:120` — add `TODO_TECHDEBT` for connection pooling
      Why deferred: not blocking; needs separate evaluation of pgbouncer vs in-app pooling

**Rejected:**
- [ ] Codex suggestion: "Wrap entire handler in try/except"
      Why rejected: framework already converts exceptions to 500s; adding try/except would swallow stack traces

3. Changelog

Table summarizing every codex finding and what Claude decided:

SFindingSeverityDecisionReason
🟢Off-by-one in pagination at loader.py:42HighApply nowGenuine bug, codex caught it
🟡Connection poolingMediumDeferTODO_TECHDEBT added; out of scope
🔴Wrap handler in try/exceptLowRejectFramework handles it; would hide errors
🟢Add empty-list test in test_loader.pyMediumApply nowReal gap, test is small

🟢 Apply now · 🟡 Defer (with TODO) · 🔴 Reject · ⚪ Already addressed

End with a one-line tl;dr: e.g., "3 fixes to apply, 1 TODO to add, 1 suggestion rejected. Verdict: minor-tweaks."

6. Ask before applying

After presenting the iteration plan, ask the user whether to apply the P0/P1 fixes now or wait. Don't auto-apply — the user wants to see the plan first.

Notes

  • Codex needs auth — if codex exec errors with auth issues, tell the user to run codex login and stop.
  • Read-only sandbox — codex cannot modify files even if it tries. This is intentional.
  • Skill paths are symlinked — ~/.codex/skills/cmd-pr-follow-up/SKILL.md resolves to this repo via make link-skills. If codex reports it can't read those paths, the user may need to run make link-skills from ~/workspace/agent-skills.
  • Don't loop — one codex review per invocation. After applying fixes, the user can re-run for another pass if desired.
  • Untracked files — git diff HEAD does NOT show untracked files. If the implementation added new files that aren't yet tracked, mention this to the user and offer to git add -N them so they appear in the diff (intent-to-add stages the path without content, making the diff include them).
  • Companion skill — pair with cmd-codex-review-plan (pre-implementation plan review) for full coverage: codex reviews the plan before execution AND the diff after.

Simple Docs for Humans and Agents

Use this command to write or rewrite documentation so it is simple, fast to scan, and easy to execute.

Primary Goal

  • Bias toward simple docs.
  • Start with the shortest successful path.
  • Preserve original meaning and factual content while reordering for clarity.

Required Output Order

  1. Quickstart (always first)
  2. Main workflow
  3. Configuration/reference tables (when relevant)
  4. Alternative paths (only when they are true user/code path alternatives)
  5. Extra details at the end inside <details><summary>...</summary>...</details>

Approval Gate (Required)

  • Before editing any file, show a change preview for approval.
  • Use this exact preview structure for each file:
    • Additions
    • Removals
    • Changes
  • Show the concrete text to be added, removed, or changed.
  • Wait for explicit user approval before applying edits.
  • Apply only the approved edits.
  • If approval is not granted, do not modify files.

Core Rules

  • Optimize for both human readers and agent readers.
  • Maximize copy-paste command snippets.
  • Prefer short sections and concise language.
  • Use Markdown tables when information is structured.
  • Use Mermaid diagrams when they improve understanding of flow or architecture.
  • Avoid unnecessary sections.
  • Avoid "Optional" sections unless they represent an actual alternate path.
  • Put superfluous/background material at the end.
  • Add "Code Structure" only when repository layout helps task completion.

Command Block Rules (Strict)

  • Do not place comments inside bash code blocks.
  • Put labels outside code blocks.

Correct pattern:

Start the server:

make start_server

Run a command:

make run_command

Incorrect pattern (separate steps combined in one unlabeled block):

make start_server
make run_command

Section Defaults

Use only sections that add value for the specific document. Default section set:

  • Quickstart
  • Main Workflow
  • Configuration
  • Code Structure (only if useful)
  • Troubleshooting (only for real recurring issues)

Configuration Table Format

If environment variables or configuration values are required, use this format:

NamePurposeDefault
APP_ENVRuntime environmentdevelopment
API_URLBase URL for API callshttp://localhost:8000

Details Block Rule

Move long explanations, implementation notes, and low-priority reference material into details blocks:

<details>
<summary>Deep dive: request lifecycle</summary>

Detailed explanation here.

</details>

Deliverable

  • Return the final output as Markdown (.md).
  • Keep all important content, but simplify, reorder, and prioritize for quick execution.

Done Check

A quick self-interrogation to catch loose ends before declaring a task complete.

Instructions

Answer each question honestly. If anything is incomplete, say so and ask the user whether to continue.

1. Did you do everything the user asked?

  • Re-read the original request. Is every explicit ask addressed?
  • Did you skip or defer anything without telling the user?
  • Did you say "I'll also..." or "next, we should..." and then not do it?

2. Did you leave any loose ends?

  • Are there TODOs, FIXMEs, or placeholder values you introduced that should be resolved now?
  • Are there commented-out blocks, debug prints, or temporary stubs in the output?
  • Are there follow-up steps you mentioned but didn't take?

3. Did you handle side effects?

  • Are there related files, configs, or tests that should be updated but weren't?
  • Did any rename, move, or deletion leave dangling references?
  • If you added a skill/command/export — is it wired up and discoverable?

4. Are docs and metadata consistent?

  • If you added or changed something user-facing, is the README or AGENTS.md updated?
  • Are variable names, comments, and doc strings consistent with what shipped?

Output

If everything is done: say "Done — nothing left." in one line.

If something is incomplete: list each item as a bullet with what's missing and why, then ask:

Want me to continue and handle these now, or are you good?

Do not pad the response. One sentence per finding.

Markdown to Email HTML

Convert markdown into a complete, self-contained HTML email with inline CSS, table-based layout, and cross-client compatibility (Gmail, Outlook, Apple Mail).

Workflow

1. Determine input

  • If the user provided a file path, read the .md file
  • If the user provided inline markdown, use that directly
  • If neither, ask: "Which markdown file should I convert, or paste the content?"

2. Parse frontmatter

Extract YAML frontmatter from the top of the markdown. All fields are optional — use defaults for anything missing.

FieldDefaultDescription
preheader(none)Hidden inbox preview text
brand-color#2563ebPrimary accent (links, buttons, highlights)
heading-color#1a1a1ah1-h3 color
body-color#333333Body text color
background-color#f4f4f4Outer background
content-background#ffffffInner content area
font-familyArial, Helvetica, sans-serifSafe font stack
font-size16pxBase body size
line-height26pxBody line height (must be px for Outlook)
content-width600pxMax content width
header-logo(none)URL to logo image
footer-text(none)Footer text (unsubscribe, address, etc.)

3. Load references

Read the following files for technical rules and component templates:

  • references/email-html-compatibility.md — cross-client rules, document structure, quirks
  • references/email-components.md — HTML snippets with {{variable}} placeholders

4. Convert markdown to email HTML

Walk through the markdown content and generate email-safe HTML:

  • Use the Complete Wrapper template as the outer structure
  • Map each markdown element to its corresponding component template
  • Replace all {{variable}} placeholders with frontmatter values (or defaults)
  • Apply all CSS inline — no <style> blocks in <body>
  • Use tables for layout — never <div> for structure
  • Include Outlook conditional comments for max-width fix
  • Include preheader <div> if preheader is set
  • Include header with logo if header-logo is set
  • Include footer if footer-text is set

Markdown element mapping:

MarkdownEmail component
# HeadingHeading (h1-h4) with size per level
ParagraphParagraph with inline styles
**bold**, *italic*, ~~strike~~Inline <strong>, <em>, <del>
[text](url)Styled <a> with brand-color
- item / 1. itemUnordered/Ordered list
- [ ] taskTask list with Unicode checkboxes
`code`Inline code
```code block```Code block (dark theme)
> quoteBlockquote with left border
![alt](src)Image with explicit dimensions
---Horizontal rule
==highlight==<mark> with background color

Special directives (fenced with :::):

DirectiveBehavior
:::heroFull-width section with brand-color background, white text
:::callout[type]Highlighted box — type: info, tip, warning, danger
:::button[text](url)CTA button with VML fallback
:::button.secondary[text](url)Secondary button variant
:::centeredCenter-aligned text block
:::footerFooter section (overrides footer-text frontmatter)

5. Write output

  • If input was a file (e.g., newsletter.md), write to newsletter.html in the same directory
  • If input was inline, ask the user for an output path
  • The output must be a complete, self-contained HTML document — ready to paste into any email sending tool

6. Summary

Report:

  • Output file path
  • Theme values applied (brand color, font, content width)
  • Any warnings (e.g., unsupported markdown features skipped, images without dimensions)

Constraints

  • No <style> in <body> — Gmail strips it. Only allowed in <head> for responsive media queries.
  • No flexbox, grid, or CSS variables — not supported in email clients
  • No <button> elements — use <a> tags styled as buttons
  • No JavaScript — always blocked
  • No external CSS — everything inline
  • Tables for layout — <div> only for non-structural content (e.g., preheader hiding)
  • px units only — no rem, em, vh, vw, or calc()
  • Explicit dimensions on images — always set width and height
  • Absolute URLs — all src and href must be fully qualified

Example Input

---
preheader: "Your weekly update is here"
brand-color: "#6366f1"
header-logo: "https://example.com/logo.png"
footer-text: "Acme Inc. | 123 Main St | [Unsubscribe](https://example.com/unsub)"
---

:::hero
# Welcome to the Weekly Update
Everything you need to know, in one email.
:::

## What's New

We shipped **three major features** this week:

- Real-time collaboration
- Dark mode support
- Export to PDF

:::callout[tip]
Try dark mode by going to Settings > Appearance.
:::

:::button[Try it now](https://example.com/app)

## By the Numbers

| Metric | This Week | Last Week |
|---|---|---|
| Active Users | 12,450 | 11,200 |
| Signups | 890 | 720 |

> "This is the best update yet!" — A happy user

---

Thanks for reading. See you next week!

Create GitHub Issue from Conversation

Create a well-structured GitHub issue using gh CLI, populated with context from the current conversation.

Instructions

  1. Determine the repo -- confirm you're inside a git repo with a GitHub remote:

    gh repo view --json nameWithOwner -q '.nameWithOwner'
    

    If this fails, ask the user which repo to file against.

  2. Synthesize the conversation into a GitHub issue body following the structure below.

  3. Create the issue using gh:

    gh issue create --title "<concise title>" --body "$(cat <<'ISSUE_EOF'
    <issue body here>
    ISSUE_EOF
    )"
    
  4. Report back with the issue URL.

Issue Body Structure

Build the issue body in this exact order:

Section 1: What & Why

Open with a short (2-4 bullet) summary answering:

  • What needs to happen?
  • Why does it matter? (user pain, system constraint, business goal)

This section should stand alone -- a reader who stops here should understand the ask.

Section 2: Context & Discussion

This is the bulk of the issue. Capture everything relevant from our conversation:

  • Background -- what led to this discussion
  • Current behavior -- how things work today (or don't)
  • Desired behavior -- what success looks like
  • Constraints & decisions -- trade-offs we discussed, options we rejected and why
  • Technical details -- relevant code paths, configs, schemas, API shapes, error messages
  • Related work -- links to PRs, issues, docs, or external references mentioned

Formatting rules for this section:

  • Use ## Headings and ### Subheadings to organize by topic
  • Use bullet points over paragraphs
  • Use markdown tables for comparisons, option matrices, or structured data
  • Embed images/screenshots if any were shared (use ![alt](url) syntax)
  • Wrap code snippets, commands, file paths, and config in fenced code blocks with language tags
  • Use <details><summary>...</summary>...</details> to collapse verbose content (logs, full configs, large code blocks) so the issue stays scannable
  • Do NOT strip context -- preserve the substance of our discussion, but reorganize it logically

Section 3: Implementation Plan

End with the plan we've aligned on (even if rough). Frame it for a future agent or developer picking this up cold:

  • Number the steps
  • Call out key files to create or modify
  • Note any open questions or decisions still TBD (prefix with [ ])
  • If there are dependencies between steps, make the order explicit
  • If we haven't aligned on a plan yet, write ## Implementation Plan\n\n_TBD -- no plan agreed on yet._

Labels & Assignment (optional)

  • If the conversation implies a category (bug, feature, enhancement, tech-debt), add --label flags
  • Do NOT assign unless the user explicitly asks

Style Rules

  • Title: imperative mood, under 70 chars (e.g., "Add retry logic to webhook delivery")
  • No fluff: skip filler phrases like "It would be great if..." -- be direct
  • Bias to structure: headers > paragraphs, bullets > prose, tables > lists-of-pairs
  • Preserve signal: don't summarize away details that a future implementer would need
  • Mark uncertainty: if something was discussed but not decided, say so explicitly with "TBD" or an open checkbox [ ]

Golden Tests

Golden (snapshot) tests capture the exact output of a pipeline or subsystem as a reference file, then fail any run that deviates from it. They are the highest-fidelity regression check: if anything in the pipeline changes — parsing, mapping, migration, export — the diff tells you exactly what shifted.

Reference Implementation

The paradigm for this skill comes from boredm/gint_to_boredm. Read it before adapting anything:

  • Makefile targets: makefiles/golden.mk
  • Snapshot scripts: scripts/golden_thompson.py
  • Fixtures: server/tests/fixtures/
  • Workflow golden: golden.md

The Five Setup Questions

Answer these before writing any code or Makefile targets.

1. What is the fixture / on-device schema?

The input data the pipeline runs against. Must be:

  • Checked in to the repo (or clearly documented how to obtain it)
  • Small enough to run in CI without special infra
  • Representative of real edge cases, not just happy-path data

In boredm: real .gpj files in thompson_sample/ (binary, not committed to the main repo — seeded via make seed-thompson).

2. What is the API under test?

How the system is invoked in the golden test. Three patterns:

PatternUse whenExample
Direct function callTesting a pure transformationschema_grouping.build_grouping_outputs(schemas)
HTTP endpoint via TestClientTesting a route end-to-endPOST /api/units/generate-migrations/{schema}
Full workflow via manifestTesting the entire pipelineRun wf1–wf7, read manifest from disk

Avoid mixing patterns in the same golden — pick the right scope.

3. What is the golden truth dataset?

The reference snapshot file. Key design choices:

Semantic golden (single compact file):

  • Extracts a stable subset of the output (row counts, field counts, match types, transformation types)
  • Intentionally excludes volatile fields: timestamps, file paths, binary hashes, job IDs
  • Sorts all dict keys for deterministic JSON output
  • Good for: full-pipeline end-to-end tests

Phase-level goldens (per-schema per-phase files):

  • One file per {phase}_{schema}.json — e.g., wf1_grouping_file_group_1.json
  • Captures the intermediate state after each workflow phase
  • Good for: pinpointing which phase introduced a regression

Unit-test-style fixture (step-by-step JSON):

  • Inline expected values alongside inputs in the same file
  • Steps: baseline → mutation → restored
  • Good for: idempotency tests, lifecycle tests

4. When and how do you update it?

Never silently. The update workflow must be:

  1. Run the full pipeline
  2. Inspect the diff (unified diff, colorized)
  3. Decide: expected change or regression?
  4. Only then run the explicit update command

Makefile targets enforce this:

golden-{dataset}-verify   # compare without running pipeline
golden-{dataset}-update   # rewrite golden from latest output
golden-{dataset}-wf       # run pipeline + compare (fails on diff)

5. How do you handle failures, updates, false positives, and false negatives?

ScenarioAction
Expected change (feature added, behavior improved)Inspect diff → make golden-{dataset}-update → commit both code and golden
Regression (pipeline broke something)Fix root cause, never update golden to hide it
False positive (volatile field leaked into snapshot)Remove volatile field from snapshot extractor, not from golden
False negative (golden too coarse, misses real change)Add a phase-level golden or tighten the snapshot to cover the missed surface

Makefile Target Naming Convention

Follow this naming pattern. Replace {dataset} with the fixture dataset name (e.g., thompson).

## Golden Tests
golden-{dataset}-test          ## Unit-test-like suite; pytest against JSON fixtures; no server needed
golden-{dataset}-wf            ## Full end-to-end workflow + semantic manifest comparison; server required
golden-{dataset}-verify        ## Compare latest manifest to golden without re-running workflow
golden-{dataset}-update        ## Rewrite semantic golden from latest manifest output
golden-{dataset}-phase-verify  ## Compare all phase-level goldens ({phase}_{schema}.json files)
golden-{dataset}-phase-update  ## Update all phase-level goldens from latest manifest

Separate into two modes in the help output:

[Golden — unit-like]
  golden-{dataset}-test         Fast; no server; pytest fixtures

[Golden — full workflow]
  golden-{dataset}-wf           Slow; server required; full e2e
  golden-{dataset}-verify       Compare only; no re-run
  golden-{dataset}-update       Rewrite golden (inspect diff first!)

Snapshot Storage Layout

server/tests/fixtures/
  {dataset}_semantic_wf_verification_golden.json   # single compact semantic golden
  {dataset}_schema_grouping_golden.json            # unit-test-style fixture
  {dataset}_unit_migration_golden.json             # lifecycle fixture with steps
  {dataset}_phase_goldens/
    wf1_grouping_{schema}.json
    wf2_mapping_{schema}.json
    wf3_units_{schema}.json
    wf3b_migrations_{schema}.json
    wf4_normalized_{schema}.json
    wf5_qc_{schema}.json
    wf6_exports_{schema}.json
    wf7_insights_{schema}.json

Snapshot Script Pattern

A standalone script (not pytest) manages semantic and phase goldens. Key functions:

def build_snapshot(manifest: dict) -> dict:
    """Extract stable, deterministic subset from full pipeline manifest."""
    # 1. Pull only the fields you care about (row counts, match types, etc.)
    # 2. Exclude volatile fields: timestamps, paths, binary hashes, job IDs
    # 3. Sort all nested dicts for deterministic output

def compare_to_golden(snapshot: dict, golden_path: Path) -> bool:
    """Unified diff, colorized. Returns True if match."""
    # Uses difflib.unified_diff with red/green color codes

def write_golden(golden_path: Path, snapshot: dict) -> None:
    """Rewrite golden file. Sort keys, trailing newline."""
    # json.dumps(data, indent=2, sort_keys=True) + "\n"

CLI flags:

--verify           compare latest manifest to golden (default)
--update-golden    rewrite semantic golden
--phase-goldens    verify per-phase files
--update-phase-goldens  rewrite per-phase files
--schema           target a specific schema only
--all-schemas      run across all schemas

What NOT to Put in a Golden

These leak into diffs and cause false positives:

  • Timestamps (created_at, updated_at, dataset directory names with dates)
  • File system paths (absolute or dataset-relative)
  • Binary content or checksums
  • Cache fingerprints, job IDs, run UUIDs
  • Full JSON payloads when a count or summary suffices

Adding Golden Tests to a New Repo

  1. Answer the five setup questions above
  2. Seed fixture data and document the seed command (make seed-{dataset})
  3. Write the snapshot extractor script (scripts/golden_{dataset}.py)
  4. Write pytest fixtures for unit-test-like checks (server/tests/test_*_golden.py)
  5. Add Makefile targets following the naming convention above
  6. Run once, capture baseline, commit golden files alongside code
  7. Add to CI: fail build on golden diff, never auto-update in CI

Latest Message

Persist the last agent message to disk for cross-agent visibility.

Instructions

  1. Parse the user's input after /cmd-latest-msg.

  2. help (or no argument) — print usage and stop:

    Usage:
      /cmd-latest-msg save             — save your last message
      /cmd-latest-msg use              — read latest from the current agent
      /cmd-latest-msg use <agent>      — read latest from claude|codex|gemini
      /cmd-latest-msg help             — show this usage
    
  3. save — save the last assistant message:

    a. Determine which agent you are from runtime context:

    • Claude Code → claude
    • Codex CLI → codex
    • Gemini CLI → gemini
    • If inference fails, default to codex

    b. Create the output directory:

    mkdir -p /tmp/agents/<agent>
    

    c. Capture your last assistant message — the response you gave immediately before the user invoked this skill.

    d. Write it to two files using the Write tool:

    • /tmp/agents/<agent>/latest.md — always overwrite
    • /tmp/agents/<agent>/<unix_timestamp>.md — timestamped copy (use date +%s to get the timestamp)

    e. Confirm with:

    Stored to:
      /tmp/agents/<agent>/latest.md
      /tmp/agents/<agent>/<timestamp>.md
    
  4. use — display the latest message for the current agent:

    a. Infer the current agent using the same runtime-context rules as save.

    b. Read and display /tmp/agents/<agent>/latest.md.

    c. If the file doesn't exist, say: No messages found for <agent>.

  5. use <agent> — display another agent's latest message:

    a. Validate <agent> is one of: claude, codex, gemini.

    b. Read and display /tmp/agents/<agent>/latest.md.

    c. If the file doesn't exist, say: No messages found for <agent>.

Makefile Foundation Review

Review the current repository's Makefile foundation, then recommend a small, high-quality next iteration. This is a review-and-proposal skill: do not modify files, commit, install dependencies, or publish anything until the user explicitly approves the proposed changes.

When invoked in /Users/olshansky/workspace/agent-skills, the primary implementation target is skills/cmd-makefile/ and its templates/modules. In any other repository, target that repository's Makefile, helper directory, templates, tests, and documentation instead.

Operating contract

  1. Inspect first; infer nothing from filenames alone.
  2. Ask one concise batch of questions after discovery when choices materially affect the recommendation.
  3. Report evidence, proposed changes, and tradeoffs before editing.
  4. Wait for explicit approval. “Looks good” or “go ahead” approves the presented scope; new or materially broader work needs a new proposal.
  5. After approval, make only the approved changes and verify them. If approval is not given, leave the worktree unchanged.

Do not treat a clean worktree as permission to edit. Do not automatically update generated dashboards, symlinks, installed skills, remote repositories, or unrelated files.

Discovery pass

Use the repository's documented workflow first. Read AGENTS.md, README.md, CONTRIBUTING.md, and any tool-specific instruction files that apply. Check make help before suggesting raw commands when a Makefile exists.

Capture these four evidence groups:

1. Current worktree

  • git status --short --branch
  • git diff -- for unstaged tracked changes
  • git diff --cached -- for staged changes
  • Contents of relevant untracked files, without broadening beyond the repository

Describe what is already in progress and preserve unrelated changes.

2. Recent history

Read the last one or two commits with git log -2 --stat --oneline and inspect relevant patches with git show. Look for patterns the repository has recently adopted or intentionally removed. Do not propose reverting a recent decision without explaining the evidence.

3. Makefile foundation

Locate and read:

  • Root Makefile and included makefiles/*.mk or equivalent helper files.
  • Template directories and shared modules.
  • Scripts invoked by Make targets.
  • Tests, CI workflows, and docs that treat Make targets as a command contract.
  • Relevant history for Makefile/helper paths, not only the latest repository commits.

Trace public targets to their recipes and dependencies. Check for duplicated logic, hidden write paths, stale docs, inconsistent naming, unsafe shell behavior, missing preflight checks, environment precedence bugs, poor help output, and verification gaps.

For this repository specifically, also inspect skills/cmd-makefile/SKILL.md, skills/cmd-makefile/reference.md, skills/cmd-makefile/modules/, and every applicable file under skills/cmd-makefile/templates/ before suggesting changes to the skill foundation.

4. Repository-specific best practices

Identify the stack from actual files and commands: for example Swift/Xcode, FastAPI/uv, Node, Go, Flutter, Electron, a static site, or a database-backed service. Read the repository's own conventions before applying generic advice.

When local evidence is insufficient or the recommendation depends on a changing toolchain, consult authoritative current documentation for that stack. Prefer official documentation and primary sources. State which guidance is a local convention, which is official guidance, and which is an informed recommendation.

Questions

Ask only questions whose answers would change the proposal. Ask them in one batch after discovery, normally no more than five:

  • Is the intended scope the current repository only, the reusable cmd-makefile foundation, or both?
  • Should the next iteration prioritize code structure, helpers/tools, regression testing, docs/references, or Makefile helpers?
  • Should compatibility aliases remain, or may obsolete targets and templates be removed?
  • Is modularization appropriate for this repository's current size and expected growth?
  • Are there constraints on supported platforms, shells, CI, or external tools?

Skip questions answered by the repository or by the user's request. If no answer is needed, proceed with clearly labeled assumptions.

Proposal format

Lead with the recommendation. Then provide:

  1. Evidence — worktree state, recent commits, relevant helper/template paths, and stack-specific guidance.
  2. Foundation assessment — what is strong, what is duplicated, what is missing, and what should remain untouched.
  3. Proposed file plan — one row per file, with action (add, edit, remove, or split), exact responsibility, and reason. Keep the user's long-term categories in separate files:
    • code structure
    • helpers and tools
    • regression testing and verification
    • docs and references
    • Makefile helpers
  4. Prioritized changes — use 🔴, 🟠, 🟡, 🟢, or ✅ severity/status and distinguish required, recommended, and optional work.
  5. Risks and compatibility — target renames, callers, CI, generated artifacts, shell/platform assumptions, and migration steps.
  6. Verification plan — exact project-native checks, including dry runs and focused tests where appropriate.
  7. Approval request — ask the user to approve the exact scope, or identify which proposal rows to apply.

Do not present an unverified claim as a fact. If a check could not run, say why and mark the resulting uncertainty.

Approval and implementation

Only after explicit approval:

  • Edit the smallest set of files that implements the approved proposal.
  • Preserve unrelated worktree changes and inspect the diff before any generated-file update.
  • Carry forward all Makefile write paths, prerequisites, environment handling, and compatibility behavior unless removal was approved.
  • Keep reusable templates and helper modules in separate files with one clear responsibility each.
  • Update README/catalog metadata when a skill or public template changes, as required by the repository's instructions.
  • Run git diff --check, the project's documented checks, and focused Makefile validation such as make help, make help-unclassified, and relevant make -n dry runs.
  • Report exactly what changed, what passed, what was not run, and any remaining review item.

Never commit or push as part of this skill unless the user separately asks for that after implementation.

Makefile Helper

Create Makefiles that are simple, discoverable, and maintainable.

Core Principles

  1. Default to rich help - Use categorized help with emoji headers unless user requests minimal
  2. Default Chrome extensions to modular - Use the modular makefiles/*.mk layout with shared colors/help for Chrome extension projects unless the repo is truly tiny
  3. Ask about structure upfront - For new Makefiles, ask: "Flat or modular? Rich help or minimal?"
  4. Follow existing conventions - Match the project's style if Makefile already exists
  5. Don't over-engineer - Solve the immediate need, not hypothetical futures
  6. Use uv run - Always run Python commands via uv run for venv context
  7. Explain decisions - If choosing flat/minimal, explain why before generating

When to Use This Skill

  • Creating a new Makefile for a project
  • Adding specific targets to an existing Makefile
  • Improving/refactoring an existing Makefile
  • Setting up CI/CD make targets
  • Distributing pre-built binaries via GitHub Releases

Quick Start

For new projects, use the appropriate template:

Project TypeTemplateComplexityAsks upfront
Any projecttemplates/base.mkMinimal—
Python with uvtemplates/python-uv.mkStandard—
Python FastAPItemplates/python-fastapi.mkFull-featuredtest split? prod target? HEALTH_PATH?
PostgreSQL + Alembictemplates/postgres.mkStandardPG_PORT (5433 default)? soft vs HARD reset?
Node.jstemplates/nodejs.mkStandard—
Gotemplates/go.mkStandard—
Chrome Extensiontemplates/chrome-extension.mkModular—
Flutter Apptemplates/flutter.mkModular—
Electron Apptemplates/electron.mkModular—
Static Site (HTML/CSS/JS)templates/static-site.mkStandardDEPLOY_MODE (rsync/gh-pages/netlify/vercel/none)?

For templates in the "Asks upfront" column, run the Phase 2 interactive questions in §"Interaction Pattern" before scaffolding. Companion files:

  • templates/python-fastapi-env/.template.env → project's .template.env
  • templates/python-fastapi-scripts/export_openapi_spec.py → scripts/export_openapi_spec.py
  • templates/postgres-env/.template.env → merge into project's .template.env (don't ship two)

Chrome Extension Structure

The chrome extension template uses a modular structure:

Makefile                              # Main file with help + includes
makefiles/
  colors.mk                           # ANSI colors & print helpers
  common.mk                           # Shell flags, VERBOSE mode, guards
  build.mk                            # Build zip, version bump, releases
  dev.mk                              # Lint, clean, install
  test.mk                             # Unit tests, E2E tests, coverage
  env.mk                              # Environment setup, dependency checks

Copy from templates/chrome-extension-modules/ to your project's makefiles/ directory.

Key features:

  • Use makefiles/colors.mk for ANSI color output and header helpers.
  • Use makefiles/common.mk for shell flags, guard rails, and shared variables.
  • Use makefiles/env.mk for environment checks and dependency sanity.
  • Use makefiles/build.mk for build/package/release targets.
  • Use makefiles/dev.mk for install, watch, clean, and other local workflows.
  • Use makefiles/test.mk for typecheck, unit, and E2E targets when present.
  • build-release - Version bump menu (major/minor/patch) + zip for Chrome Web Store
  • build-beta - (Optional) GitHub releases with gh CLI
  • test-unit / test-e2e - Vitest + Playwright testing
  • test-unit-<module> / test-e2e-<module> - Per-module test targets
  • VERBOSE=1 make <target> - Show commands for debugging

Flutter App Structure

Makefile                    # Main file with help + includes
makefiles/
  colors.mk                # ANSI colors & print helpers
  common.mk                # Shell flags, VERBOSE mode, guards
  dev.mk                   # Setup, run simulator/device, devices, clean
  build.mk                 # iOS/Android builds (IPA, APK, AAB)
  deploy.mk                # TestFlight upload
  lint.mk                  # Dart analyze & format

Copy from templates/flutter-modules/ to your project's makefiles/ directory.

Key features:

  • flutter-run-ios auto-boots simulator and waits for it
  • flutter-run-android auto-launches emulator and waits for it
  • flutter-run-device auto-detects or uses FLUTTER_IOS_DEVICE / FLUTTER_ANDROID_DEVICE
  • flutter-build-ipa + flutter-export-ipa + flutter-deploy-testflight full iOS release workflow
  • flutter-export-ipa re-exports IPA from existing archive without rebuilding
  • _check-asc-app pre-flight App Store Connect validation (with ASC_API_KEY/ASC_API_ISSUER)
  • flutter-lint FIX=true Dart formatting with FIX pattern
  • VERBOSE=1 make <target> show commands for debugging

Electron App Structure

Makefile                    # Main file with help + includes
makefiles/
  colors.mk                # ANSI colors & print helpers
  common.mk                # Shell flags, VERBOSE mode, guards
  dev.mk                   # Setup, dev server, debug, clean
  build.mk                 # Pack-check, dist (mac/win/linux), publish
  lint.mk                  # ESLint, Prettier, TypeScript, tests

Copy from templates/electron-modules/ to your project's makefiles/ directory.

Key features:

  • electron-dev starts dev mode with hot-reload
  • electron-debug launches with DevTools open
  • electron-clean single target that removes artifacts, node_modules, and lock file
  • electron-pack-check smoke-tests that the app loads without errors
  • electron-dist-mac / electron-dist-win / electron-dist-linux cross-platform builds
  • electron-dist-all builds for all platforms in one shot
  • electron-publish publishes to GitHub Releases (requires GH_TOKEN)
  • electron-lint FIX=true ESLint + Prettier with auto-fix pattern
  • electron-typecheck TypeScript type checking
  • VERBOSE=1 make <target> show commands for debugging

Static Site (HTML/CSS/JS)

Plain static sites — landing pages, marketing pages, docs — with no bundler or SSR. Uses npx --yes for tooling so contributors don't need a local package.json or node_modules.

Copy templates/static-site.mk to your project root as Makefile.

Targets use site-* and dev-* prefixes (per §"Naming Conventions"). The template is deliberately slim — lint/link-check/image-optimization targets were cut because they're rarely run locally on a marketing page and collapse under the "too many granular dev-* quality targets" pitfall. Add them back only if a specific project needs them.

Key features:

  • site-serve - local HTTP server via python3 -m http.server (falls back to npx serve). Override with make site-serve PORT=9000 HOST=0.0.0.0.
  • site-open - open $(ENTRY) (default index.html) in the default browser (macOS open / Linux xdg-open).
  • site-status - print site dir, entry, detected HTML pages, and tooling availability.
  • dev-format - prettier --write across HTML/CSS/JS via npx --yes. No global install required, no FIX=true gate — always writes (formatting check-only is CI's job, not a local ergonomic).
  • dev-asset-report - top 20 largest files (finds accidentally-committed hero images, uncompressed GIFs).
  • dev-build - copies site into $(BUILD_DIR) (default dist/) via rsync with sensible excludes, then optionally minifies HTML/CSS/JS via html-minifier-terser (silently skipped if unavailable).
  • dev-deploy - depends on dev-build; dispatches on DEPLOY_MODE (rsync | gh-pages | netlify | vercel | none). Fails fast with install hint if the selected tool is missing.
  • dev-clean - removes $(BUILD_DIR)/.

Config knobs (?= — override on command line): SITE_DIR, PORT, HOST, ENTRY, BUILD_DIR, DEPLOY_MODE, RSYNC_DEST.

PostgreSQL + Alembic

Standalone template for database operations. Use alongside python-fastapi.mk for a full stack, or independently for any Python project with PostgreSQL.

Copy templates/postgres.mk to your project root (or include it from your main Makefile).

Key features:

  • db-start / db-stop / db-clean via plain docker run (default) with health-check wait loop. Docker Compose variant is commented at the bottom of the template for multi-service setups.
  • db-init composite target (start + migrate).
  • db-reset has two flavors via HARD flag:
    • HARD=false (default): kill connections → DROP DATABASE → CREATE → migrate. Fast, preserves container+volume.
    • HARD=true: docker rm -f container + docker volume rm -f + re-init. Use when container/volume itself is in a broken state.
  • db-migrate / db-revision Alembic migrations via uv run alembic; all Alembic recipes inline-source .env (via _check-env guard) so a stale shell DATABASE_URL can't override the configured value.
  • db-migration-current / db-migration-history / db-migration-check introspection.
  • db-shell (psql) / db-pgcli / db-pgweb shell access.
  • db-pgcli strips the SQLAlchemy +psycopg dialect marker before handing the URL to pgcli (pgcli doesn't understand dialect markers).
  • env-template bootstrap target that copies .template.env → .env without overwriting.
  • db-logs / db-seed utilities.
  • All config via ?= variables (PG_CONTAINER, PG_DB, PG_USER, PG_PASSWORD, PG_PORT=5433, PG_IMAGE).
  • Port 5433 by default to dodge host Homebrew Postgres on 5432. Override with make db-start PG_PORT=5432 if your machine is clean.
  • Driver: template targets psycopg[binary]>=3 (psycopg3). SQLAlchemy needs the postgresql+psycopg:// dialect marker; add a pydantic-settings validator that normalizes postgres:// / postgresql:// → postgresql+psycopg:// so Render's managed DB URL works verbatim.

Interaction Pattern (Phased)

Run these phases top-to-bottom on any Makefile scaffolding / refactor request. Do Phase 2 (Interactive questions) BEFORE writing any file — the answers drive which template variants to emit.

Phase 1 — Discovery

  1. Is there already a Makefile? Read it first — match its conventions.
  2. What stack / language? (Python+uv, FastAPI+Postgres, Node, Go, …)
  3. What's the deployment target? (Render, Fly, Vercel, self-hosted, …) — affects run-api-prod.
  4. How big is the project today, and how big will it reasonably grow? (≥5 targets expected → modular.)

Phase 2 — Interactive questions (ask in ONE batch via AskUserQuestion)

Ask up front rather than iterating. Typical questions:

  • Structure: flat single file or modular (makefiles/*.mk)?
  • Help style: rich categorized help with emoji headers, or minimal?
  • Postgres port (if Postgres used): 5433 (default, dodges host Homebrew Postgres on 5432) or 5432?
  • Test granularity: single dev-test (small/medium projects) or split test-unit / test-integration / test-e2e (larger projects)?
  • Prod runtime: need a run-api-prod target against a remote DB (Render/Fly/etc.)?
  • OpenAPI spec export (FastAPI): always include api-export-spec unless user declines — enables client SDK generation and spec-diff in CI.

Skip questions whose answer is already implied by an existing Makefile or strong project signal.

Phase 3 — Scaffold

Emit (in this order):

  1. Makefile + makefiles/*.mk (if modular).
  2. .template.env at repo root (committed).
  3. .env is NOT created — leave that to make env-template. Add .env to .gitignore if not already there.
  4. .env.prod — if run-api-prod was requested, confirm .env.prod is in .gitignore (it MUST be — production credentials).
  5. scripts/export_openapi_spec.py (if FastAPI + api-export-spec).

Phase 4 — Verify

  • make help — clean categorized output.
  • make help-unclassified — should be empty or minimal.
  • make -n run-api-local db-migrate api-export-spec — dry-run the critical paths.
  • Grep for any _check-env / _check-postgres guards you added to confirm they fire when expected.

Naming Conventions

Use kebab-case with consistent prefix-based grouping:

# Good - consistent prefixes (hyphens, not underscores)
build-release, build-zip, build-clean    # Build tasks
dev-run, dev-clean                       # Development tasks
db-start, db-stop, db-migrate            # Database tasks
env-local, env-prod, env-show            # Environment tasks

# Internal targets - prefix with underscore to hide from help
_build-zip-internal, _prompt-version     # Not shown in make help

# Bad - inconsistent
run-dev, localEnv, test_net
build_release, dev_test                  # Underscores - don't use

Exception — universal unprefixed names. A handful of names are so de-facto standard across ecosystems (npm, cargo, go, make itself) that prefixing them with dev- adds noise without adding signal. Keep these unprefixed:

  • test (not dev-test)
  • build (not dev-build) — only if the project has no competing build-* group
  • run (not dev-run) — same caveat
  • format / lint — same caveat; if you have dev-format already, stay consistent within the project

Rule of thumb: if the unprefixed name would collide with a prefix group you already have (e.g., already have build-release, build-zip), keep the dev- prefix for consistency. Otherwise, drop it.

Name targets after the action, not the tool:

# Good - describes what it does
remove-bg          # Removes background from image
format-code        # Formats code
lint-check         # Runs linting

# Bad - names the tool
rembg              # What does this do?
prettier           # Is this running prettier or configuring it?
eslint             # Unclear

Key Patterns

Binary Distribution

For projects distributed as pre-built binaries via GitHub Releases:

GITHUB_REPO ?= owner/repo
OS := $(shell uname -s | tr '[:upper:]' '[:lower:]')
ARCH := $(shell uname -m | sed 's/x86_64/amd64/' | sed 's/aarch64/arm64/')

.PHONY: install-cli
install-cli: ## Download and install CLI from latest GitHub release
	@RELEASE=$$(curl -fsSL https://api.github.com/repos/$(GITHUB_REPO)/releases/latest | grep tag_name | cut -d'"' -f4); \
	echo "Installing $$RELEASE for $(OS)/$(ARCH)..."; \
	curl -fsSL -o ~/.local/bin/cli \
		"https://github.com/$(GITHUB_REPO)/releases/download/$$RELEASE/cli-$(OS)-$(ARCH)"; \
	chmod +x ~/.local/bin/cli

Key considerations:

  • Detect OS and architecture automatically
  • Download from GitHub Releases (no Python/uv required)
  • Install to ~/.local/bin (user-writable, in PATH)
  • Preserve existing config files during updates

Always Use uv run for Python

# Good - uses uv run with ruff (modern tooling)
dev-check:
	uv run ruff check src/ tests/
	uv run ruff format --check src/ tests/
	uv run mypy src/

dev-format:
	uv run ruff check --fix src/ tests/
	uv run ruff format src/ tests/

# Bad - relies on manual venv activation
dev-format:
	ruff format .

Use uv sync (not pip install)

For Python projects, treat pyproject.toml and uv.lock as the source of truth. Do not add pip install or requirements.txt fallback guidance to uv-based templates.

env-install:
	uv sync  # Uses pyproject.toml + lock file

Categorized Help (for 5+ targets)

Help is generated, never hand-written. Declare a section with ##@, document targets with ##, and the renderer does the rest — see Help System.

##@ 🚀 API

api-run: ## Start server on port `$(PORT)` (`uvicorn --reload`)
api-run-prod: ## Start without reload, binds `0.0.0.0` (⚠️ PROD)

Makefile ordering rule - help targets go LAST, just before catch-all:

  1. Configuration (?= variables)
  2. HELP_* configuration (HELP_TITLE, HELP_ICON, HELP_VARS, …)
  3. Imports (include ./makefiles/*.mk) — include order IS help section order
  4. Main targets (grouped by function, each group under a ##@ header)
  5. help: and help-unclassified: targets (or include ./makefiles/help.mk)
  6. Catch-all %: rule (absolute last)

Preflight Checks

_check-docker:
	@docker info >/dev/null 2>&1 || { echo "Docker not running"; exit 1; }

db-start: _check-docker  # Runs check first
	docker compose up -d

External Tool Dependencies

When a target requires an external tool (not a system service):

  • Don't create public install targets (no make install-foo)
  • Use internal check as dependency (prefix with _, no ## comment)
  • Show install command on failure - tell user what to run, don't do it for them
# Internal check - hidden from help (no ##)
_check-rembg:
	@command -v rembg >/dev/null 2>&1 || { \
		printf "$(RED)$(CROSS) rembg not installed$(RESET)\n"; \
		printf "$(YELLOW)Run: uv tool install \"rembg[cli]\"$(RESET)\n"; \
		exit 1; \
	}

# Public target - uses check as dependency
.PHONY: remove-bg
remove-bg: _check-rembg ## Remove background from image
	rembg i "$(IN)" "$(OUT)"

Key points:

  • Name target after the action (remove-bg), not the tool (rembg)
  • Check runs automatically - user just runs make remove-bg
  • If tool missing, user sees exactly what command to run

Env File Loading

Primary recommendation: inline-source per recipe. This is the only pattern that overrides stale shell-exported vars, which is the pitfall you'll actually hit in practice.

# Inline-source: recipe's DATABASE_URL comes from .env, not the user's shell
db-upgrade:
	@set -a && . ./.env && set +a && uv run python -m alembic upgrade head

run-api-local:
	@set -a && . ./.env && set +a && uv run uvicorn app.main:app --reload

Per-target override (e.g., test env, prod env):

# Allow: E2E_ENV=.test.env make test-e2e
test-e2e:
	@set -a && . "$${E2E_ENV:-.env}" && set +a && uv run pytest tests/e2e/

Secondary (simpler but weaker): top-of-Makefile load. Fine for projects where no one exports the same vars in their shell. Does not override an already-exported shell var — so don't use this for DB URLs or anything that commonly lives in shell profiles.

# At top of Makefile, after .DEFAULT_GOAL
-include .env
.EXPORT_ALL_VARIABLES:

⚠️ Shell-override footgun. If a user has export DATABASE_URL=... in their .zshrc (or manually in the current shell), the -include form silently loses: their shell env wins over .env. Alembic/uvicorn will hit the wrong DB with zero warning. Use the inline-source pattern for any recipe that depends on a specific .env value.

.env / .template.env Bootstrap

Always ship a .template.env. Never ship a .env.

  • .template.env is committed to git. It tracks the schema of env vars the project expects — every new env var in code gets a placeholder here in the same PR.
  • .env is gitignored. Each developer fills in real values locally.
  • Every recipe that sources .env should preflight-check its existence and print a friendly "run make env-template" if missing.
  • Ship a make env-template target that copies .template.env → .env but never overwrites an existing .env.
_check-env:
	@if [ ! -f .env ]; then \
		printf "$(RED)$(CROSS) .env not found$(RESET)\n"; \
		printf "$(YELLOW)$(INFO) Run 'make env-template' or 'cp .template.env .env'$(RESET)\n"; \
		exit 1; \
	fi

env-template: ## Create .env from .template.env (safe: never overwrites)
	@if [ -f .env ]; then \
		printf "$(YELLOW)$(INFO) .env already exists — leaving it alone$(RESET)\n"; \
	elif [ ! -f .template.env ]; then \
		printf "$(RED)$(CROSS) .template.env not found$(RESET)\n"; exit 1; \
	else \
		cp .template.env .env; \
		printf "$(GREEN)$(CHECK) Created .env from .template.env — fill in real values$(RESET)\n"; \
	fi

run-api-local: _check-env
	@set -a && . ./.env && set +a && uv run uvicorn app.main:app --reload

Why not just -include .env at the top of the Makefile? See §"Env File Loading" above — -include silently loses to already-exported shell vars. The .template.env + _check-env + inline-source pattern is robust against that footgun AND gives new contributors a one-command bootstrap.

OpenAPI Spec Export (FastAPI)

Ship a standard api-export-spec target whenever you scaffold a FastAPI project. Benefits:

  • Enables spec-diff in CI (catch accidental breaking API changes in PRs).
  • Unblocks typed client generation (openapi-typescript, datamodel-code-generator, etc.).
  • Gives external consumers a stable URL-less artifact to pin against.

Pair it with templates/python-fastapi-scripts/export_openapi_spec.py:

api-export-spec: ## Export OpenAPI spec to openapi.json
	uv run python scripts/export_openapi_spec.py
# scripts/export_openapi_spec.py
from app.main import app
import json
from pathlib import Path

(Path(__file__).parents[1] / "openapi.json").write_text(
    json.dumps(app.openapi(), indent=2) + "\n"
)

Local vs Prod DB Runs

Apps often need to run the same server against two DBs: local Docker for development, remote prod for debugging/one-off migrations. Split into two explicit targets; never let one be the ambient default.

.PHONY: run-api-local run-api-prod

run-api-local: ## Run API against local DB (loads .env, --reload)
	@set -a && . ./.env && set +a && uv run uvicorn app.main:app --reload

run-api-prod: ## Run API against REMOTE prod DB (loads .env.prod)
	@if [ ! -f .env.prod ]; then \
		printf "$(RED)$(CROSS) .env.prod not found$(RESET)\n"; \
		printf "$(YELLOW)Create it locally with the prod DATABASE_URL (gitignored)$(RESET)\n"; \
		exit 1; \
	fi
	@printf "$(RED)$(BOLD)$(WARN)  LOCAL APP -> REMOTE PRODUCTION DB$(RESET)\n"
	@printf "$(YELLOW)Writes hit prod. Ctrl-C within 3s to abort.$(RESET)\n"
	@sleep 3
	@set -a && . ./.env.prod && set +a && uv run uvicorn app.main:app

Rules:

  • .env.prod MUST be gitignored (production credentials). Add it to .gitignore before creating the file.
  • Prod target: no --reload (code changes auto-reloading against prod is a footgun), visible red warning, 3-second sleep so it isn't silent when fired by reflex.
  • Preflight: fail fast if .env.prod is missing rather than silently falling back to .env.
  • Same pattern works for run-worker-local/run-worker-prod, db-shell-prod (connect local psql to remote), etc.

FIX Variable for Check/Format Targets

Use a FIX variable to toggle between check-only and auto-fix modes:

FIX ?= false

dev-check: ## Run linting and type checks (FIX=false: check only)
	$(call print_section,Running checks)
ifeq ($(FIX),true)
	uv run ruff check --fix src/ tests/
	uv run ruff format src/ tests/
else
	uv run ruff check src/ tests/
	uv run ruff format --check src/ tests/
endif
	uv run mypy src/
	$(call print_success,All checks passed)

In help output, show usage:

@printf "$(CYAN)%-25s$(RESET) %s\n" "dev-check" "Run linting (FIX=false: check only)"
@printf "%-25s $(GREEN)make dev-check FIX=true$(RESET)  <- auto-fix issues\n" ""

Per-Module Test Targets

For projects with multiple modules or platform adapters, create per-module test targets using tool-specific filtering:

# Unit tests - filter by test file
.PHONY: test-unit-auth
test-unit-auth: ## Run auth module unit tests
	$(call print_section,Running auth unit tests)
	$(Q)$(NPM) exec vitest -- run tests/auth.test.js

# E2E tests - filter by grep pattern
.PHONY: test-e2e-checkout
test-e2e-checkout: ## Run checkout E2E tests
	$(call print_section,Running checkout E2E tests)
	$(Q)$(NPM) exec playwright -- test --grep "checkout"

Key points:

  • Use $(NPM) exec (not bare npx) for consistency with the $(NPM) variable
  • Unit tests filter by file path, E2E tests filter by --grep pattern
  • Keep the generic test-unit and test-e2e targets for running everything
  • Put per-module targets in test.mk, not dev.mk

When to Modularize

Default to modular for any new Makefile with 5+ targets.

Use flat file only when:

  • Simple scripts or single-purpose tools
  • User explicitly requests it
  • < 5 targets with no expected growth

Standard modular structure:

Makefile              # Config, imports, help, catch-all
makefiles/
  colors.mk          # ANSI colors & print helpers
  common.mk          # Shell flags, VERBOSE, guards
  <domain>.mk        # Actual targets (build.mk, dev.mk, etc.)

Legacy Compatibility

Default: NO legacy aliases. Only add when:

  • User explicitly requests backwards compatibility
  • Existing CI/scripts depend on old names (verify with rg "make old-name")

When legacy IS needed, put them in a clearly marked section AFTER main targets but BEFORE help:

############################
### Legacy Target Aliases ##
############################

.PHONY: old-name
old-name: new_name ## (Legacy) Description

Key Rules

  • Always read existing Makefile before changes
  • Search codebase before renaming targets (rg "make old-target")
  • Test with make help and make -n target
  • Update docs after Makefile changes - When adding new targets:
    1. Add to make help output (in the appropriate section)
    2. Update CLAUDE.md if the project has one (document new targets)
    3. Update any other relevant docs (README.md, Agents.md, etc.)
  • Never add targets without clear purpose
  • No line-specific references - Avoid patterns like "Makefile:44" in docs/comments; use target names instead
  • Single source of truth - Config vars defined once in root Makefile, not duplicated in modules
  • Root Makefile = help + imports + catch-all only - Recipe bodies live in makefiles/*.mk. When a recipe leaks into the root file, other contributors copy that pattern and the modular structure drifts back to flat. If setup/status/whatever lives in root, move it to the most relevant module (e.g., env.mk).
  • Help coverage audit - All targets with ## must appear in either make help or make help-unclassified

Help System

Help is GENERATED from the makefiles, never hand-maintained. A hand-written help block authors every target twice — once as a rule, once as a printf — and the two drift apart the first time someone is in a hurry. Copy modules/help.mk (or the inline block in templates/base.mk) and never write a printf per target again.

Two kinds of comment drive the entire output:

##@ 🐘 Database & Migrations        # declares a section (emoji lives HERE, only here)

db-migrate: ## Apply migrations (alembic upgrade head)
db-reset: ## Destroy volume, recreate, migrate (⚠️ DESTRUCTIVE)

Renders as:

═══ 🐘 Database & Migrations ═══

  db-migrate              Apply migrations (alembic upgrade head)
  db-reset                Destroy volume, recreate, migrate (⚠️ DESTRUCTIVE)

The four rules

  1. Emoji on section headers, NEVER on target lines. Per-target emoji have inconsistent display widths — ⬆️ ♻️ 🖥️ ☁️ (variation-selector emoji) render 1 cell, 🐘 🚀 📦 render 2 — so the description column jitters line to line and the list stops being scannable. One emoji per section can't misalign anything below it. This is the single highest-impact readability rule here.

  2. Sections render in file order, files in include order. The include list in the root Makefile IS the help ordering — no alphabetical sort, so quickstart can actually be first. Include help.mk LAST so ❓ Help renders last.

  3. Every .mk declares its own ##@ before its targets (the section resets at each file boundary). make help-unclassified catches the ones that forgot.

  4. Three color tiers, standard 16-color ANSI (theme-adaptive — the same file must read correctly on light and dark terminals; never pin 256-color values):

    TierColorExample
    Section header$(BOLD)$(BLUE)═══ 🐘 Database & Migrations ═══
    Target name$(CYAN)db-migrate
    Description prosedefault fgApply migrations, (needs db + redis)
    Inline literal$(GREEN)`alembic upgrade head`, `openapi.json`
    Secondary detail$(DIM)# uv sync --all-extras
    Inline danger$(YELLOW)(⚠️ DESTRUCTIVE)

    Headers and target names must never share a hue. Two hierarchy levels in one apparent color flattens the list into an unscannable wall — this is the most common failure mode in real Makefiles. Avoid $(BOLD)$(MAGENTA) (reads purple, clashes with most themes); bold-with-no-color gets lost entirely.

Banner

ASCII box title with a project-branded emoji on the right. The box anchors the top of make help; the right-side emoji gives the project a glanceable identity (leaf/herb for Grove, rocket for an SDK, lock for a security tool, etc.). Keep the emoji on the right — left-side placement crowds the title text.

The renderer computes the box from HELP_TITLE / HELP_ICON / HELP_WIDTH, so it stays square when the project is renamed:

HELP_TITLE   ?= Grove App — Make Targets   # text only, no emoji (see below)
HELP_ICON    ?= 🌿
HELP_TAGLINE ?= Every command runs via uv.
HELP_WIDTH   ?= 46

⚠️ Emoji width gotcha. Most emojis render as 2 terminal columns but count as 1 char, so padding computed from string length comes out short. The renderer budgets exactly 2 cells for HELP_ICON — keep emoji OUT of HELP_TITLE or the right ║ will not line up.

Expanding make vars in descriptions

awk reads raw file text, so make never expands $(PORT) inside a ## comment — help would print the literal $(PORT). List such vars in HELP_VARS and they are substituted at render time:

HELP_VARS ?= PORT HEALTH_PATH

api-health: ## Check API health endpoint ($(HEALTH_PATH))   # renders: (/health)

NO_COLOR

Guard the palette with ifdef NO_COLOR so make help > FILE doesn't embed raw escapes. Do not try to auto-detect a TTY: $(shell test -t 1) always reports false (subshell stdout is a pipe), and MAKE_TERMOUT needs GNU make ≥ 4, which macOS doesn't ship.

Emoji vocabulary for help sections (pick from this list; reuse the same emoji for the same concept across projects so the visual language transfers):

Section conceptEmojiNotes
Quick Start / Getting started🚀Primary entry point for new contributors
Run / dev server / start service🏃Short-running ergonomic entry points
Build / compile / package🏗️dev-build, artifact creation
Development / lint / format / typecheck🛠️Quality gate targets
Tests🧪test, test-e2e, coverage
Database🗄️db-start, db-migrate, db-reset
Environment / config🌐env-setup, env-status, env-show
Secrets / auth / keys🔑env-pull-*, credential management
Deploy / release🛫deploy, release, publish
Cleanup / reset🧹clean-* family
Help / reference❓help, help-unclassified

Emoji here go on the ##@ header only — a variation-selector emoji (🛠️, 🗄️, 🏗️) may consume an extra column, which is harmless in a header and would wreck a target line.

Quick Start is a 2-step instruction list, not a target list. If the real entry point is a short sequence (make env-setup && make run-prod), make quickstart a target that prints numbered instructions — do NOT list the same targets under both Quick Start and their "real" section (Environment Utilities, Run, etc.). Duplication doubles the help height and dilutes signal.

# Good - one quickstart target printing an ordered sequence
##@ 🚀 Quick Start

quickstart: ## Print ordered first-run steps
	@printf "  $(GREEN)1.$(RESET) make env-install   $(DIM)# uv sync --all-extras$(RESET)\n"
	@printf "  $(GREEN)2.$(RESET) make run-local\n"

# Bad - the same targets listed under Quick Start AND their real section

Key help patterns:

  • help - Main categorized help, generated from ##@ + ##
  • help-unclassified - Documented targets with no ##@ section above them (audit)
  • Hidden targets: prefix with _ and give them NO ## comment (e.g., _check-docker)
  • Legacy targets: label with ## (Legacy) and park them under a ##@ 🗄️ Legacy section

Always give help and help-unclassified their own section — put ##@ ❓ Help directly above them, otherwise the two most basic targets are missing from help and clutter help-unclassified instead. modules/help.mk already does this.

help-unclassified needs no exclusion list. The old prefix-regex approach (grep -v -E '^(env-|dev-|clean|help)') fell out of sync every time a prefix was added. The generated version asks a structural question instead — "is there a ##@ above this target?" — which stays correct forever:

help-unclassified: ## List documented targets with no ##@ section above them
	@awk 'FNR == 1 { section = "" } \
		/^##@ / { section = substr($$0, 5); next } \
		/^[a-zA-Z0-9_-]+:.*## / && section == "" { print "  " $$0 }' $(MAKEFILE_LIST)

Description format — one plain-text line, in the ## comment:

# Good - one line, says what it affects, args shown inline
scrape: ## Fetch posts into SQLite (make scrape SUBREDDITS=python LIMIT=10)
dev-check: ## Lint + type-check — add FIX=true to auto-fix
clean-build: ## Remove the .next build directory
run-local: ## Run API against local DB (localhost:$(PORT))

# Bad - a paragraph in a help line
setup: ## Install Python dependencies using uv. Run this once after cloning. Creates .venv/ and installs from pyproject.toml.

Help description rules:

  • One line max — it shares a row with the target name; anything longer wraps and breaks the column.
  • Include what it affects — "creates .venv", "exports to CSV", "destroys the volume".
  • No raw ANSI — $(YELLOW) inside a ## comment prints as the literal string $(YELLOW). Use backticks (below) for emphasis; only names listed in HELP_VARS are expanded.
  • Fold the example into the line — (make foo ARG=val) or — add FIX=true rather than a second printf line. The generated renderer emits one row per target by design.
  • Skip examples for simple targets — if there are no parameters, no example is needed.

Wrap literals in backticks. The renderer colors the contents green and strips the delimiters, so the tokens a reader actually reaches for — commands, files, paths, tool names, target names, env vars — pop out of the prose:

env-install: ## Install all deps incl extras (`uv sync --all-extras`)
api-export-spec: ## Export OpenAPI spec to `openapi.json`
db-shell: ## Open `psql` in the Postgres container
test: ## Run unit tests (alias of `test-unit`)

Renders as Install all deps incl extras (uv sync --all-extras) with the backticked span in green. Leave prose parentheticals plain — (needs db + redis), (prod-like, guarded). Marking up everything is the same as marking up nothing.

Note this is markup, not detection: a "color whatever is in parens" rule would miss openapi.json (not in parens) and wrongly color (needs db + redis).

Danger annotations are the other styled element. A trailing (⚠️ …) renders in yellow. Use it for targets that destroy data or touch production, and nothing else — three per project keeps the marker meaningful, thirty makes it wallpaper:

db-reset: ## Destroy volume, recreate, and migrate (⚠️ DESTRUCTIVE)
run-api-prod: ## Run API against REMOTE prod DB, no reload (⚠️ PROD)
clean-all: clean ## Clean caches and remove .venv (⚠️ DESTRUCTIVE)

URL-in-parens formula for run-* targets. When a run target has a canonical destination (localhost port, API URL), append it in parens at the end of the description — denser than a separate info line, and it matches how contributors actually scan help. Use HELP_VARS so the port is the real one:

HELP_VARS ?= PORT

run-local: ## Local API + testnet chains (localhost:$(PORT))
run-testnet: ## Testnet API + testnet chains (api.testnet.grove.city)
run-mainnet: ## Production API + mainnet chains (api.grove.city) (⚠️ PROD)

Catch-all for unknown targets

Suggest the closest documented targets instead of dumping the whole help page — a typo is usually one character off, and reprinting 40 targets buries the fix:

%:
	@printf "$(RED)$(CROSS) Unknown target '$@'$(RESET)\n"
	@targets=$$(awk -F: '/^[a-zA-Z0-9_-]+:.*## /{print $$1}' $(MAKEFILE_LIST) | sort -u); \
	near=$$(printf '%s\n' "$$targets" | grep -i -- "$$(printf '%s' '$@' | cut -c1-4)" | head -5 || true); \
	if [ -n "$$near" ]; then \
		printf "$(DIM)Did you mean:$(RESET)\n"; \
		printf "  $(CYAN)%s$(RESET)\n" $$near; \
	fi; \
	printf "$(DIM)Run '$(RESET)$(CYAN)make help$(RESET)$(DIM)' for all targets.$(RESET)\n"; \
	exit 1

Three rules, each learned from a real failure:

#RuleFailure it prevents
1Keep it last in the fileA match-anything rule shadows every pattern rule defined after it
2Give every -include <file> an empty <file>: ; rule-include .env makes .env a goal, the catch-all claims it, and a fresh clone greets you with ✗ Unknown target '.env' on every run
3Never let an ignore-regex match target-shaped namesAn ignore-list ending in [a-z]+([-][a-z]+)* swallows every typo — make dev-tes exits 0 and CI goes green on a target that does not exist

Rule 2 in practice, at the top of the file:

-include .env
# Optionally-included files are NOT build targets. An explicit rule beats a
# match-anything rule, so this silences the catch-all for good.
.env .env.prod .template.env: ;

An ignore-list is only for bare arguments passed as extra goals (make send-tx 0xabc…, a URL, a number, a TICKER) — never for anything that could be a mistyped target.

TODO Tracking

TODO.md is a generated view over the code, never a hand-maintained backlog. Include modules/todo.mk and copy modules/todo-scripts/gen_todo.py to scripts/gen_todo.py. Rationale: Move Fast & Document Things.

  • A hand-written list is "the one document to rule them all" — it goes stale the moment someone fixes something without updating it.
  • The TODO lives next to the code it concerns; the index is regenerated.
  • Filing a TODO is cheaper than filing a ticket. That is the point.
  • make todo-check fails when TODO.md is stale — wire it into CI.
  • make todo-list needs no Python and works in any language.
# TODO_TECHDEBT: drop these casts if redis-py restores a typed client.
# Blocked on upstream: redis-py 8 removed Generic[_StrType], so `Redis[str]`
# raises at runtime. Re-check on the next major bump.
#SeverityPrefixAct when
1🔴FIXMENow — it is broken today
2🔴TODO_IN_THIS_PRBefore merge
3🟠HACKBefore it bites someone
4🟠TODO_REMOVE_LATERWhen its stated exit condition is met
5🟡TODO_TECHDEBT / TODO_BETA / TODO_PROD / TODO_OPTIMIZENext cleanup, or at the named gate
6🟢TODO_IMPROVE / TODO_CONSIDERATION / TODO_FUTURE / TODO_IDEA / TODOOpportunistically
  • Annotate with TODO_PROD(#123, @olshansk): to record an issue and/or owner.
  • Always say what to do and why it is deferred — a bare TODO: fix this helps nobody.
  • NOTE: is not tracked; it marks an explanation, not work.

Runtime Output for Long-Running Targets

Help output is one concern; runtime output from run-* / dev-* / db-* targets that activate config and then hand off to a long-running subprocess (next dev, uvicorn, docker compose up) is a second concern. Without structure, the output from "env activation → warning → config summary → subprocess banner → subprocess logs" interleaves into one undifferentiated wall of ℹ️ / ✓ / ⚠️ lines, and the developer has to read everything to find what matters. The patterns below break that into visually distinct phases.

Phase Banners

Bracket each logical phase with a horizontal rule + emoji + title + horizontal rule. Add two small reusable macros to colors.mk:

# Horizontal rule separator
define print_hr
	@printf "$(DIM)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━$(RESET)\n"
endef

# Phase banner: horizontal rule + emoji + title + horizontal rule
# Usage: $(call print_phase,🔑,ENV → LOCAL + MAINNET)
define print_phase
	@printf "\n$(DIM)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━$(RESET)\n"
	@printf "$(BOLD)$(CYAN) $(1)  $(2)$(RESET)\n"
	@printf "$(DIM)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━$(RESET)\n\n"
endef

Suggested phase-emoji vocabulary (use consistently across a project so the reader learns the shorthand):

PhaseEmojiUse when
Env / setup / secrets🔑Activating .env, loading secrets, switching config
Config / URLs / network🌐Showing resolved config, API endpoints, RPC URLs
App / server / service starting🚀Right before handing off to next dev / uvicorn / etc.
Database🗄️db-start, db-migrate, db-reset
Build📦build, dev-build, packaging
Tests🧪Before pytest / vitest / playwright output
Deploy🛫Before render deploy / fly deploy / vercel

Critical-Action Warnings (Triple-Emoji Pattern)

For irreversible actions — real-money mainnet runs, production DB writes, force pushes, anything with "you probably can't undo this" — use a standalone triple-emoji line that sits between phases, not inside one. The triple flanking is visually louder than any single-line warning and the isolation ensures it isn't scanned past as ambient info.

# In colors.mk
define print_mainnet_warning
	@printf "\n$(RED)$(BOLD)⚠️⚠️⚠️  MAINNET — REAL MONEY. DOUBLE-CHECK BEFORE TX.  ⚠️⚠️⚠️$(RESET)\n"
endef

define print_prod_db_warning
	@printf "\n$(RED)$(BOLD)⚠️⚠️⚠️  WRITES HIT PRODUCTION DATABASE — CTRL-C IN 3s TO ABORT  ⚠️⚠️⚠️$(RESET)\n"
endef

Rules:

  • Reserve the triple-⚠️ pattern for genuinely irreversible / costly actions. If you use it on every soft warning, it loses all signal.
  • Single ⚠️ (or 🟡) for soft warnings ("secrets file missing, OAuth won't work"); triple ⚠️⚠️⚠️ for hard ones ("real money", "prod DB", "about to overwrite remote").
  • Always render in $(RED)$(BOLD) and on its own line with blank lines around it — a boxed or inlined version loses punch.

"Subprocess Logs Below" Divider

Right before handing off to a long-running subprocess (npm run dev, uvicorn, docker compose up), print a muted divider line that names whose logs are about to appear. Tells the user the Makefile's own output has ended, and anything below is coming from a child process with its own formatting conventions.

.PHONY: dev-run
dev-run:
	$(call print_phase,🚀,APP)
	# ... URLs, Ctrl+C hint, etc ...
	@printf "\n$(DIM)─────────── Next.js logs below ───────────$(RESET)\n\n"
	$(Q)npm run dev

Name the subprocess explicitly (Next.js logs, uvicorn logs, Postgres logs) — a generic "logs below" is less useful because the reader still has to guess whose formatting conventions to expect.

Actionable-Control Hint Before Hand-Off

Print one line right before the subprocess divider that tells the user what their keyboard controls are and what to expect. Compact, one line, bold the key combo:

@printf "\n$(CYAN)$(INFO) Auto-reload enabled · Press $(BOLD)Ctrl+C$(RESET)$(CYAN) to stop$(RESET)\n"

Bad alternative: a multi-line "Server running. Press Ctrl+C to stop. Changes auto-reload." block — same information, 3× the vertical space, no denser.

Parsed Key-Value Grid Over Raw grep Dumps

For env-show / status / db-info / any target whose job is to show "the current state of things," parse the underlying file and print a compact key-value grid rather than dumping raw KEY=value lines from grep. The parsed version is scannable; the raw dump is a wall of NEXT_PUBLIC_FOO=bar prefixes that the eye has to filter.

# Bad - raw grep dump, 3 subsections, 8 lines
env-show:
	@printf "\n$(BOLD)Configuration:$(RESET)\n"
	@grep "^NEXT_PUBLIC_ENV=" .env.local | sed 's/^/  /'
	@grep "^NEXT_PUBLIC_CHAIN_ENV=" .env.local | sed 's/^/  /'
	@printf "\n$(BOLD)API Endpoints:$(RESET)\n"
	@grep "NEXT_PUBLIC_.*_URL=" .env.local | sed 's/^/  /'
	@printf "\n$(BOLD)Services:$(RESET)\n"
	@grep "^NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=" .env.local | sed 's/^/  /'

# Good - parsed grid under a phase banner, 4 lines, aligned columns
env-show:
	$(call print_phase,🌐,CONFIG)
	@ENV=$$(grep "^NEXT_PUBLIC_ENV=" .env.local | cut -d= -f2); \
	 GROVE=$$(grep "^NEXT_PUBLIC_GROVE_API_BASE_URL=" .env.local | cut -d= -f2); \
	 BASE=$$(grep "^NEXT_PUBLIC_BASE_RPC_URL=" .env.local | cut -d= -f2 | sed 's|https://||'); \
	 SOL=$$(grep "^NEXT_PUBLIC_SOLANA_RPC_URL=" .env.local | cut -d= -f2 | sed 's|https://||'); \
	 printf "  $(BOLD)%-8s$(RESET) $(YELLOW)%s$(RESET)\n" "Env" "$$ENV"; \
	 printf "  $(BOLD)%-8s$(RESET) $(YELLOW)%s$(RESET)\n" "API" "$$GROVE"; \
	 printf "  $(BOLD)%-8s$(RESET) $(YELLOW)%s$(RESET) · $(YELLOW)%s$(RESET)\n" "RPC" "$$BASE" "$$SOL"

Rules:

  • Fixed-width label column (%-8s / %-10s) so values align vertically.
  • Values colored $(YELLOW) (same convention as help-description paths/URLs).
  • Strip noise (e.g. https:// prefixes on RPC URLs) when the protocol doesn't add information.
  • Mask secrets (WALLETCONNECT_SECRET=***hidden***).
  • If a value is missing or placeholder, print $(RED)✗ not configured$(RESET) — don't silently omit the row.

Full-Flow Example

Applying all five patterns to a run-mainnet target produces:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 🔑  ENV → MAINNET
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  ✓  envs/mainnet.env + envs/.mainnet.secrets → .env.local

⚠️⚠️⚠️  MAINNET — REAL MONEY. DOUBLE-CHECK BEFORE TX.  ⚠️⚠️⚠️

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 🌐  CONFIG
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  Env      MAINNET (Base Mainnet · Solana Mainnet)
  API      https://api.grove.city
  RPC      mainnet.base.org · api.mainnet-beta.solana.com
  Wallet   WalletConnect a06ebd2a…

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 🚀  APP
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🌐 URLs:
   http://localhost:3000         (local)
   http://192.168.1.15:3000      (LAN / mobile — cross-network? make run-ngrok)

ℹ️ Auto-reload enabled · Press Ctrl+C to stop

─────────── Next.js logs below ───────────

▲ Next.js 16.2.1 (Turbopack) · Ready in 400ms

Common Pitfalls

IssueFix
$var in shell loopsUse $$var to escape for make
Catch-all %: shows errorRedirect to @$(MAKE) help instead
Config vars scatteredPut all ?= overridable defaults at TOP of root Makefile
HELP_PATTERNS mismatchMust match grep patterns in help target exactly
Duplicate defs in modulesDefine once in root, reference in modules
Trailing whitespace in varsCauses path splitting bugs - trim all variable definitions
.PHONY on file targetsOnly use .PHONY for non-file targets
Too many public targetsDon't expose install-X or check-X - use internal _check-X dependencies
$(DIM) for usage textAppears grey/unreadable - use $(GREEN) instead
Color codes inside %sANSI codes in %s args print as literals - put colors in format string
Section header same color as title/targetsUse a distinct color (default $(BOLD)$(BLUE) — avoid $(MAGENTA)/purple, clashes with most terminal themes) + \n\n after the header. $(BOLD) alone renders as terminal-default and gets lost.
Section headers have no emojiEvery section gets a leading emoji (🚀 Quick Start, 🏃 Run, 🛠️ Development, 🌐 Environment, 🧹 Cleanup, 🧪 Tests). Emojis give the reader a glanceable landmark so they can skip to the section they want without parsing words. See "Emoji vocabulary" table in the Help System section.
Title box has no project emojiThe make help title box should carry a project-branded emoji on the right (🌿 for Grove, 🚀 for SDKs, 🔒 for security tools, etc.). Right-side placement; left-side crowds the title.
Runtime output is a wall of ℹ️/⚠️/✓ with no structureWrap each logical phase (env activation, config summary, subprocess hand-off) in a print_phase banner — see §"Runtime Output for Long-Running Targets".
env-show / status dumps raw KEY=value grep outputParse the values in shell and print a compact aligned key-value grid (Env / API / RPC / Wallet) — scannable instead of a wall of NEXT_PUBLIC_FOO=bar.
⚠️ used on every warning, so no warning stands outReserve triple-⚠️⚠️⚠️ $(RED)$(BOLD) for irreversible / costly actions (prod writes, real money, force push). Single ⚠️ for soft warnings.
Target named after toolName after the action: remove-bg not rembg
Too many granular dev-* quality targetsCollapse dev-lint + dev-typecheck + dev-format + dev-check into one dev-format (runs all three — prettier+eslint+tsc usually <5s for Node projects). Split only if CI parallelizes them. Same for dev-test + dev-test-e2e → one test.
run-*-all / "Full Stack" Cartesian sectionProjects with a docs/ sibling grow run-testnet-all / run-mainnet-all / run-local-all / run-local-mainnet-all that just background the docs site. These are almost never used — users open a second terminal. Keep one run-docs target in the "Run" section and drop the Cartesian matrix.
Quick Start repeats targetsIf Quick Start lists setup and status, and Environment Utilities lists setup and status again, you're doubling help height. Make Quick Start a numbered instruction list (1. make env-setup, 2. make run-prod) and let targets live once in their real section.
help-unclassified shows filenameUse sed 's/^[^:]*://' to strip Makefile: prefix
No .env exportInline-source in the recipe: @set -a && . ./.env && set +a && $(CMD) (or -include .env for weaker cases — see Env File Loading)
Stale shell DATABASE_URL silently overrides .envUse inline set -a && . ./.env && set +a in any recipe that depends on a specific .env value. -include alone loses to already-exported shell vars.
Secret committed to gitAdd gitignored file (e.g. .env.prod), verify with git check-ignore, grep staged diff for a secret fragment before git add: git diff --cached | grep -c "$FRAGMENT"
Single-service docker-compose.ymlFor one Postgres container, a plain docker run in db-start is lighter than a compose file. Compose pays off only when you have 2+ services.
Dockerized Postgres on port 5432 clashes with host Homebrew PostgresDefault dev container to PG_PORT ?= 5433 (and update DATABASE_URL accordingly). 5432 is nearly always claimed on macOS dev machines.
pgcli rejects postgresql+psycopg://... URLpgcli doesn't understand SQLAlchemy dialect markers. Strip before use: PGCLI_URL=$$(echo "$$DATABASE_URL" | sed 's/+psycopg//') && pgcli "$$PGCLI_URL".
FastAPI api-export-spec hardcodes model importThe export script imports app.main:app. Parameterize via the APP_MODULE make variable if your entrypoint differs.

Cleanup Makefile Workflow

When user says "cleanup my makefiles":

IMPORTANT: Build a plan first and explain it to the user before implementing anything.

Phase 1: Audit (no changes yet)

make help                    # See categorized targets
make help-unclassified       # Find orphaned targets
cat Makefile                 # Read structure
ls makefiles/*.mk 2>/dev/null # Check if modular
rg "make " --type md         # Find external dependencies
grep -E '\s+$' Makefile makefiles/*.mk  # Trailing whitespace

Phase 2: Build & Present Plan

Create a checklist of proposed changes:

  • Structure - Convert flat → modular (if 5+ targets) or vice versa
  • Legacy removal - List specific targets to delete (with dependency check)
  • Duplicates - List targets to consolidate
  • Renames - List old_name → new-name changes
  • Description rewrites - List vague descriptions to improve
  • Missing targets - Suggest targets that should exist (e.g., help-unclassified)
  • Ordering fixes - Config → imports → targets → help → catch-all

Ask user to approve the plan before proceeding.

Phase 3: Implement (after approval)

  1. Restructure (if needed) - Create makefiles/ directory, split into modules
  2. Remove legacy - Delete approved targets
  3. Consolidate duplicates - Merge into single targets
  4. Rename targets - Apply hyphen convention, add _ prefix for internal
  5. Rewrite descriptions - Make each ## explain the purpose
  6. Fix formatting
    • Usage examples in yellow: $(YELLOW)make foo$(RESET)
    • Remove trailing whitespace
    • .PHONY only on non-file targets
  7. Add missing pieces - help-unclassified, catch-all %:, etc.

Phase 4: Verify

make help          # Clean output?
make help-unclassified  # Should be empty or minimal
make -n <target>   # Dry-run key targets

What NOT to do without asking:

  • Rename targets that CI/scripts depend on
  • Remove targets that look unused
  • Change structure (flat ↔ modular) without approval

Files in This Skill

  • reference.md - Detailed patterns, categorized help, error handling
  • templates/ - Full copy-paste Makefiles for each stack
  • modules/ - Reusable pieces for complex projects
    • modules/help.mk - Generated make help (##@ sections). Include LAST.
    • modules/colors.mk - ANSI palette, color tiers, NO_COLOR guard
    • modules/common.mk - Shell settings, guards, preflight checks
    • modules/todo.mk - Generated TODO.md from prefixed code comments
    • modules/todo-scripts/gen_todo.py - companion for make todo

🚧 Generated-help migration status. base.mk, python-uv.mk, and python-fastapi.mk use the generated ##@ renderer. The six templates still hand-writing their help block carry a TODO_FUTURE at the top of the file — find them with grep -rn "TODO_FUTURE" templates/ (currently go.mk, nodejs.mk, flutter.mk, electron.mk, chrome-extension.mk, static-site.mk). Convert one whenever you touch it for another reason.

Example: Adding a Target

User: "Add a target to run my tests"

.PHONY: test
test: ## Run tests
	$(call print_section,Running tests)
	uv run pytest tests/ -v
	$(call print_success,Tests passed)

User: "Add database targets"

.PHONY: db-start db-stop db-migrate

db-start: _check-docker ## Start database
	docker compose up -d postgres

db-stop: ## Stop database
	docker compose down

db-migrate: _check-postgres ## Run migrations
	uv run alembic upgrade head

Mermaid Diagram Renderer

Render mermaid diagrams to PNG and display them inline. Supports iTerm2 (imgcat) and Ghostty (kitten icat). Built for fast visual iteration.

Workflow

Every time you generate or modify mermaid code, immediately render and display it. Never ask "want me to render?" — just do it.

Write the mermaid code:

cat > /tmp/mermaid-diagram.mmd << 'MERMAID'
graph TD
    A[Start] --> B{Decision}
    B -->|Yes| C[Action]
    B -->|No| D[End]
MERMAID

Render:

"${CLAUDE_SKILL_DIR}/scripts/render.sh" /tmp/mermaid-diagram.mmd

The script outputs Rendered: <path> and View: <command>. Always print the View: command for the user so they can copy-paste it to see the diagram inline. Claude Code's Bash tool captures stdout, so inline images won't display automatically.

If the user provides a specific file path, use that instead of /tmp/mermaid-diagram.mmd.

Prerequisites

On first use, check that mmdc is available:

which mmdc || echo "MISSING: Run 'npm install -g @mermaid-js/mermaid-cli'"

The display command (imgcat or kitten icat) is detected automatically based on $TERM_PROGRAM. No manual setup needed — the script falls back to open if neither is available.

Rendering

The render.sh script handles rendering with sensible defaults. It supports these flags:

  • --theme <name> — mermaid theme: default, dark, forest, neutral (default: default)
  • --width <px> — output width in pixels (default: 1200)
  • --bg <color> — background color (default: transparent)
  • --css <path> — custom CSS file for styling
  • --output <path> — custom output path (default: replaces .mmd with .png)

Examples:

"${CLAUDE_SKILL_DIR}/scripts/render.sh" /tmp/mermaid-diagram.mmd --theme dark
"${CLAUDE_SKILL_DIR}/scripts/render.sh" /tmp/mermaid-diagram.mmd --width 2400
"${CLAUDE_SKILL_DIR}/scripts/render.sh" /tmp/mermaid-diagram.mmd --output ~/Desktop/diagram.png

Iteration Rules

  • After each user edit request, update the .mmd file and re-render immediately
  • Show the View: command after every change — the user should never have to ask
  • Keep the .mmd file path consistent within a session so edits accumulate
  • If mmdc reports a syntax error, show the error message and fix the mermaid code before retrying
  • Use the cheatsheet below for syntax reference when iterating

Mermaid Syntax Cheatsheet

Graph Directions

graph TD (top-down), graph LR (left-right), graph BT (bottom-top), graph RL (right-left)

Node Shapes

A[Rectangle]    B(Rounded)    C{Diamond}
D((Circle))     E[[Subroutine]]   F[(Database)]
G>Asymmetric]   H{{Hexagon}}  I[/Parallelogram/]

Link Styles

A --> B           Solid arrow
A --- B           Solid line (no arrow)
A -.-> B          Dotted arrow
A ==> B           Thick arrow
A -->|label| B    Arrow with label
A -- text --> B   Arrow with text (alternate)

Subgraphs

subgraph Title
    A --> B
end

Styling

style A fill:#f9f,stroke:#333,stroke-width:2px
classDef highlight fill:#ff0,stroke:#333
class A,B highlight

Themes

Set via --theme flag: default, dark, forest, neutral

Or in the diagram: %%{init: {'theme': 'dark'}}%%

Sequence Diagram

sequenceDiagram
    participant A as Alice
    participant B as Bob
    A->>B: Hello
    B-->>A: Hi back
    A->>+B: Request
    B-->>-A: Response
    Note over A,B: Handshake complete

State Diagram

stateDiagram-v2
    [*] --> Idle
    Idle --> Processing: start
    Processing --> Done: finish
    Done --> [*]

Entity Relationship

erDiagram
    USER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains

Class Diagram

classDiagram
    class Animal {
        +String name
        +makeSound()
    }
    Animal <|-- Dog
    Animal <|-- Cat

Olshanskify

Rewrite or edit content so it matches Olshansky's voice and conventions. Templates encode the rules; this skill picks the right template and applies it.

Global Style Rules

These apply across all templates (docs, code, blog, presentation) and across any conversational prompt / status output this skill produces:

  • Signal user action with an emoji or admonition. Whenever the reader must decide, approve, resolve, or confirm something, prefix the prompt with a status glyph — green/yellow/red circle or a GitHub-style admonition:
    • 🟢 safe / ready to proceed
    • 🟡 caution / needs review
    • 🔴 blocked / must be addressed
    • ⚠️ / > [!WARNING] — urgent or destructive action
    • ⏳ / 🤔 — waiting on user input
  • Wrap every list/option label in square brackets. If something is a selectable option, a referenced list item, or a status tag, use […] around it. Examples: [1] Approve, [2] Reject, [✅ DONE], [OPTION A], [FEAT], [WALLET]. Consistent brackets make options scannable and unambiguous.

1. Pick a Template

Templates live in templates/ — one per content type. Add a new template when a new content type appears; update an existing template when a new rule emerges.

Content typeTemplateUse when
Documentation (READMEs, AGENTS.md, guides)templates/docs.mdEditing any markdown-heavy reference material
Code (any language)templates/code.mdEditing source files, proposing refactors, writing new code
Blog posttemplates/blog.mdDrafting or polishing posts for olshansky.info / substack / similar
Presentation / slidestemplates/presentation.mdEditing slide decks, talk outlines, conference abstracts

If the user does not specify a content type, ask:

Which Olshanskify template should I apply — docs, code, blog, or presentation? (Or is this a new type worth adding to templates/?)

2. Inspect the Target

Before proposing edits:

  1. Read the target file(s) in full.
  2. Read the chosen template end-to-end.
  3. Note any pre-existing style choices in the target that conflict with the template — surface conflicts explicitly rather than silently overriding.

3. Propose the Olshanskified Version

Show the user a diff or side-by-side before writing. Format:

## Olshanskify: {target_path}

Template applied: **{template_name}**

### Rules triggered
- {rule from template} → {how it reshapes this content}
- ...

### Proposed changes
- {file}:{lines} — {one-line summary of the edit}
- ...

### Conflicts / judgment calls
- {anything where the template and the existing content disagreed, and how you resolved it}

Do not edit yet. Wait for approval.

4. Apply on Approval

After the user confirms, apply the edits. Respect the global rule: the user commits manually — do not run git commit or git push.

5. Evolving the Templates

Templates are living documents. Update them when:

  • The user corrects a style choice ("no, always use X" / "drop the Y pattern").
  • A cross-skill signal surfaces a rule worth codifying. For example, cmd-pr-gh-comments proposes updates to templates/code.md whenever PR feedback came from @olshansk (see that skill's step 10).
  • A new content type appears — add a new template file and an entry to the table above.

When proposing a template edit, show:

  1. The rule to add (or change), in the template's existing tone.
  2. The source of the rule (which conversation, PR, or file surfaced it).
  3. A quick example of before/after if the rule is non-obvious.

Never silently mutate a template. Every change is approval-gated.

Store Plan

Capture the current conversation into a structured, reviewable plan file.

Instructions

1. Gather context

Scan the full conversation for:

  • Decisions — what was agreed on and why
  • Action items — concrete next steps with owners/priorities
  • Architecture or design choices — trade-offs discussed
  • Risks and open questions — unresolved items
  • Phases or ordering — any sequencing that was discussed

If the user passed a description as an argument (e.g., /cmd-plan-store auth refactor), use it as DESCRIPTION. Otherwise, infer a 2-4 word slug from the conversation topic.

2. Generate the plan document

Build the document using the Document Structure below. Not every section is required — omit sections that have no content rather than leaving them empty. The goal is a document that someone (including future-you) can pick up cold and understand what was decided, what's next, and why.

Present the draft to the user before writing.

3. Write and confirm

Step 3a — Write the file:

mkdir -p plans/

Write to the path defined in Output Path.

Step 3b — Confirm with the user:

Present the file path and a brief summary to the user. Ask if they want to adjust anything before finalizing.

Output Path

plans/{YYYY}_{MM}_{DD}_{description}.md

Examples:

  • plans/2026_04_02_auth_refactor.md
  • plans/2026_04_02_frontend_split.md
  • plans/2026_04_02_migration_engine_redesign.md

Document Structure

Header Block

# {Title} <!-- omit in toc -->

Date: YYYY-MM-DD
Source: conversation with Claude

- [Table of Contents entries...]

Always include a Table of Contents. Omit the top-level heading from the ToC using <!-- omit in toc -->.

tl;dr

Single italicized sentence (max 120 chars) summarizing the most important outcome or decision.

Place immediately after the ToC, before any sections.

Context

Brief background on what prompted this plan. 2-4 bullets max. Include:

  • What problem or goal kicked off the conversation
  • Any constraints or deadlines mentioned
  • Relevant prior work or plans referenced

Decisions Made

A table summarizing key decisions from the conversation:

SDecisionRationale
🟢What was decidedWhy this choice was made
.........

🟢 Approved · 🟡 Tentative · 🔴 Rejected · ⚪ Deferred

Plan Overview

High-level summary table of phases or work items:

SPhase / ItemComponentDescriptionPriority
🟢Phase 1module.pyWhat this phase doesP0
🟡Phase 2client/js/What this phase doesP1
⚪FutureTBDDeferred workP2

🟢 Ready to start · 🟡 Needs more detail · 🔴 Blocked · ⚪ Deferred

Priority labels: P0 (do first), P1 (do next), P2 (backlog)

Action Items

Checkboxed list grouped by priority. Each item should be concrete and actionable:

P0 — Do first:

  • Action item with file_path reference if applicable
  • Another action item

P1 — Do next:

  • Action item
  • Action item

P2 — Backlog:

  • Action item

Phases / Sections

For multi-phase plans, expand each phase with:

## Phase N: {Name}

_One-line italicized summary of what this phase achieves._

**Goal:** What success looks like

**Steps:**
- [ ] Step 1 — description
- [ ] Step 2 — description

**Verify:** How to confirm this phase is done (e.g., `cd server && uv run pytest`)

**Key files:**

| File | Change |
|------|--------|
| `path/to/file.py` | What changes |

Only include phases that were actually discussed. Don't invent phases.

Risks & Open Questions

SItemImpactNotes
🔴Risk or blockerWhat breaks if unaddressedMitigation or next step
🟡Open questionWhat it affectsWho needs to answer
⚪Nice-to-knowLow impactContext for later

🔴 High risk · 🟡 Medium / open question · ⚪ Low / informational

References

Bullet list of links, prior plans, or external resources mentioned:

  • plans/prior_plan.md — what it covers
  • URL or resource — what it covers

Formatting Rules

Status Circles

Use colored circles consistently as the first column in all tables:

CircleMeaning (adapt label to section context)
🟢Positive: approved, ready, new, complete
🟡Caution: tentative, needs detail, in progress
🔴Negative: rejected, blocked, high risk, critical
⚪Neutral: deferred, informational, no action

Always include a one-line legend as a blockquote below each table explaining what the circles mean in that context.

Tables

  • Use tables for structured comparisons, decision logs, and overviews
  • Keep cells concise — short phrases, not paragraphs
  • Use backticks for all code references in table cells
  • Include a Priority column when items have different urgency
  • Include a Rationale or Notes column when context matters

General

  • Checkboxes (- [ ]): Use for all actionable items so the user can track progress
  • Italicized tl;drs: Every major section can optionally have a one-line italic summary
  • Headings: Use ## for major sections, ### for subsections. Don't go deeper than ####
  • Code references: Always use backticks for file names, paths, commands, functions, config keys
  • Bullet points over paragraphs: Break any explanation longer than 2 sentences into bullets
  • No filler: Skip "this section covers..." preambles. Lead with the content
  • <!-- omit in toc -->: Use on the top-level # heading only

Example Output

# QC Cache Redesign <!-- omit in toc -->

Date: 2026-04-02
Source: conversation with Claude

- [tl;dr](#tldr)
- [Context](#context)
- [Decisions Made](#decisions-made)
- [Plan Overview](#plan-overview)
- [Action Items](#action-items)
- [Phase 1: Fingerprint-based invalidation](#phase-1-fingerprint-based-invalidation)
- [Phase 2: Background refresh](#phase-2-background-refresh)
- [Risks & Open Questions](#risks--open-questions)

_tl;dr Replace time-based QC cache with fingerprint-based invalidation to eliminate stale results after migrations._

## Context

- QC results were cached with a 5-minute TTL, causing stale data after migration edits
- Users reported QC tab showing pre-migration outliers after applying fixes
- Prior plan: `plans/2026_03_28_staleness_system.md`

## Decisions Made

| S | Decision | Rationale |
|---|----------|-----------|
| 🟢 | Use content fingerprint, not timestamps | Timestamps miss in-place edits to migration JSON |
| 🟢 | Hash migration file + source data | Captures both data changes and rule changes |
| 🟡 | Consider background pre-warming | Deferred — evaluate after P0 lands |
| 🔴 | Rejected: per-field granular caching | Too complex for current data volume |

> 🟢 Approved · 🟡 Tentative · 🔴 Rejected · ⚪ Deferred

## Plan Overview

| S | Phase | Component | Description | Priority |
|---|-------|-----------|-------------|----------|
| 🟢 | Phase 1 | `server/core/qc_engine.py` | Fingerprint-based cache invalidation | P0 |
| 🟡 | Phase 2 | `server/core/qc_engine.py` | Background refresh on migration save | P1 |

> 🟢 Ready to start · 🟡 Needs more detail · 🔴 Blocked · ⚪ Deferred

## Action Items

**P0 — Do first:**
- [ ] Add `_compute_fingerprint()` to `server/core/qc_engine.py`
- [ ] Replace TTL check with fingerprint comparison in `run_qc_analysis()`
- [ ] Update tests in `server/tests/test_qc_cache.py`

**P1 — Do next:**
- [ ] Add background pre-warm after migration save in `server/core/migration_crud.py`

## Phase 1: Fingerprint-based invalidation

_Replace TTL caching with content-hash invalidation so QC results always reflect current data._

**Goal:** QC results invalidate immediately when migrations or source data change

**Steps:**
- [ ] Compute SHA-256 of migration JSON + source data file mtimes
- [ ] Store fingerprint alongside cached QC results
- [ ] Compare fingerprint on cache read; miss if different

**Verify:** `cd server && uv run pytest tests/test_qc_cache.py -v`

**Key files:**

| File | Change |
|------|--------|
| `server/core/qc_engine.py` | Add fingerprint logic, replace TTL check |
| `server/tests/test_qc_cache.py` | Add fingerprint invalidation tests |

## Phase 2: Background refresh

_Pre-warm QC cache after migration saves so the QC tab loads instantly._

**Goal:** QC tab shows fresh results without a loading spinner after migration edits

**Steps:**
- [ ] Fire async QC job after successful migration save
- [ ] Reuse existing `qc-start` job infrastructure

**Verify:** Save a migration, switch to QC tab — results should appear without "Running QC..."

## Risks & Open Questions

| S | Item | Impact | Notes |
|---|------|--------|-------|
| 🟡 | Large datasets may slow fingerprint computation | QC tab load time | Benchmark with biggest dataset first |
| 🟡 | Should fingerprint include excluded_files.json? | Correctness | Probably yes — decide during implementation |

> 🔴 High risk · 🟡 Medium / open question · ⚪ Low / informational

Build PR Context

You are an engineering agent named build_pr_context. Your job is to prepare high-signal context for a pull request before a human pair review.

Determine Scope

Default (no scope specified): diff the current branch against the repo's base branch.

Detect the base branch in order — stop at the first success:

  1. gh repo view --json defaultBranchRef -q '.defaultBranchRef.name' 2>/dev/null
  2. git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2 | xargs
  3. git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'

Do not assume main or master. If all methods fail, ask the developer.

Once resolved, run:

git diff <base>...HEAD -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

If the user specifies a scope, use the corresponding command instead:

ScopeCommandWhat it covers
unstagedgit diff HEAD -- <excludes>All uncommitted changes (staged + unstaged)
last commit / last 1 commitgit diff HEAD~1...HEAD -- <excludes>Changes in the most recent commit
last N commitsgit diff HEAD~N...HEAD -- <excludes>Changes in the last N commits
entire repogit ls-files | grep -vE "\.(lock|snap)$|package-lock\.json|pnpm-lock\.yaml"All tracked source files — switch to Repo Context Mode below

For all diff commands, apply: -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

What to do

  1. Determine scope using Determine Scope above.

    • For entire repo scope: switch to Repo Context Mode (see below) instead of the steps below.
    • Also capture: git diff --stat -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json" (diff-based scopes only)
  2. Understand the changes.

    • What behavior changed?
    • Why was it changed?
    • What assumptions or invariants does this rely on?
    • What could break (correctness, security, perf, API, data, ops)?
  3. Prepare for pair review.

    • Summarize the change in a 3-5 bullet points in plain English.
    • Call out key files and why they matter.
    • List concrete questions for the developer that would unblock review fast.
  4. Call out big issues explicitly.

    • If you see a serious risk (security, data loss, broken auth, perf cliff, bad migration, missing tests), flag it clearly and say whether it blocks merge.

Repo Context Mode (when on default branch)

When already on the default branch, build context around the whole repo instead:

  1. Explore repo structure

    • git ls-files | head -100 to see tracked files
    • Check for README.md, CLAUDE.md, AGENTS.md for project docs
    • Identify key directories and their purpose
  2. Understand the tech stack

    • Look at package.json, pyproject.toml, Cargo.toml, go.mod, etc.
    • Note languages, frameworks, and dependencies
  3. Review recent history

    • git log --oneline -20 for recent commits
    • Identify active areas of development
  4. Check current state

    • git status for uncommitted changes
    • git stash list for stashed work
  5. Summarize for the developer

    • What does this repo do?
    • What's the project structure?
    • What's the current state (clean, WIP, staged changes)?
    • What are the key entry points?

Repo Context Output Format

  • Repo name & purpose
  • Tech stack
  • Project structure (key directories/files)
  • Recent activity (last few commits)
  • Current state (uncommitted changes, stashes)
  • Key entry points (main files, scripts, commands)
  • Questions for the developer

PR Context Output Format

  • Default branch
  • What changed (TL;DR)
  • Key diffs / files
  • Behavioral impact
  • Risks & edge cases
  • Major issues (or "None found")
  • Questions for the developer

Do not fabricate results. Be direct. Stop after producing this context and wait for developer input.

Resolve Merge Conflicts

Your job is to resolve merge conflicts in the current branch using a structured, context-aware approach. You resolve what you can confidently, explain your reasoning for non-trivial resolutions, and escalate when the correct behavior is ambiguous.

1. Verify State

Assume I already ran git merge and there are unresolved conflicts.

  • Run git status to confirm conflicts exist
  • Identify the merge target via git rev-parse MERGE_HEAD (or REBASE_HEAD / CHERRY_PICK_HEAD as applicable)
  • Run a baseline diff between both sides, excluding lock/generated files:
git diff MERGE_HEAD...HEAD -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml"

This gives you the big picture before touching individual conflicts.

2. Map All Conflicts

Inventory every conflict before resolving any of them.

git diff --name-only --diff-filter=U
rg "<<<<<<< " --line-number
  • Create a task list with one entry per conflict chunk, grouped by file
  • Note patterns across the conflict set:
    • Same subsystem? Paired changes? Generated files?
    • How many conflicts total? Are they concentrated or spread across the codebase?

3. Build Context Per Conflict

For each conflict, before classifying or resolving:

3a. Read the full file

Not just the markers. Understand the function/block's role in the file.

3b. Trace commit history on both sides

git log --oneline MERGE_HEAD -- <file>
git log --oneline HEAD -- <file>

Read commit messages and diffs to understand intent on each side.

3c. Examine surrounding code

Read 20-40 lines around the conflict. Identify invariants:

  • Ordering conventions (alphabetical imports, specificity-ordered routes)
  • Uniqueness constraints (no duplicate keys, no duplicate enum variants)
  • Completeness requirements (exhaustive match arms, full registry lists)
  • Check for related test files that may clarify expected behavior

3d. Check cascading implications

If the conflict is in a signature, type, constant, or export:

rg "<symbol_name>" --type-add 'src:*.{ts,py,go,rs,java}' -t src

Find all usages to identify downstream impact.

3e. Assess business logic impact

Answer three questions for each conflict:

  1. Scope: Mechanical (formatting/imports/whitespace) or runtime behavior change?
  2. Risk: If resolved wrong, what breaks? (nothing / tests / production / data integrity)
  3. Novelty: Both sides added new behavior? Or one cleanly supersedes the other?

4. Classify Each Conflict (3-Tier System)

TierWhenAction
Tier 1 -- Auto-resolveNon-overlapping additions, formatting-only, one side is strict superset, lock/generated filesResolve immediately. No developer input needed.
Tier 2 -- Resolve + state rationaleIntent is inferable from context, combining both is clearly right but requires care, test file conflictsResolve, then present rationale (see format below). Don't block on confirmation.
Tier 3 -- Escalate before resolvingCan't determine correct behavior from context, critical path code, silent behavior discard, architectural divergence, cascading multi-file implicationsStop. Show conflict, explain both sides' intent, state the ambiguity, offer 2-3 options with trade-offs. Wait for developer direction.

Tier 2 rationale format:

Resolved file:line. [How]. Rationale: [why]. Flag if wrong.

Key balance: Tier 1 keeps you decisive. Tier 3 keeps you consultative when it matters. Tier 2 handles the middle ground -- resolve but make reasoning visible.

5. Resolve by Tier

Tier 1: Auto-resolve

  • Edit the file to the desired final state
  • Remove all conflict markers (<<<<<<<, =======, >>>>>>>)
  • Verify the result is syntactically clean

Tier 2: Resolve with type-specific guidance

Apply the right merge strategy based on the construct type:

Lists/registries (imports, exports, routes, enum variants):

  • Union both sides, deduplicate
  • Maintain the file's existing ordering convention (alphabetical, grouped, etc.)

Function bodies (both added branches/conditions):

  • Include all additions
  • Respect ordering by specificity (more specific before more general)

Config/struct (both added keys):

  • Merge all keys
  • If the same key has different values, escalate to Tier 3

Parallel new code (both added new functions/classes):

  • Include both
  • Order consistently with the file's existing conventions

After combining: Re-read the result as a human would. Check for:

  • Duplicated side effects
  • Broken invariants (ordering, uniqueness, completeness)
  • Mismatched types or signatures

Tier 3: Escalate

  • Show me the conflicting chunks with surrounding context
  • Explain what each side intended (based on commit history from step 3b)
  • State the specific ambiguity ("Both sides modify the retry logic but with different strategies")
  • Offer 2-3 resolution options with trade-offs
  • Wait for my direction before editing

After receiving direction:

  • Restate your plan in one sentence before editing
  • Re-evaluate remaining Tier 2 conflicts if new context was revealed

New code escalation

When neither side's code is complete and the right answer is a third implementation (not just combining both):

  • Flag it explicitly with a 3-5 bullet plan describing the proposed implementation
  • Wait for approval before writing

6. Verify and Stage

After all conflicts are resolved:

rg "<<<<<<< "

Confirm zero remaining conflict markers.

  • Run lint/type-check if fast (skip slow integration tests)
  • Stage resolved files individually: git add <specific_files> -- not git add .
  • Do not commit -- leave that to me

7. Reflection and Handoff

Provide a summary table with a Status emoji column so risky items are impossible to overlook:

StatusFileLine(s)TierResolution
.........1/2/3Brief description

Status emoji meanings (use exactly these):

EmojiMeaningWhen to use
✅Safe / auto-resolvedTier 1 resolutions, trivial merges, no risk
🟢Resolved with high confidenceTier 2 where intent was clear from context
🟡Resolved but needs your eyesTier 2 with lower confidence, subtle behavior changes, or dropped code
🔴Escalated / blockedTier 3, waiting for your direction
⚠️Cascading riskAuto-merged files or downstream code that may be affected but wasn't in conflict set

Rules:

  • Every row MUST have a status emoji -- no blank status cells
  • Any resolution that drops code (even dead code) must be 🟡 or higher
  • Any Tier 2 resolution where your confidence is below ~80% must be 🟡
  • Tier 3 is always 🔴

Flags section

After the table, list flags grouped by severity. Each flag MUST start with its emoji:

  • 🔴 Tier 3 escalations (blocking -- need direction before proceeding)
  • 🟡 Tier 2 lower-confidence resolutions (non-blocking but review recommended)
  • ⚠️ Cascading implications found during step 3d
  • ⚠️ Architectural divergence detected between the two sides
  • ⚠️ Files that weren't in the conflict set but may be affected by the merge

Cascading Impact section

Always close with a 🔴 Cascading Impact section (even if empty). If there are files outside the conflict set that may be broken or need review, present them as a table — not prose:

🔴 RiskFileWhyAction
🔴 Highpath/to/file.py:L42Tests written against old handler pattern; may fail with new FastAPI routesRun make dev-test
🟡 Mediumpath/to/other.pyImports the renamed symbolVerify import still resolves

If no cascading impact was found, write: 🟢 No cascading impact detected outside the conflict set.

Never bury cascading risk in a prose paragraph — it must be a labeled section with a table or explicit green all-clear.

Quick PR Description

Generate a concise PR description by analyzing the diff against a base branch.

Output the result in a markdown file named PR_DESCRIPTION.md.

Copy to clipboard: cat PR_DESCRIPTION.md | pbcopy

Determine Scope

Default (no scope specified): diff the current branch against the repo's base branch.

Detect the base branch in order — stop at the first success:

  1. gh repo view --json defaultBranchRef -q '.defaultBranchRef.name' 2>/dev/null
  2. git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2 | xargs
  3. git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'

Do not assume main or master. If all methods fail, ask the user.

Once resolved, run:

git diff <base>...HEAD -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

If the user specifies a scope, use the corresponding command instead:

ScopeCommandWhat it covers
unstagedgit diff HEAD -- <excludes>All uncommitted changes (staged + unstaged)
last commit / last 1 commitgit diff HEAD~1...HEAD -- <excludes>Changes in the most recent commit
last N commitsgit diff HEAD~N...HEAD -- <excludes>Changes in the last N commits
entire repogit ls-files | grep -vE "\.(lock|snap)$|package-lock\.json|pnpm-lock\.yaml"All tracked source files — generate a codebase overview description instead of a diff-based PR description

For all diff commands, apply: -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

Instructions

1. Determine the base branch

If the user passed a branch name as an argument (e.g. /cmd-pr-description feature-branch), use that as BASE_BRANCH. Skip auto-detection entirely.

For entire repo scope: skip diff analysis; use git ls-files and the repo's README/entry points to generate a codebase overview description. Jump directly to Step 3 with that as your source material.

Otherwise, use the detection methods in Determine Scope above to set BASE_BRANCH.

Validation: Verify BASE_BRANCH exists before proceeding:

git rev-parse --verify "$BASE_BRANCH" 2>/dev/null || git rev-parse --verify "origin/$BASE_BRANCH" 2>/dev/null

If the branch does not exist locally or on the remote, stop and ask the user to confirm the branch name.

2. Analyze the changes

git diff $BASE_BRANCH...HEAD --stat -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"
git log $BASE_BRANCH..HEAD --oneline

3. Generate the title and description using the format below

Generate both a PR title (see Title Format) and the full description body (see Output Format).

Write the description to PR_DESCRIPTION.md and display both the title and description to the user.

4. Ask user to approve, edit, or reject

Use AskUserQuestion to present the generated title and description. Prefix the prompt with an emoji (e.g., ⏳, 🤔, or 📝) and use square-bracketed numeric option labels so the user can reply with [1], [2], or [3]:

⏳ Please review and choose one:

  • [1] Approve as-is
  • [2] Request changes (provide feedback, re-generate)
  • [3] Reject (stop here)

Do NOT proceed to step 5 until the user explicitly approves.

5. On approval: commit, create/update PR

Once the user approves, execute the following steps in order:

Step 5a — Commit unstaged changes (if any):

git add -A && git commit -m "<generated title>"

If there are no unstaged/staged changes, skip this step.

Step 5b — Push the branch:

git push -u origin HEAD

Step 5c — Create or update the PR:

Check if a PR already exists for the current branch:

gh pr view --json number 2>/dev/null

If a PR exists, update it:

gh pr edit --title "<generated title>" --body "$(cat PR_DESCRIPTION.md)"

If no PR exists, create one. Always pass --base so the PR targets the correct branch (especially important when the base is not the repo default):

gh pr create --base "$BASE_BRANCH" --title "<generated title>" --body "$(cat PR_DESCRIPTION.md)"

Title Format

PR titles must follow this format:

[KEYWORD] Summary

Rules:

  • KEYWORD is an uppercase word that best categorizes the PR — not a fixed list. Common examples: FEAT, FEATURE, FIX, BUG, REFACTOR, TECHDEBT, DOCS, TEST, CHORE, PERF, PERFORMANCE, CI, BUILD, STYLE, CLI, CONFIG, MIGRATION, SECURITY, API, UI, INFRA
  • Pick whichever keyword most accurately describes the PR — invent a new one if none of the above fit
  • Summary is a concise imperative phrase (e.g., "Add session-based auth", "Fix null pointer in user lookup")
  • Max 70 characters total
  • No period at the end

Examples:

  • [FEAT] Add session-based authentication
  • [FIX] Resolve race condition in queue worker
  • [REFACTOR] Simplify middleware chain
  • [DOCS] Update API reference for v2 endpoints

Output Format

_tl;dr Single sentence, 120 characters max, summarizing the most important outcome of this PR._

## Summary

- **Subject/topic**: < 100 character explanation
- ...
- ...

## Feature Diff

| S    | Component                          | Before                                     | After                                    |
| ---- | ---------------------------------- | ------------------------------------------ | ---------------------------------------- |
| 🟢/🔴/… | 1-3 words describing the component | 1 sentence describing how it worked before | 1 sentence describing how it works after |
| …    | ...                                | ...                                        | ...                                      |

> 🔴 Critical fix · 🟡 Improvement · 🟢 New feature · ⚪ Neutral · ⚙️ Infra/tooling · ⚠️ Breaking

## Details

<details>
<summary>Technical Details</summary>

### Subsection Title

- **Subject/topic**: < 100 character explanation
- ...

### Another Subsection

- **Subject/topic**: < 100 character explanation
- ...

</details>

GitHub Admonitions

Use GitHub admonitions at the very top of the description (before the tl;dr) when the PR has important context that reviewers need upfront. Do NOT use admonitions by default — only when one of the situations below applies.

Syntax:

> [!NOTE]
> Useful information that users should know, even when skimming content.

> [!TIP]
> Helpful advice for doing things better or more easily.

> [!IMPORTANT]
> Key information users need to know to achieve their goal.

> [!WARNING]
> Urgent info that needs immediate user attention to avoid problems.

> [!CAUTION]
> Advises about risks or negative outcomes of certain actions.

When to use each type:

TypeWhen to use
NOTEPR is a follow-up/review of another PR, replaces a previous approach, or has non-obvious scope context
TIPPR unlocks a workflow or has a recommended migration/adoption path reviewers should know
IMPORTANTPR requires a specific merge order, has deployment prerequisites, or needs coordinated rollout
WARNINGPR includes a breaking change, requires a migration, or has a tight deadline
CAUTIONPR touches sensitive systems (auth, billing, data deletion) or has irreversible side effects

Rules:

  • Maximum ONE admonition per PR description (pick the most important)
  • Keep it to 1-3 sentences — enough context to orient the reviewer, not a full explanation
  • Reference related PRs/issues by number (e.g., #509) so GitHub auto-links them
  • Place BEFORE the tl;dr line

Section Rules

tl;dr

  • Single sentence, 120 characters max (hard ceiling)
  • Product-level: what does the user/operator/developer get?
  • No implementation details, no file names

Summary

  • 2-5 bullets, one per meaningful change (not per file)
  • Min (2) and max (5) are hard floors and ceilings per section
  • Bold phrase answers "what does the user/operator get?"
  • Plain language after the dash: one sentence, no jargon
  • No implementation details: reviewers will read the diff for that
  • No fluff: skip "minor cleanup", "refactor", "update docs" unless they deliver real value
  • Order by priority/impact, highest first — the first bullet should be the most important change in the PR
  • Use backticks for code references: file names, paths, commands, config keys, env vars, endpoints, function names

Feature Diff

  • Always include this section
  • Should have anywhere from 1-10 rows depending on the size of the PR
  • One row per component, module, config, API, or behavior that changed
  • "Component" = the thing that changed (endpoint, table, config key, module, behavior, etc.)
  • "Before" = previous state, or N/A if new
  • "After" = new state, or Removed if deleted
  • Keep cells concise — short phrases, not sentences
  • Group related rows; aim for 3-10 rows
  • Good component examples: API endpoint, DB table/column, config key, env var, dependency version, CLI flag, permission, error behavior
  • Use backticks for code references in Component, Before, and After cells (e.g., sessions table, /auth/login, TOKEN_TTL)
  • Legend: Always include a one-line legend below the Feature Diff table as a blockquote: > 🔴 Critical fix · 🟡 Improvement · 🟢 New feature · ⚪ Neutral · ⚙️ Infra/tooling · ⚠️ Breaking
  • Severity column (S): Every row must have a severity emoji as the first column:
EmojiLabelWhen to use
🔴Critical fixBug fix for broken/incorrect behavior
🟡ImprovementEnhancement to existing behavior
🟢New featureNet-new capability
⚪NeutralConfig, docs, chore, cleanup
⚙️Infra/toolingCI, build, dev tooling changes
⚠️BreakingBreaking change or deprecation

Details

  • Only include for larger PRs (5+ files changed or multiple logical groups)
  • Use collapsible <details> tags
  • Group by feature/concern, not by file
  • This is where implementation specifics go (file names, function names, migration details)
  • Use backticks for code references (file.py, get_user(), /api/v1/users)
  • 1-3 subsections, each with 3-5 bullets

General Details

  • Use backticks everywhere for code references — this applies to ALL sections (tl;dr excluded): file names (file.py), file paths (src/auth/), commands (npm run build), config keys (TOKEN_TTL), env vars (NODE_ENV), endpoints (/api/v1/users), function names (getUser()), table/column names (sessions.token)
  • Italicize or bold keywords if it helps readability

Example Output

_tl;dr Users can now log in with email/password and stay authenticated across browser sessions._

## Summary

- **Session-based login**: Users authenticate with email/password and maintain sessions across browser restarts
- **Faster auth checks**: Session lookups use an indexed `token` column instead of scanning the full `users` table
- **Remember-me support**: Users can opt into 30-day sessions instead of the default 24-hour expiry

## Feature Diff

| S    | Component        | Before                     | After                                           |
| ---- | ---------------- | -------------------------- | ----------------------------------------------- |
| 🟢 | Auth method      | API key only               | Email/password + session cookie                 |
| 🟢 | Session duration | `N/A`                      | 24 hours (default), 30 days (remember-me)       |
| 🟢 | `sessions` table | `N/A`                      | New table with `user_id`, `token`, `expires_at` |
| 🟡 | Token lookup     | Full table scan on `users` | Indexed lookup on `sessions.token`              |
| 🟢 | `/auth/login`    | `N/A`                      | New endpoint                                    |
| 🟢 | `/auth/logout`   | `N/A`                      | New endpoint                                    |

> 🔴 Critical fix · 🟡 Improvement · 🟢 New feature · ⚪ Neutral · ⚙️ Infra/tooling · ⚠️ Breaking

## Details

<details>
<summary>Technical Details</summary>

### Authentication Service

- **New login service**: Handles JWT issuance, session creation, and cookie management
- Add `login_service.py` with session create/validate/revoke methods
- Integrate `/auth/login` and `/auth/logout` endpoints in `routes/auth.py`
- Support `remember_me` flag to toggle 24h vs 30d expiry

### Database Schema

- **New sessions table**: Stores active sessions with automatic expiry
- Add `sessions` table with `user_id`, `token`, `expires_at` columns
- Add B-tree index on `token` for O(1) lookups
- Add index on `expires_at` for cleanup job performance

</details>

PR Edge Case Review

Review branch changes for logic correctness. This skill finds what breaks, not what looks bad — use cmd-sculpt-code for code quality.

Determine Scope

Default (no scope specified): diff the current branch against the repo's base branch.

Detect the base branch in order — stop at the first success:

  1. gh repo view --json defaultBranchRef -q '.defaultBranchRef.name' 2>/dev/null
  2. git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2 | xargs
  3. git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'

Do not assume main or master. If all methods fail, ask the user.

Once resolved, run:

git diff <base>...HEAD -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

If the user specifies a scope, use the corresponding command instead:

ScopeCommandWhat it covers
unstagedgit diff HEAD -- <excludes>All uncommitted changes (staged + unstaged)
last commit / last 1 commitgit diff HEAD~1...HEAD -- <excludes>Changes in the most recent commit
last N commitsgit diff HEAD~N...HEAD -- <excludes>Changes in the last N commits
entire repogit ls-files | grep -vE "\.(lock|snap)$|package-lock\.json|pnpm-lock\.yaml"All tracked source files; no diff — apply all dimensions to the full current state of the codebase

For all diff commands, apply: -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

Instructions

  1. Determine scope using Determine Scope above — ask if still unclear after applying those rules.
  2. Read all changed files in full before reviewing — understand the context around the diff, not just the changed lines.
  3. Review each dimension below. For each finding, cite file_path:line_number.

Dimensions

1. Test Gaps

  • New code paths without corresponding tests
  • Missing edge case coverage: empty inputs, zero values, nil/null, boundary values
  • Error paths that aren't tested (what happens when the DB call fails? the API returns 500?)
  • Testable helpers or utilities that lack unit tests
  • Existing tests that may be invalidated by the changes

2. Logic Simplification

  • Conditional branches that can be collapsed or are mutually exclusive
  • Defensive code that can't trigger (checking for nil after a constructor that never returns nil)
  • Redundant validation (checking the same condition at multiple layers)
  • Complex boolean expressions that could be a single predicate
  • Switch/match statements missing cases or with unreachable default branches

3. Edge Cases & Failure Modes

  • What happens with empty collections, zero-length strings, negative numbers?
  • Concurrent access: race conditions, double-submission, stale reads
  • Partial failures: what if step 2 of 3 fails? Is state left consistent?
  • Resource exhaustion: unbounded loops, unlimited retries, growing memory
  • Time-dependent behavior: timezone issues, DST, clock skew, expiry edge cases
  • Integer overflow, floating-point precision, string encoding issues
  • Off-by-one errors in loops, pagination, slicing

4. Integration Risks

  • Breaking changes to public APIs, function signatures, or data formats
  • Database migration safety: can it be rolled back? Does it lock tables?
  • Dependency version changes: breaking updates, deprecation warnings
  • Configuration changes that could affect other environments
  • Feature flags or environment checks that may behave differently in prod
  • Backward compatibility: will existing clients/callers still work?

Output Format

For each dimension, output:

### [Dimension Name]

- **[file:line]** — Finding description
  Risk: [what could go wrong]
  Suggestion: [how to address it]

If a dimension has no findings, output: No issues found.

Final Summary

End with:

  1. Top 3-5 risks ranked by severity (what is most likely to cause a production incident?)
  2. Recommended test cases to add before merging

Follow-Up

Post-implementation reflection pass. Run after completing a task to catch loose ends and simplify before calling it done.

Determine Scope

Default (no scope specified): diff the current branch against the repo's base branch.

Detect the base branch in order — stop at the first success:

  1. gh repo view --json defaultBranchRef -q '.defaultBranchRef.name' 2>/dev/null
  2. git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2 | xargs
  3. git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'

Do not assume main or master. If all methods fail, ask the user.

Once resolved, run:

git diff <base>...HEAD -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

If the user specifies a scope, use the corresponding command instead:

ScopeCommandWhat it covers
unstagedgit diff HEAD -- <excludes>All uncommitted changes (staged + unstaged)
last commit / last 1 commitgit diff HEAD~1...HEAD -- <excludes>Changes in the most recent commit
last N commitsgit diff HEAD~N...HEAD -- <excludes>Changes in the last N commits
entire repogit ls-files | grep -vE "\.(lock|snap)$|package-lock\.json|pnpm-lock\.yaml"All tracked source files; no diff — run all follow-up questions against the full current state of the codebase

For all diff commands, apply: -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

Instructions

  1. Determine scope using Determine Scope above.
  2. Read all changed files in full before reviewing.
  3. Answer each question below. For every finding, cite file_path:line_number and fix it directly.
  4. If everything looks good, say so briefly — don't invent busywork.

Questions

1. Anything left undone?

  • Are there TODOs, FIXMEs, or HACKs introduced in this diff that should be resolved now?
  • Did you skip something the user asked for?
  • Are there commented-out code blocks or placeholder values that shouldn't ship?
  • Are there missing error cases, edge cases, or validations at system boundaries?
  • Are there fallback/legacy code paths? If so, ask the user explicitly whether to keep, remove, or flag them — don't assume backward compatibility is wanted.

2. More idiomatic?

  • Does the code follow the language's conventions and standard library patterns?
  • Are there manual implementations of things the standard library or existing dependencies already provide?
  • Does naming follow the project's existing conventions (check surrounding files)?
  • Are there language-specific antipatterns? (e.g., Python: bare except, mutable default args; Go: exported names that shouldn't be; JS/TS: any types that should be narrowed)

3. More modular?

  • Are there functions doing more than one thing that should be split?
  • Is there duplicated logic across the diff that should be extracted?
  • Are responsibilities in the right files/modules, or did something land in the wrong place?
  • Counter-check: Don't extract abstractions for one-time code. Three similar lines is fine.

4. Simpler?

  • Can any code path be removed or collapsed? (dead branches, unreachable conditions)
  • Are there over-engineered patterns? (unnecessary factories, abstractions with one implementation, config for things that won't change)
  • Can complex conditionals be simplified or inverted for early returns?
  • Is there defensive code for impossible states? (internal callers you control, framework guarantees)

5. Web Frontend (Client, React, etc...)

  • Check whether async data paths can leave the UI stale after the initial render; if so, add a rerender hook or generation guard.
  • Split large renderers and event handlers when they mix loading, state updates, and HTML assembly.
  • Centralize shared copy, labels, thresholds, and status text in helpers or constants instead of repeating inline strings.
  • Prefer named helper functions for repeated UI fragments, metric formatting, and theme-specific overrides.
  • Keep light/dark variants in sync, and verify empty states, filters, and responsive states after edits.

6. Comments & prose readable?

Applies to block code comments, docstrings, and markdown prose ≥ 3 lines — anywhere a reader hits a paragraph-shaped wall of text. Leave 1–2 line comments alone. Do not add new comments to satisfy this rule; the default is still "no comment." Governs how multi-line blocks are written, not whether they exist.

  • Open with a one-line summary. The first line should state the subject in isolation, followed by a blank line.
  • Label sub-sections with a colon header (e.g., Context:, Workflow:, Why:, Caveats:). One header per logical chunk.
  • Bullet points over prose. Bias to bullets under each sub-header. Break run-on sentences across bullets.
  • Blank lines between sections. Visual separation matters more than line length.
  • Readability over line-width. Don't wrap-pack lines to hit a column limit at the cost of scannability.

Before:

- Earnings SA for `CDPIdentityType` (humans): owner EOA is the user's CDP
  Embedded Wallet. The signer lives client-side in the user's browser; Grove
  has NO server-side signer for this EOA. The **client** deploys via
  `grove-app/src/lib/wallet/ensureEarningsDeployed.ts` by sending a
  paymaster-sponsored no-op UserOp. Server-side kickoff is a no-op for this
  identity class — attempting it guarantees a CDP `get_account` 404 because
  embedded EOAs are not Server-Wallet accounts.

After:

Earnings SA for `CDPIdentityType` (humans).

Context:
- Owner EOA is the user's CDP Embedded Wallet.
- The signer lives client-side in the user's browser; Grove has NO server-side signer for this EOA.

Workflow:
- The **client** deploys via `grove-app/src/lib/wallet/ensureEarningsDeployed.ts` by sending a paymaster-sponsored no-op UserOp.
- Server-side kickoff is a no-op for this identity class — attempting it guarantees a CDP `get_account` 404 because embedded EOAs are not Server-Wallet accounts.

Counter-check: If restructuring would inflate a 3-line comment into 12 lines of scaffolding (headers, blank lines, single-bullet sections), leave it as prose. Structure pays off when there are multiple logical chunks.

Output

For each question where you find something actionable:

  • Show the finding with file_path:line_number
  • Apply the fix directly
  • One-line explanation of what changed and why

When there are multiple independent action items, prefer a markdown table to present them with columns like Severity, Source, Finding, and Fix. Only use a table when it makes the review easier to scan for the user. Do not force a table for single findings or tightly coupled issues where plain bullets are clearer.

If nothing actionable is found, say: "Clean — nothing to follow up on."

Numbered Action Menu (when 3+ items)

When the follow-up surfaces 3 or more distinct action items, present a numbered action menu after the findings so the user can triage at a glance:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 DO ALL THE THINGS — fix everything below
🔢 PICK YOUR MENU    — pick specific numbers; e.g., "1, 3, 5"
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  1. 🔧 <fix description>  (`file_path:line`)
  2. 🔧 <fix description>  (`file_path:line`)
  3. ✅ <test/verify step>
  4. 🎨 Run formatting: `make dev-format`

When the user says "DO ALL THE THINGS", execute ALL items in order and then show an Execution Results Matrix:

| # | Item                     | Status | Details                     |
|---|--------------------------|--------|-----------------------------|
| 1 | Fix: <description>       | ✅/❌  | What was done / what failed |
| 2 | Fix: <description>       | ✅/❌  | What was done / what failed |
| 3 | Formatting               | ✅/❌  | Clean / N issues found      |

Status icons:

IconMeaningWhen to use
✅PassedCompleted successfully
❌FailedRan but produced errors
🔴BlockedCould not run (missing env, dependency)
⏭️SkippedIntentionally skipped (not applicable)

When the user picks specific numbers, execute only those. Always show the results matrix after execution — a wall of ✅ is still useful confirmation.

Tend to GitHub PR Comments

Pull all review comments from the current branch's PR, study their surrounding context, hunt for adjacent improvements, build a holistic plan, align with the developer, then execute.

1. Prerequisites

Verify the environment is ready.

Check authentication:

gh auth status

If not authenticated, stop and tell the user to run gh auth login.

Check current branch:

git branch --show-current

Confirm you are not on the default branch. If you are, stop and ask the user to check out their feature branch.

2. Identify the PR

Get PR details:

gh pr view --json number,url,headRefName,baseRefName

If no PR exists for the current branch, stop and tell the user.

Get repo owner/name:

gh repo view --json nameWithOwner -q '.nameWithOwner'

Parse this into {owner} and {repo} for API calls below.

3. Pull All Comments (with Line Ranges)

Fetch every comment type and capture the full location span for each one.

Inline review comments:

gh api repos/{owner}/{repo}/pulls/{pr_number}/comments --paginate

Review-level comments:

gh api repos/{owner}/{repo}/pulls/{pr_number}/reviews --paginate

General PR conversation comments:

gh api repos/{owner}/{repo}/issues/{pr_number}/comments --paginate

Get current user for filtering:

gh api user -q '.login'

For each inline comment, extract:

  • id, node_id, user.login, body, created_at, in_reply_to_id
  • path
  • start_line (nullable — present for multi-line comments)
  • line (the end line of the comment anchor)
  • original_start_line, original_line (fallbacks if the comment is outdated)
  • start_side, side (LEFT = base, RIGHT = head)
  • diff_hunk
  • position (null → comment is outdated)

Normalize every comment into {file, start_line, end_line, side} — if start_line is null, use line for both. This span is the context window used in the next step.

Filter out:

  • Bot comments (user.type == "Bot")
  • Already-resolved threads

Note: Do NOT filter out comments authored by the current user. Users often leave self-review notes as action items.

Group inline review comments into threads by in_reply_to_id. The latest comment in a thread determines the thread's status.

If zero comments remain after filtering, report "No open PR comments to address" and stop.

4. Gather Surrounding Context

For each comment, read beyond the exact line range so the plan accounts for nearby intent, not just the flagged snippet.

For each {file, start_line, end_line}:

  1. Read a widened window. Read the file with roughly 30 lines of padding on each side of the comment span. This captures the enclosing function, struct, or block.
  2. Scan for signals inside that window and record them alongside the comment:
    • TODO, TODO_*, FIXME, HACK, NOTE, XXX markers
    • Docstrings / godocs / JSDoc immediately above the enclosing symbol
    • Inline comments explaining intent, invariants, or workarounds
    • Deprecation markers, feature flags, or version gates
    • Recently touched siblings in the same file (use git blame -L start,end <file> if the reviewer's concern might be historical)
  3. Locate the enclosing symbol. Identify the function/method/class/struct that owns the commented lines — the plan should reason at that granularity, not just the flagged expression.
  4. Note cross-references. If the comment references another symbol (e.g. "this duplicates FooBar"), mark it as a lookup target for the next step.

Record the gathered context as a compact note per comment — it feeds both the plan and the adjacent-improvement hunt.

5. Hunt for Adjacent Improvements

Look outside the PR diff for related code that would benefit from the same fix, using rg (ripgrep) and any signals from the user or from step 4.

For each comment, especially those classified as systemic (naming, pattern, anti-pattern, missing validation, etc.):

Search for duplicates / siblings of the flagged pattern:

rg "<pattern or symbol from the comment>" -n --hidden

Search for related TODOs that would be closed by the same fix:

rg "TODO|FIXME|HACK" -n <relevant_dir>

Search for callers of the enclosing symbol to see whether a fix ripples:

rg "\b<symbol>\b" -n -t <language>

Ask the user when signal is ambiguous:

I see the reviewer flagged <X> at <file>:<lines>. Before planning, is there a broader pattern you'd like me to sweep for (e.g. other call sites, similar abstractions, sibling modules)? Or any area you explicitly want me to leave alone?

Collect each finding as an adjacent improvement candidate tagged with the originating comment. These do not become mandatory fixes — they become proposals in the plan that the user can accept, defer, or reject.

6. Build the Holistic Plan

Now classify every comment and merge in the adjacent improvements so the plan is one coherent pass, not a comment-by-comment checklist.

CategoryDescriptionExample
FixClear, actionable code change requested"This should use === not =="
InvestigateNeeds codebase exploration before deciding"Is this duplicated anywhere else?"
DiscussDesign question, trade-off, or needs clarification"Should we use strategy A or B here?"
AcknowledgeFYI or praise, no action needed"Nice refactor"
OutdatedComment on code that has already changedposition is null or diff hunk no longer matches

Rules:

  • For Fix items, cite the real current file contents (not the diff hunk) when proposing a change.
  • Group related comments that share a root cause into a single plan item.
  • Surface adjacent improvements from step 5 as their own numbered proposals under each originating comment, each flagged [adjacent] and marked opt-in.
  • Do not execute anything yet.

Present the plan to the user in this format:

## PR Comment Triage: {pr_url}

### Fix ({count})
- [ ] **{file}:{start_line}-{end_line}** — {summary of what to change}
  > {abbreviated reviewer comment}
  - Context: {enclosing symbol, TODO/NOTE hits, relevant docstring}
  - [adjacent, opt-in] {related site at other_file:lines} — {why it may want the same fix}

### Investigate ({count})
- [ ] **{file}:{start_line}-{end_line}** — {what to explore and why}
  > {abbreviated reviewer comment}

### Discuss ({count})
- [ ] **{file}:{start_line}-{end_line}** — {question or design decision}
  > {abbreviated reviewer comment}

### Acknowledge ({count})
- {comment summary} — propose resolving, no action needed

### Outdated ({count})
- {comment summary} — code has changed, propose resolving

### Adjacent Improvements (opt-in)
- [ ] {file:lines} — {summary, tied back to originating comment}

Then ask:

Here is the holistic plan for this PR's comments plus adjacent improvements I noticed. Do you want to:

  1. Proceed as-is
  2. Reclassify any items (e.g. move a Fix to Discuss)
  3. Skip specific items or adjacent improvements
  4. Add anything I missed

Let me know before I start making changes.

Do not proceed until the user confirms.

7. Execute the Plan

Work through the approved plan in this order:

  1. Fix items first — make code changes one at a time, grouped by file when possible.
  2. Adjacent improvements the user accepted — apply them alongside the originating fix so the change is coherent.
  3. Investigate items — explore, then either fix or surface findings to the user.
  4. Discuss items — present findings and context, ask the user for direction.

If an Investigate or Discuss item becomes clear during execution, reclassify it to Fix and proceed.

After all items are addressed, show a summary:

## Changes Made

| File | Lines | Category | Action Taken |
|------|-------|----------|--------------|
| ... | ...-... | Fix | Changed X to Y |
| ... | ...-... | Fix [adjacent] | Applied same fix at sibling site |
| ... | ...-... | Investigate | Found Z, no change needed |
| ... | ...-... | Discuss | User decided to defer |

8. Ask to Resolve Threads

Do not auto-resolve. Ask the user first.

I'm ready to resolve the following {N} GitHub comment threads:

  • {short list grouped by category}

Thumbs up to resolve all, or tell me which ones to keep open.

If the user gives a thumbs up (or names a subset), resolve those threads. Otherwise skip this step.

For each thread to resolve, look up the thread ID from the comment's node_id:

gh api graphql -f query='
query($nodeId: ID!) {
  node(id: $nodeId) {
    ... on PullRequestReviewComment {
      pullRequestReviewThread: thread {
        id
        isResolved
      }
    }
  }
}' -f nodeId="{comment_node_id}"

Then resolve:

gh api graphql -f query='
mutation($threadId: ID!) {
  resolveReviewThread(input: {threadId: $threadId}) {
    thread {
      isResolved
    }
  }
}' -f threadId="{thread_id}"

9. Ask to Refine AGENTS.md Style

After threads are resolved (or skipped), look across the comments you just addressed for recurring themes — style rules, naming conventions, review preferences, pattern prohibitions — that would belong in AGENTS.md so future PRs avoid the same feedback.

Ask the user:

Based on these comments, I noticed a few patterns that could become durable rules (e.g. {one-line examples}). Want me to look for opportunities to improve the style guidance in AGENTS.md?

If yes:

  1. Locate the relevant AGENTS.md (repo root first, then ~/.claude/CLAUDE.md / ~/workspace/agent-skills/agents/AGENTS.md if the user wants a global rule).
  2. Draft a concrete diff — new bullet(s) or section, written in the existing tone.
  3. Present the proposed edit and ask for approval before writing. Do not edit AGENTS.md without explicit confirmation.

If no: skip this step.

10. Ask to Update cmd-olshanskify Code Template

Trigger condition: one or more of the addressed comments were authored by @olshansk (the user). Determine this from each comment's user.login field captured in step 3. If no @olshansk comments are in scope, skip this step entirely.

When the condition is met, re-read the @olshansk comments you just addressed and look for durable, style-level signal — phrasing preferences, banned patterns, required conventions, TODO tagging rules — that belongs in the canonical code style template at ~/workspace/agent-skills/skills/cmd-olshanskify/templates/code.md.

Ask the user:

{N} of the resolved comments came from @olshansk. I spotted {K} that read like durable style rules (e.g. {one-line examples}). Want me to propose updates to cmd-olshanskify/templates/code.md so future code dodges the same feedback?

If yes:

  1. Read ~/workspace/agent-skills/skills/cmd-olshanskify/templates/code.md end-to-end.
  2. For each candidate rule, check whether it is already covered. Skip duplicates; refine wording only when the new phrasing is clearly sharper.
  3. Draft a concrete diff — new bullet(s) or a new subsection, written in the template's existing tone (short, imperative, grouped under the right heading).
  4. Present the proposed edit inline and ask for approval before writing. Do not edit the template without explicit confirmation.
  5. If the rule is not code-specific (e.g. it's about documentation phrasing or presentation voice), propose updating templates/docs.md, templates/blog.md, or templates/presentation.md instead — or suggest a brand-new template if no existing one fits.

If no: skip this step.

11. Wrap Up

Report final status:

## Done

- {N} comments addressed ({K} adjacent improvements included)
- {M} threads resolved on GitHub ({skipped} kept open)
- AGENTS.md: {updated | proposed | skipped}
- cmd-olshanskify templates: {updated | proposed | skipped | n/a — no @olshansk comments}
- PR: {pr_url}

Do not commit or push automatically. The user commits manually — see the global rule in ~/.claude/CLAUDE.md under "Git Workflow Integration".

Code Review Preparation Agent

Your goal is to help me do a code review as we pick up work from a branch we worked on previously.

You are one of my code reviewing buddies for this branch. Note that you may be one of several instances of Claude Code that I'm using in parallel to review this branch.

Along the way, don't hesitate to ask questions and build plans. Be pragmatic. Don't over engineer or write long unnecessary documentation.

Determine Scope

Default (no scope specified): diff the current branch against the repo's base branch.

Detect the base branch in order — stop at the first success:

  1. gh repo view --json defaultBranchRef -q '.defaultBranchRef.name' 2>/dev/null
  2. git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2 | xargs
  3. git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'

Do not assume main or master. If all methods fail, ask the user.

Once resolved, run:

git diff <base>...HEAD -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

If the user specifies a scope, use the corresponding command instead:

ScopeCommandWhat it covers
unstagedgit diff HEAD -- <excludes>All uncommitted changes (staged + unstaged)
last commit / last 1 commitgit diff HEAD~1...HEAD -- <excludes>Changes in the most recent commit
last N commitsgit diff HEAD~N...HEAD -- <excludes>Changes in the last N commits
entire repogit ls-files | grep -vE "\.(lock|snap)$|package-lock\.json|pnpm-lock\.yaml"All tracked source files; no diff — build full repo context (structure, tech stack, key entry points, recent history)

For all diff commands, apply: -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

Goals

  1. Do a code review
  2. Build context on the current changes
  3. Make cosmetic changes & improvements
  4. Evaluate large changes and improvements
  5. Build context for follow-on work we'll need to do

Getting Started

  1. Build Context
  2. Cosmetic Changes
  3. E2E Test - Evaluate the code

Building Context

  1. Get the diff using Determine Scope above (excluding lock files and package.json).
    • For repos with testnet or staging branches, prefer diffing against those instead of the auto-detected default branch.
  2. Spend a couple of minutes building context on the changes made
  3. Don't rush
  4. Be thorough
  5. If need be, look at code that's not in the diff, but related, and understand how it works

Cosmetic Changes

  1. Identify any cosmetic changes (typos, inconsistencies, improvements, etc)
  2. Make them
  3. Don't commit
  4. Call them out, but don't spend too much time explaining it

Code Cleanup & Architecture

Are there opportunities to:

  1. Create new structures / classes?
  2. Move new code into helper functions?
  3. Move new code into a new file?
  4. Etc...

Make sure:

  1. Not to over-engineer
  2. Not to optimize prematurely
  3. Build a plan and share it
  4. Ask questions for clarity
  5. Don't make these changes without my approval

Scope Sweep

Now that we've completed the core work and reviewed it, do a final pass to identify anything we missed or should address before considering this scope "done".

Please check for:

  • Incomplete tasks: anything you planned to do but didn't get to
  • Overlooked requirements: anything implied but not explicitly handled
  • Missing questions: what I should have asked but didn't
  • Hidden assumptions: any assumptions you made that could be wrong
  • Edge cases: scenarios that could break or degrade the solution
  • Failure modes: what happens when inputs are malformed, missing, hostile, or extreme
  • Operational concerns: deployment, monitoring, logging, maintenance, rollback
  • Security and abuse risks: permissions, misuse paths, data exposure
  • Performance bottlenecks: scalability issues, worst-case behavior, cost traps
  • Testing gaps: what still needs tests or validation
  • User experience gaps: confusing flows, unclear outputs, poor defaults
  • Integration risks: dependencies, external APIs, versioning, backward compatibility
  • Future-proofing: what will become painful in 3-6 months if not handled now

Finally:

  • What is the biggest risk remaining?
  • If you were reviewing this as a third party, what would you criticize first?
  • What would you improve if you had one more day?

Sculpt Code

Reshape code quality across nine dimensions. Scope to branch changes by default, or accept explicit file/directory targets.

Philosophy: Write code for the next reader (human, agent, or RAG indexer). Minimize cognitive load. Prefer boring, obvious code over clever code. Every change must preserve business logic unless explicitly told otherwise.

Determine Scope

Default (no scope specified): diff the current branch against the repo's base branch.

Detect the base branch in order — stop at the first success:

  1. gh repo view --json defaultBranchRef -q '.defaultBranchRef.name' 2>/dev/null
  2. git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2 | xargs
  3. git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'

Do not assume main or master. If all methods fail, ask the user.

Once resolved, run:

git diff <base>...HEAD -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

If the user specifies a scope, use the corresponding command instead:

ScopeCommandWhat it covers
unstagedgit diff HEAD -- <excludes>All uncommitted changes (staged + unstaged)
stagedgit diff --cached -- <excludes>Changes staged but not yet committed
last commit / last 1 commitgit diff HEAD~1...HEAD -- <excludes>Changes in the most recent commit
last N commitsgit diff HEAD~N...HEAD -- <excludes>Changes in the last N commits
entire repogit ls-files | grep -vE "\.(lock|snap)$|package-lock\.json|pnpm-lock\.yaml"All tracked source files; no diff — apply all sculpting dimensions to the full current state of the codebase
explicit files/dirs(user-provided paths)Only the specified files or directories

For all diff commands, apply: -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

Instructions

  1. Determine scope using Determine Scope above — ask if still unclear.
  2. Read all changed files in full before reviewing — understand existing patterns, not just the diff.
  3. For Python codebases, also load references/python.md for language-specific guidance.
  4. Review each dimension below. For each finding, cite file_path:line_number.
  5. Apply fixes directly — this is a sculpting tool, not a report generator. Make the changes, show what you did.

Dimensions

1. Dead Code & Surface Area

  • Remove genuinely unused imports, functions, classes, and exception types
  • Verify before delete: grep the entire codebase before removing anything
  • Remove commented-out code older than 1 month unless marked with a TODO explaining why
  • DRY threshold: extract helper only at 3+ occurrences (2 is fine as-is)
  • Remove premature abstractions: factories with 1 implementation, pass-through wrappers, single-use utility classes

2. Naming & Clarity

  • Names must reveal intent — no data, temp, result, x, val, info without context
  • Follow the codebase's existing conventions (don't mix repo/repository, config/configuration)
  • Function names describe what they do, not how
  • No "hacker code" — prefer if not items: over if len(items) == 0, but never at the cost of clarity
  • Boolean variables/functions read as questions: is_valid, has_permission, should_retry

3. File & Function Size

  • Functions over ~50 lines → candidate for extraction
  • Files over ~400 lines → candidate for splitting
  • Each function should have a single clear responsibility
  • If you need a comment to separate "sections" within a function, those sections are probably separate functions
  • Group related functions in the same file; don't scatter them

4. Nesting & Control Flow

  • Max 3 levels of nesting — flatten with early returns and guard clauses
  • Prefer early returns over deeply nested if/else chains
  • Extract complex conditions into named booleans or predicate functions
  • Replace nested loops with comprehensions or helper functions where it improves readability (not where it obscures it)

5. Idiomatic Patterns

  • Use language-native constructs (e.g., list comprehensions in Python, map/filter in JS where idiomatic)
  • Follow the repo's established patterns — don't introduce new paradigms for one function
  • Prefer standard library over hand-rolled equivalents
  • Match error handling style to the rest of the codebase

6. Reuse Opportunities

  • Check if an existing helper already does what new code is doing — grep before writing
  • Identify patterns repeated across the diff that should use a shared utility
  • Flag cases where a library function was reimplemented
  • Constants and magic values: extract to named constants if used in more than one place

7. TODO Hygiene

Apply the project's TODO prefix standards:

  • TODO: — general future work
  • TODO_IMPROVE: — code quality improvements
  • TODO_OPTIMIZE: — performance improvements
  • TODO_TECHDEBT: — technical debt to address later
  • TODO_REVISIT: — design decisions that may need revisiting
  • TODO_IDEA: — potential features to consider
  • TODO_IN_THIS_PR: — must complete before merge
  • TODO_REMOVE_LATER: — temporary code with removal condition
  • FIXME: — known bugs
  • HACK: — temporary workarounds

Each TODO must include:

  • What: clear description
  • Why: context on why it's deferred

Add missing TODOs for: known shortcuts, deferred work, temporary workarounds, and obvious improvement opportunities spotted during review. Remove stale or resolved TODOs.

8. Readability & Cognitive Load

  • Comments explain why, never what (delete # increment counter above counter += 1)
  • Add a brief comment above grouped code blocks (~5+ lines doing one thing)
  • Convert paragraph-style comments to bullet points when feasible
  • Strategic whitespace: blank lines between logical sections
  • Preserve all IMPORTANT, NOTE, CRITICAL, DEV_NOTE markers — clean up the text, not the tag
  • Keep links, issue references, and external references intact

9. Agent & Index Readability

Code is increasingly consumed by agents traversing a codebase and RAG pipelines embedding individual chunks. Apply these checks in addition to the structural ones in Dimensions 3 and 4.

Self-containment: Each function should be understandable without reading its callers or surrounding file state.

  • Flag functions that only make sense in the context of their caller — extract the shared context into a parameter or a named type
  • Avoid implicit shared state (module-level mutation, magic globals) that forces a reader to hold the whole file in mind
  • Prefer explicit inputs and outputs over side effects on outer-scope variables

Meaningful boundaries: File and module splits should reflect conceptual units, not arbitrary line-count budgets.

  • A file with 3 unrelated utility functions is worse than one slightly larger file with a coherent theme
  • Module names should describe the concept, not the implementation (auth_tokens.py > helpers.py, user_processor.py > utils.py)
  • If splitting a file, each half should have a name that a reader can immediately map to a concept

Embeddable names: Names must carry enough signal to be useful in isolation — without surrounding code as context.

  • Avoid generic names at module or class scope (process, handle, run, execute) — add the subject (process_payment, handle_auth_error)
  • Single-letter variables are fine inside a 3-line loop; flag them inside functions that could be indexed independently
  • Constants should be named for their meaning, not their value (MAX_RETRY_ATTEMPTS > THREE)

Branching budget: High cyclomatic complexity fragments meaning across many paths, making any single path hard to embed or summarize.

  • Flag functions with more than ~5 distinct branches (if/elif/except/case arms combined)
  • Prefer dispatch tables, strategy objects, or polymorphism over long if/elif chains when the branches share a shape
  • Each branch arm should be readable as a standalone case — extract arm bodies to named helpers when they exceed ~5 lines

Output Format

For each file changed, show:

### file_path

**Changes made:**
- [dimension] description of change (line X)
- [dimension] description of change (line Y)

End with a summary: files touched, lines removed, TODOs added/removed, helpers extracted.

What NOT to Change

  • Working abstractions (even if currently simple)
  • Type hints (always valuable)
  • Test code (unless explicitly asked)
  • Forward-looking base classes if second implementation is likely soon
  • Domain-specific patterns the team uses intentionally

PR Test Plan

Generate a manual test plan for the changes in the current branch. The plan should focus on what a developer/reviewer needs to manually verify — real user flows, integration behavior, and observable outcomes. Leave input validation, error branches, and edge cases to unit tests.

Determine Scope

Default (no scope specified): diff the current branch against the repo's base branch.

Detect the base branch in order — stop at the first success:

  1. gh repo view --json defaultBranchRef -q '.defaultBranchRef.name' 2>/dev/null
  2. git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2 | xargs
  3. git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'

Do not assume main or master. If all methods fail, ask the user.

Once resolved, run:

git diff <base>...HEAD -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

If the user specifies a scope, use the corresponding command instead:

ScopeCommandWhat it covers
unstagedgit diff HEAD -- <excludes>All uncommitted changes (staged + unstaged)
last commit / last 1 commitgit diff HEAD~1...HEAD -- <excludes>Changes in the most recent commit
last N commitsgit diff HEAD~N...HEAD -- <excludes>Changes in the last N commits
entire repogit ls-files | grep -vE "\.(lock|snap)$|package-lock\.json|pnpm-lock\.yaml"All tracked source files; no diff — generate a full application test plan covering all major flows and integration points

For all diff commands, apply: -- ":(exclude)*.lock" ":(exclude)package-lock.json" ":(exclude)pnpm-lock.yaml" ":(exclude)package.json"

Instructions

Step 1: Determine scope

Use Determine Scope above to resolve the scope and get the diff (or file list for entire repo).

Step 2: Gather change context

Run all of these and capture the results:

git diff $BASE_BRANCH...HEAD --name-only
git diff $BASE_BRANCH...HEAD --stat
git log $BASE_BRANCH..HEAD --oneline

For non-branch scopes (unstaged, last N commits), adapt the commands accordingly — replace $BASE_BRANCH...HEAD with the scoped range (e.g. HEAD~N...HEAD), and replace git log with git log HEAD~N..HEAD --oneline.

Step 3: Detect project tooling

Check what's available in the project so you can reference real commands (not generic guesses):

  • Makefile targets: make help 2>/dev/null || grep -E '^[a-z_-]+:.*##' Makefile makefiles/*.mk 2>/dev/null
  • Package manager: Look for pyproject.toml (uv/pip), package.json (npm/pnpm), Cargo.toml (cargo), go.mod (go)
  • Test runners: Look for pytest.ini, pyproject.toml [tool.pytest], jest.config.*, .mocharc.*
  • Project docs: Read AGENTS.md, CLAUDE.md, CONTRIBUTING.md, or README.md for project-specific test/build instructions
  • CI config: Check .github/workflows/, Makefile, or Taskfile.yml for existing test commands

Prefer project Makefile targets and documented commands over raw tool invocations. If the project has make test_unit, use that instead of uv run pytest tests/unit/.

Step 4: Categorize changes and confirm with user

Group changed files into categories. Common categories (adapt based on actual changes):

  • Feature code -- new commands, API routes, services, UI components
  • Configuration / docs -- config files, markdown, schemas, manifests
  • Tests -- new or modified test files
  • Build / deploy -- Makefiles, CI, Dockerfiles, scripts
  • Deletions -- removed files or deprecated code

Present the detected categories to the user with a summary of what changed in each. Ask them to confirm or adjust before generating the full plan.

Example confirmation format:

I found 3 change areas in this branch:

1. CLI agent mode -- new --agent flag on setup command (cli/commands/setup.py, cli/cli.py)
2. Skills restructuring -- SKILL.md rewrite, new reference docs, deleted shell scripts
3. Test fixes -- E2E test stability improvements (4 test files)

Should I generate the test plan for all 3, or would you like to adjust?

Step 5: Generate the test plan

For each confirmed category, generate a test section following these rules:

Severity & importance markers

Tag every test step with one of these emojis in the step title:

EmojiMeaningWhen to use
🔴CriticalCore functionality — if this fails, the feature is broken
🟢ExpectedStandard behavior that should work — moderate confidence but worth verifying
🔵Nice-to-havePolish, UX, non-blocking — skip if short on time

Example: 1a. 🔴 **Pre-register a profile end-to-end**

Formatting rules
  • Numbered sections with separator lines (---) between them
  • Numbered sub-steps within each section (1a, 1b, 1c...)
  • Each sub-step has an emoji tag + bold title describing what to test
  • Each sub-step has a copy-paste command in a fenced code block (or manual UI steps if applicable)
  • Each sub-step has a "Verify:" line stating what success looks like
  • One command per code block -- never stack multiple commands in one block with comments between them
  • Use Makefile targets when available instead of raw tool commands
  • For commands requiring env vars, put them inline: GROVE_API_URL=http://localhost:8000 make test_e2e_suite
What to focus on (and what to skip)

DO include — things you must verify manually:

  • Happy-path user flows end-to-end (the main thing the feature does)
  • Integration points — does component A actually talk to component B correctly?
  • State transitions — does data persist, propagate, and display correctly across the system?
  • Resumption / retry behavior — if a multi-step process fails midway, does retry work?
  • UI rendering — does the new section/field/page show up and look right?
  • API response shape — do new fields appear in real responses?
  • Existing behavior preserved — does the change break anything that was already working?

DO NOT include — leave these for unit tests:

  • Invalid input validation (wrong types, missing fields, malformed data)
  • Boundary values and off-by-one checks
  • Error message wording verification
  • Permission/auth edge cases (401/403 responses)
  • Schema validation failures
Failure-path test column

For any changed file that has multi-phase logic (e.g., validate → external I/O → DB write), add a "Failure-path" column to the test coverage table:

| File Changed           | Unit | Integration | E2E | Failure-path |
|------------------------|------|-------------|-----|--------------|
| routes/account.py      | ❌   | ❌          | ✅  | ❌           |
| db/display_names.py    | ✅   | ❌          | ❌  | ⏭️           |

The "Failure-path" column asks: does at least one test inject a failure into a non-first phase of multi-phase work?

  • For a route that does verify token → DB read → external API call → DB write, a failure-path test mocks the external API to raise and asserts the route logs context and returns a typed error (not a silent 500).
  • Mark ⏭️ only for files with no exception-bearing branches (pure utilities, type definitions).
  • For route handlers and DB helpers with multi-step logic, ❌ is the default until a test exists.
Quick smoke test section

Always end with a "Quick Smoke Test" section -- the 2-3 commands a reviewer would run if they only have 60 seconds. Tag each with the appropriate emoji.

Step 6: Write output

  1. Write the plan to TEST_PLAN.md in the repo root
  2. Print a summary to the terminal showing the section count and a one-liner per section

Terminal summary format:

Wrote TEST_PLAN.md with 4 sections:

  1. CLI Agent Mode -- 4 test steps (🔴×2, 🟢×1, 🔵×1)
  2. Skills Restructuring -- 3 test steps (🔴×1, 🟢×2)
  3. Automated Tests -- 2 test steps (🟢×2)
  4. Quick Smoke Test -- 3 commands

Run `cat TEST_PLAN.md` to view the full plan.

Style Reference

Follow the same style used in cmd-pr-description:

  • Bold the what, plain text the how
  • No fluff -- every step must verify something real that a human needs to see
  • Copy-paste ready -- a reviewer should never need to edit a command
  • Separate code blocks -- one command per block, bold header above it

Productionize App Agent Rules

When asked to productionize an application for deployment:

Overview

Transform development code into production-ready applications through systematic, methodical analysis, improvement, and deployment preparation. Supports multiple frameworks and deployment targets.

Quality Over Speed Mandate: Take time to be thorough and comprehensive. Focus on quality implementation over rapid completion. This is production-critical work that requires careful attention to detail.

Usage Patterns

/cmd-productionize                          # Auto-detect framework, general production prep
/cmd-productionize flutter testflight       # Flutter app for TestFlight
/cmd-productionize react vercel            # React app for Vercel deployment
/cmd-productionize nodejs docker           # Node.js app for Docker deployment
/cmd-productionize python heroku           # Python app for Heroku
/cmd-productionize vue netlify             # Vue app for Netlify

Workflow

1. Initial Analysis & Planning

  • Always start with TodoWrite tool to create a comprehensive task list
  • Breadth AND Depth Navigation: Look beyond immediate scope to understand:
    • Related systems that might be affected
    • Broader architectural implications
    • Integration points and dependencies
    • Edge cases and potential failure modes
    • Long-term maintenance considerations
  • Analyze codebase structure and identify the framework/stack
  • Read existing documentation (README, package.json, pubspec.yaml, etc.)
  • Identify deployment target and requirements
  • Create systematic task breakdown covering all productionization phases
  • Proactive Question Analysis: Identify critical production questions the user hasn't asked yet

2. Codebase Analysis Phase

  • Architecture review: Analyze project structure, dependencies, and patterns with methodical thoroughness
  • Comprehensive Production Readiness Audit: Systematically identify potential issues:
    • Hardcoded values and missing environment configurations
    • Missing error handling and edge case coverage
    • Performance bottlenecks and optimization opportunities
    • Security vulnerabilities and data exposure risks
    • Missing caching and state management
    • API pagination and data fetching issues
    • UI/UX polish and accessibility concerns
    • Rate limiting and abuse protection
    • Offline support and network failure handling
    • Data validation and sanitization
    • Memory leaks and resource cleanup
    • Cross-platform compatibility issues
    • Third-party service dependencies and fallbacks
  • Framework-specific checks: Apply framework-appropriate best practices with deep domain knowledge
  • Critical Questions Analysis: Document what production concerns the user should consider but hasn't addressed

3. Implementation Phase

Execute improvements systematically with methodical attention to detail, updating TodoWrite progress frequently:

Quality Focus: Each implementation step should be thorough and well-tested. Don't rush through tasks - take time to implement robust, production-grade solutions.

Configuration & Environment
  • Add environment-based configurations (dev/staging/prod)
  • Implement feature toggles and debug modes
  • Secure API keys and sensitive data
  • Add configuration validation
Performance & Reliability
  • Implement proper caching mechanisms (memory, disk, network)
  • Add error handling and retry logic
  • Optimize network requests and pagination
  • Add loading states and offline handling
  • Implement proper state persistence
User Experience
  • Polish UI/UX with loading indicators and feedback
  • Add proper error messages and user guidance
  • Implement accessibility improvements
  • Test edge cases and error scenarios
Code Quality
  • Add comprehensive logging and monitoring
  • Implement proper testing coverage
  • Clean up technical debt and code smells
  • Add documentation and comments

4. Framework-Specific Optimizations

Flutter
  • Implement SharedPreferences for persistent caching
  • Add proper error handling for network requests
  • Optimize widget rebuilds and state management
  • Add platform-specific configurations (iOS/Android)
  • Implement proper navigation and state restoration
React/Next.js
  • Implement proper state management (Redux, Zustand, Context)
  • Add error boundaries and suspense loading
  • Optimize bundle size and code splitting
  • Implement proper caching (SWR, React Query)
  • Add SEO and meta tag optimizations
Node.js
  • Add proper middleware for error handling and logging
  • Implement rate limiting and security headers
  • Optimize database queries and connections
  • Add health checks and monitoring endpoints
  • Implement proper environment configuration
Python
  • Add proper error handling and logging
  • Implement caching (Redis, in-memory)
  • Optimize database queries and ORM usage
  • Add input validation and sanitization
  • Implement proper testing and CI/CD

5. Documentation Phase

Create comprehensive production-ready documentation:

README.md Structure (based on proven patterns):
# Project Name - Production Ready

_Brief compelling description with value proposition_

## Quick Start
- One-command setup instructions
- Environment requirements
- Configuration steps

## Features
- Core functionality overview
- Production-ready capabilities
- Toggle configurations

## Deployment
- Platform-specific deployment guides
- Environment variable setup
- Testing and validation steps

## Development
- Local development setup
- Testing procedures
- Contributing guidelines

## Architecture
- High-level system overview
- Key design decisions
- Production considerations
Additional Documentation
  • Deployment checklists for each target platform
  • API documentation if applicable
  • Troubleshooting guides
  • Performance optimization notes

6. Deployment Preparation Phase

TestFlight (iOS)
  • Verify App Store Connect configurations
  • Test provisioning profiles and certificates
  • Validate Info.plist settings
  • Create build and upload scripts
  • Prepare app description and screenshots
Google Play (Android)
  • Configure Play Console settings
  • Test signing configurations
  • Validate manifest permissions
  • Create release notes and store listing
  • Test different device configurations
Web Deployment (Vercel/Netlify/AWS)
  • Configure build scripts and environment variables
  • Set up domain and SSL certificates
  • Test deployment pipeline
  • Configure CDN and caching headers
  • Set up monitoring and analytics
Container Deployment (Docker/Kubernetes)
  • Create optimized Dockerfiles
  • Configure health checks and resource limits
  • Set up environment variable management
  • Test scaling and load balancing
  • Configure logging and monitoring

7. Quality Assurance Checklist

Before marking productionization complete:

  • All configurations are environment-aware
  • Error handling covers edge cases
  • Caching is implemented and tested
  • Performance is optimized for target platforms
  • Security best practices are followed
  • Documentation is comprehensive and accurate
  • Deployment process is tested and reliable
  • Monitoring and logging are configured
  • User experience is polished and accessible
  • All TodoWrite tasks are completed

8. Proactive Question Analysis & Next Steps

After completing productionization, ALWAYS provide:

Critical Questions the User Should Have Asked

Systematically identify and present production concerns the user hasn't considered:

Example Framework-Specific Questions:

  • Flutter: "Have you considered rate limiting for API calls? What happens when the device goes offline? How will you handle app store review rejections?"
  • React/Web: "What's your strategy for SEO and social media previews? How will you handle bot traffic? What about GDPR compliance for user data?"
  • Node.js: "How will you monitor server health in production? What's your database backup strategy? How will you handle traffic spikes?"
  • Python: "What's your strategy for handling memory leaks in long-running processes? How will you manage database migrations in production?"
Actionable Next Steps Checklist

Provide a prioritized, concrete list of post-productionization actions:

## Immediate Next Steps (Complete within 48 hours)
1. [ ] Test deployment pipeline end-to-end in staging environment
2. [ ] Set up monitoring alerts for critical metrics
3. [ ] Create rollback procedures and test them
4. [ ] Validate all environment variables are properly configured

## Short-term (Complete within 1 week)
1. [ ] Implement comprehensive logging for production debugging
2. [ ] Set up automated backup procedures
3. [ ] Create incident response playbook
4. [ ] Conduct load testing with realistic traffic patterns

## Medium-term (Complete within 1 month)
1. [ ] Establish performance benchmarking and alerting
2. [ ] Implement A/B testing framework if applicable
3. [ ] Create comprehensive user documentation
4. [ ] Plan for scaling based on usage growth projections

9. Framework Detection Logic

Auto-detect framework based on:

  • Flutter: pubspec.yaml, .dart files
  • React: package.json with React dependencies
  • Vue: package.json with Vue dependencies
  • Node.js: package.json with server dependencies
  • Python: requirements.txt, pyproject.toml, .py files
  • Go: go.mod, .go files

10. Best Practices

  • Use TodoWrite religiously - Track every phase and task with granular detail
  • Quality over speed mentality - Take time to implement robust solutions rather than rushing through tasks
  • Be methodically systematic - Don't skip phases even if they seem obvious; thoroughness is critical
  • Breadth AND depth analysis - Always consider broader architectural implications beyond immediate scope
  • Document decisions comprehensively - Explain why certain production choices were made with context for future maintainers
  • Proactive questioning - Always identify what the user should have asked but didn't
  • Test deployment rigorously - Verify the deployment process works before completion
  • Focus on real-world user experience - Production means real users with real problems will interact with this
  • Plan for scale and failure - Consider what happens when usage grows AND when things break
  • Security first mindset - Never compromise on security for convenience
  • Measure twice, deploy once - Thorough testing and validation prevents production issues
  • Always provide actionable next steps - Give users concrete, prioritized actions to take post-productionization

11. Success Criteria

The application is production-ready when:

  • It handles real-world usage patterns gracefully
  • Error scenarios are covered with appropriate user feedback
  • Performance is optimized for the target deployment platform
  • Configuration can be managed without code changes
  • Documentation enables others to deploy and maintain the application
  • The deployment process is reliable and repeatable
  • Monitoring and observability are in place for production operations
  • Critical questions analysis has been completed - All important production concerns have been identified and addressed
  • Actionable next steps have been provided - User has clear, prioritized guidance for post-productionization actions
  • Breadth and depth analysis is complete - Related systems, architectural implications, and dependencies have been thoroughly considered

Notes

  • Methodical thoroughness is paramount - Take time to be comprehensive rather than rushing through tasks
  • Always adapt to the specific framework and deployment target with deep domain expertise
  • Prioritize based on the application's critical user flows and real-world usage patterns
  • Focus on production concerns, not development convenience
  • Document architectural decisions comprehensively for future maintainers
  • Test the complete user journey, not just individual features
  • Always conclude with proactive question analysis and actionable next steps - This is not optional
  • Consider broader architectural implications and related systems impact
  • Quality over speed - production readiness cannot be rushed

Chain Halt Code Reviewer

You are a senior CosmosSDK protocol engineer in charge of the next protocol upgrade.

Do a git diff like:

  1. Git diff main (current change); default
  2. Git diff (previous tag); if prompted

Then:

  1. Identify any potential bugs, edge cases or issues.
  2. Focus on any onchain behaviour that can result in non-deterministic outcomes. For example, iterating a map without sorting the keys first.
  3. Look through all of the code but pay particular attention to code in the x/ directory.

Remember:

  1. This is critical to avoid chain halts. Take your time and provide a comprehensive analysis.

Request for Comments (RFC) Review

You are a very experienced, thoughtful, and kind software engineer who reviews RFC (Requests for Comments) written by members of the team. You make thoughtful suggestions of areas to improve.

You focus your comments on:

  1. Ensuring the RFC describes problems using the SCQA format: Situation, Complication, Question, Answer. (You do not need to describe problems this way.)
  2. Maintaining our SOC2 compliance standing, along with general compliance topics
  3. Explicitly linking to referenced resources and documents (to prevent readers from having to find them themselves)
  4. Delivering secure, performant software

Your response should:

  • Be very brief.
  • Identify the three to five most important issues and give feedback on them.
  • Not give feedback on every potential issue.
  • Be less than 1500 characters long at the very longest.

You have been asked to provide feedback on this RFC.

Session Commit

Analyze the current coding session, propose improvements to AGENTS.md, and apply approved changes.

Workflow

  1. Read the current AGENTS.md and build a mental map of existing sections.
  2. If the repo documents a validation or repair command for instruction files, run it before proposing edits.
  3. Extract only durable learnings from the current session.
  4. Propose changes using the format in references/change-proposal-format.md.
  5. Wait for explicit user approval before applying any edits.
  6. Apply approved changes and merge with existing content.

What to capture

  • Coding patterns and conventions established in the session
  • Architecture decisions and reasoning that should persist
  • Debugging playbooks and recurring gotchas
  • Workflow preferences that improve future sessions

Guardrails

  • Do not capture transient implementation details that will age quickly.
  • Prefer updating existing sections before creating new headings.
  • Use concise bullet points rather than long paragraphs.
  • Keep guidance tool-agnostic unless behavior differs by tool.
  • If no meaningful learning occurred, report that and stop.

Pointer file behavior

If CLAUDE.md, CODEX.md, or GEMINI.md are missing or empty, create symlinks that point to AGENTS.md.

Output contract

  • Proposal stage: output only proposed changes with explicit add/modify/remove counts.
  • Apply stage: update AGENTS.md only after explicit approval.
  • Completion stage: summarize what changed and where.

Skills Dashboard Generator

Scrape the skills.sh registry and produce an interactive Plotly.js dashboard showing who publishes the most skills, who has the most installs, and how adoption is distributed.

When to Use This Skill

  • Generating a fresh snapshot of the skills.sh ecosystem
  • Comparing publishers by skill count vs install count
  • Exploring the power-law distribution of skill adoption
  • Answering "who dominates the skills ecosystem?"

How It Works

  1. Scrape - Fetch https://skills.sh/api/search with broad 2-char queries to discover all skills
  2. Aggregate - Group by owner (GitHub org/user) and repo, compute counts and totals
  3. Render - Generate a self-contained HTML file with Plotly.js charts

Running

Generate the dashboard with the scraper script:

python3 scripts/scrape_and_build.py

This writes index.html to the current directory.

To write to a specific path:

python3 scripts/scrape_and_build.py --output /path/to/dashboard.html

Dashboard Contents

ChartWhat It Shows
TreemapInstall share by publisher, click to drill into individual skills
Bar: Skill CountTop 25 publishers by number of skills published
Bar: Total InstallsTop 25 publishers by total install volume
HistogramLog-scale distribution showing the long tail of installs
Top 30 SkillsThe 30 most-installed individual skills

Data Source

All data comes from the skills.sh/api/search endpoint. Each entry has:

{
  "source": "owner/repo",
  "skillId": "skill-name",
  "name": "skill-name",
  "installs": 12345
}

Generate It Yourself

Install the skill:

npx skills add olshansk/agent-skills

Select skills-dashboard when prompted.

Then:

  1. Launch your agent CLI of choice (Claude Code, Codex, Gemini CLI, OpenCode)
  2. Ask it to "build the skills ecosystem dashboard"

No API keys needed — the skill scrapes the public skills.sh registry and outputs a self-contained HTML file.

Repo-Local Skill Manager

Create or refactor repo-local skills and agent instructions that work across Claude, Codex, Gemini, and Codex-home using a single canonical source in .agents/.

Architecture

repo-root/
├── .agents/
│   ├── AGENTS.md                                           # Canonical agent instructions
│   └── skills/<name>/SKILL.md                              # Canonical skill source
├── AGENTS.md → .agents/AGENTS.md                           # Symlink (tools reading repo root)
├── CLAUDE.md → .agents/AGENTS.md                           # Symlink (Claude reads repo root)
├── .codex/AGENTS.md → ../.agents/AGENTS.md                 # Symlink
├── .gemini/GEMINI.md → ../.agents/AGENTS.md                # Symlink
├── .claude/skills/<name> → ../../.agents/skills/<name>     # Per-skill symlink
├── .codex/skills/<name> → ../../.agents/skills/<name>      # Per-skill symlink
├── .codex-home/skills/<name> → ../../.agents/skills/<name> # Per-skill symlink
└── .gitignore                                              # Whitelist entries for all paths

Key rules:

  • .agents/ is the single source of truth for both agent instructions and skills
  • .agents/AGENTS.md is the canonical agent instruction file — all tool-specific files are symlinks
  • Per-skill symlinks are used instead of directory-level symlinks so externally installed skills (e.g. via npx skills add) coexist without conflict
  • .gitignore uses a base skills/ ignore rule, then whitelists specific paths
  • An optional evals/ directory inside .agents/skills/<name>/ is always gitignored
  • No skill may live as a real directory under a tool-specific path (.claude/skills/<name>/, .codex/skills/<name>/, .codex-home/skills/<name>/). Per-tool dirs contain only symlinks. Canonical source is always .agents/skills/<name>/ — this keeps skills cross-tool and prevents silent Claude-only (or Codex-only, etc.) drift

Phase 1: Gather Context

Before asking questions, run discovery:

ls .agents/ 2>/dev/null
ls .agents/skills/ 2>/dev/null
ls .claude/commands/ 2>/dev/null
cat CLAUDE.md 2>/dev/null | head -5
cat AGENTS.md 2>/dev/null | head -5
grep -n "^skills/" .gitignore 2>/dev/null

Also run the cross-tool audit (see Audit commands for the copy-paste block). Detect:

  • Tool-specific real-dir skills — any directory under .claude/skills/, .codex/skills/, or .codex-home/skills/ that is a real directory (not a symlink). These violate the cross-tool rule and must be promoted.
  • Orphans in .agents/skills/ — any skill in .agents/skills/ that is missing a symlink in one or more per-tool dirs. These are reachable from some tools but not others.

Present all findings (shared-context reads + audit output), then use AskUserQuestion with these questions (max 4 per call):

  1. Mode: "Do you want to (a) create a NEW repo-local skill from scratch, (b) refactor an existing .claude/commands/ file into the cross-tool skill structure, (c) just set up agent instructions (no skill), (d) promote an existing tool-specific real-dir skill into the cross-tool layout, or (e) repair an orphan .agents/skills/ skill by creating missing per-tool symlinks?"
  2. Skill name (if a/b/d/e): "What should the skill be called? (kebab-case, e.g. grove-api-review)"
  3. Description (if a or b): "One-line description of what the skill does."
  4. If commands exist and mode = b: "Which command file should I migrate?" (list the files found in .claude/commands/)

If the audit surfaced violations or orphans, lead with those — it's almost always the right next action before scaffolding anything new.

Phase 2a: Agent Instructions

Set up .agents/AGENTS.md as the canonical agent instruction file with symlinks for every tool.

Step 1 — Create or migrate the canonical file:

mkdir -p .agents
  • If AGENTS.md exists at repo root and is a regular file, move it: mv AGENTS.md .agents/AGENTS.md
  • If CLAUDE.md exists at repo root and is a regular file (not a symlink), move it: mv CLAUDE.md .agents/AGENTS.md
  • If neither exists, create .agents/AGENTS.md with a minimal skeleton
  • If both exist, merge them into .agents/AGENTS.md (prefer AGENTS.md content, append unique CLAUDE.md content)

Step 2 — Create symlinks:

ln -sf .agents/AGENTS.md AGENTS.md
ln -sf .agents/AGENTS.md CLAUDE.md
mkdir -p .codex .gemini
ln -sf ../.agents/AGENTS.md .codex/AGENTS.md
ln -sf ../.agents/AGENTS.md .gemini/GEMINI.md

Step 3 — Verify all symlinks resolve:

readlink AGENTS.md
readlink CLAUDE.md
readlink .codex/AGENTS.md
readlink .gemini/GEMINI.md
head -3 CLAUDE.md

Step 4 — Update .gitignore:

Check if entries already exist, then add as needed:

grep -n "AGENTS.md\|CLAUDE.md\|GEMINI.md" .gitignore 2>/dev/null

Append the agent instructions block from the gitignore template if not present.

Phase 2b: Scaffold, Promote, or Repair the Skill

Skip this phase if the user chose mode (c) in Phase 1. Modes (a), (b), (d), and (e) all share the same symlink + gitignore steps — they only differ in how the canonical source is produced.

Create canonical source

Create the canonical directory:

mkdir -p .agents/skills/<name>

If creating new (mode a):

Create .agents/skills/<name>/SKILL.md with frontmatter and a minimal skeleton. Ask the user to provide or iterate on the skill content.

If refactoring from .claude/commands/ (mode b):

  1. Read the source command file (e.g., .claude/commands/<name>.md)
  2. Create .agents/skills/<name>/SKILL.md with YAML frontmatter added
  3. Convert the top-level header to include <!-- omit in toc -->
  4. Do NOT delete the original command file yet — offer in Phase 3

If promoting an existing tool-specific real-dir skill (mode d):

The skill currently lives as a real directory under a per-tool path (e.g., .claude/skills/<name>/ with a real SKILL.md inside). Move it to the canonical location:

mv .claude/skills/<name> .agents/skills/<name>

If the violation is under .codex/skills/ or .codex-home/skills/ instead, mv from there. Then proceed to Create symlinks — a symlink must be re-added to the per-tool dir the skill was promoted from (since the mv removed it), and to the other two per-tool dirs.

If repairing an orphan (mode e):

The skill already lives at .agents/skills/<name>/ but is missing one or more per-tool symlinks. Skip directly to Create symlinks — the canonical source is untouched; only the symlinks need to be (re-)created.

Create symlinks

Each skill needs a symlink in every tool's skills directory. This approach allows external skills (e.g. from npx skills add) to coexist.

mkdir -p .claude/skills .codex/skills .codex-home/skills
ln -sf ../../.agents/skills/<name> .claude/skills/<name>
ln -sf ../../.agents/skills/<name> .codex/skills/<name>
ln -sf ../../.agents/skills/<name> .codex-home/skills/<name>

Check that the symlinks resolve correctly:

test -f .claude/skills/<name>/SKILL.md && echo "OK" || echo "BROKEN"

Two legacy layouts require normalization before this loop runs cleanly:

Legacy — directory-level symlink (.claude/skills → ../.agents/skills). Replace with per-skill symlinks:

for tool in .claude .codex .codex-home; do
  [ -L "$tool/skills" ] && rm "$tool/skills"
  mkdir -p "$tool/skills"
done

Legacy — tool-specific real-dir skill (a real .claude/skills/<name>/ or .codex/skills/<name>/ dir, not a symlink). Promote to canonical first:

for tool in .claude .codex .codex-home; do
  for d in "$tool"/skills/*/; do
    [ -d "$d" ] && [ ! -L "${d%/}" ] || continue
    name=$(basename "${d%/}")
    # Skip if a canonical source already exists (manual conflict resolution needed)
    [ -d ".agents/skills/$name" ] && { echo "CONFLICT: .agents/skills/$name already exists; resolve manually"; continue; }
    mv "${d%/}" ".agents/skills/$name"
  done
done

After either normalization, populate all three per-tool dirs with per-skill symlinks:

mkdir -p .claude/skills .codex/skills .codex-home/skills
for skill in .agents/skills/*/; do
  name=$(basename "$skill")
  ln -sf "../../.agents/skills/$name" ".claude/skills/$name"
  ln -sf "../../.agents/skills/$name" ".codex/skills/$name"
  ln -sf "../../.agents/skills/$name" ".codex-home/skills/$name"
done

ln -sf makes this idempotent — safe to re-run on a partially-configured repo (mode e).

Update .gitignore

The gitignore must be updated carefully to preserve existing entries.

Step 1 — Check if the base skills/ rule exists:

grep -n "^skills/" .gitignore

Step 2 — Check if entries for this skill already exist:

grep "<name>" .gitignore

Step 3 — Append or insert the whitelist block.

If NO skills/ section exists, append the full block from the gitignore template.

If a skills/ section already exists (adding a 2nd+ skill), only add the NEW skill-specific lines. The base rules (skills/, !.agents/skills/, !.claude/skills, !.codex/skills, !.codex-home/skills) already exist — do NOT duplicate them. Insert the new lines after the last entry:

!.agents/skills/<name>/
!.agents/skills/<name>/SKILL.md
.agents/skills/<name>/evals/

Never duplicate a line that already exists in .gitignore.

Phase 3: Verify

Run these checks and report results:

# Verify agent instruction symlinks
readlink AGENTS.md
readlink CLAUDE.md
readlink .codex/AGENTS.md
readlink .gemini/GEMINI.md
head -1 CLAUDE.md

If skills were scaffolded, promoted, or repaired:

# Verify per-skill symlinks resolve correctly
readlink .claude/skills/<name>
readlink .codex/skills/<name>
readlink .codex-home/skills/<name>

# Verify skill content is accessible through each symlink
head -3 .claude/skills/<name>/SKILL.md
head -3 .codex/skills/<name>/SKILL.md
head -3 .codex-home/skills/<name>/SKILL.md

# Verify git tracks the canonical skill file
git status .agents/skills/<name>/SKILL.md

# Lint: all three per-tool symlink entries must be whitelisted in .gitignore
for tool in .claude .codex .codex-home; do
  grep -q "^!$tool/skills/<name>$" .gitignore \
    || echo "FAIL: .gitignore missing '!$tool/skills/<name>'"
done

# Lint: no real-dir skills should remain under any per-tool path
for tool in .claude .codex .codex-home; do
  find "$tool/skills" -mindepth 1 -maxdepth 1 -type d -not -name skills \
    | while read d; do echo "FAIL: real-dir skill at $d (should be a symlink)"; done
done

If refactoring, ask: "The original command file at .claude/commands/<file> still exists. Should I delete it now that the skill has been migrated?"

Present summary:

Agent instructions:
  Canonical: .agents/AGENTS.md
  AGENTS.md → .agents/AGENTS.md                → ✅
  CLAUDE.md → .agents/AGENTS.md                → ✅
  .codex/AGENTS.md → ../.agents/AGENTS.md      → ✅
  .gemini/GEMINI.md → ../.agents/AGENTS.md     → ✅

Skill: <name>
  Canonical: .agents/skills/<name>/SKILL.md
  .claude/skills/<name> → ../../.agents/skills/<name>      → ✅
  .codex/skills/<name> → ../../.agents/skills/<name>       → ✅
  .codex-home/skills/<name> → ../../.agents/skills/<name>  → ✅

Gitignore: ✅ updated

Templates

SKILL.md frontmatter template

 ---
 name: <skill-name>
 description: <one-line description>
 disable-model-invocation: false
 ---

 # Skill Title <!-- omit in toc -->

AGENTS.md skeleton template

# AGENTS.md <!-- omit in toc -->

## Project Overview

- Brief description of the project

## Development

- Key commands and workflows

Gitignore block template

Full block for agent instructions (add once per repo):

# Agent instructions
# Canonical source: .agents/AGENTS.md — tool-specific files are symlinks
!.agents/
!.agents/AGENTS.md

Full block for the first skill in a repo (replace <name> with the skill name):

# Skills
# Default: ignore generic skills/ trees from external skill repos.
# Exception: keep repo-local cross-tool skills tracked via per-skill symlinks.
skills/
!.agents/skills/
!.agents/skills/<name>/
!.agents/skills/<name>/SKILL.md
.agents/skills/<name>/evals/
# Per-skill symlinks — track each symlink so all tools discover the skill
!.claude/skills/
!.claude/skills/<name>
!.codex/skills/
!.codex/skills/<name>
!.codex-home/skills/
!.codex-home/skills/<name>

For additional skills, append only the new skill-specific lines:

!.agents/skills/<name>/
!.agents/skills/<name>/SKILL.md
.agents/skills/<name>/evals/
!.claude/skills/<name>
!.codex/skills/<name>
!.codex-home/skills/<name>

Audit commands

Use these during Phase 1 to surface cross-tool drift before scaffolding anything new.

Detect tool-specific real-dir skills (violations — a skill that exists under a per-tool path as a real directory, not a symlink):

for tool in .claude .codex .codex-home; do
  [ -d "$tool/skills" ] || continue
  find "$tool/skills" -mindepth 1 -maxdepth 1 -type d -not -name skills 2>/dev/null \
    | while read d; do echo "VIOLATION: real-dir skill at $d"; done
done

Detect orphans (skill exists in .agents/skills/ but is missing a symlink in one or more per-tool dirs):

[ -d .agents/skills ] && for skill in .agents/skills/*/; do
  name=$(basename "${skill%/}")
  for tool in .claude .codex .codex-home; do
    [ -L "$tool/skills/$name" ] || echo "ORPHAN: .agents/skills/$name missing $tool/skills/$name"
  done
done

Detect broken symlinks (target missing):

for tool in .claude .codex .codex-home; do
  [ -d "$tool/skills" ] || continue
  find "$tool/skills" -maxdepth 1 -type l -exec test ! -e {} \; -print \
    | while read l; do echo "BROKEN: $l"; done
done

Empty output from all three = healthy cross-tool layout.

Symlink commands template

Agent instructions setup (run once per repo):

mkdir -p .agents .codex .gemini
ln -sf .agents/AGENTS.md AGENTS.md
ln -sf .agents/AGENTS.md CLAUDE.md
ln -sf ../.agents/AGENTS.md .codex/AGENTS.md
ln -sf ../.agents/AGENTS.md .gemini/GEMINI.md

Per-skill setup (run for each new skill):

mkdir -p .agents/skills/<name> .claude/skills .codex/skills .codex-home/skills
ln -sf ../../.agents/skills/<name> .claude/skills/<name>
ln -sf ../../.agents/skills/<name> .codex/skills/<name>
ln -sf ../../.agents/skills/<name> .codex-home/skills/<name>

Skills Review

Audit one skill or all skills, get a second opinion from Codex, then apply only what you approve.

When to use

  • "review my skills" / "audit my skills" / "revisit my skills" / "clean up my skills"
  • "review the cmd-foo skill" — single-skill mode
  • Before publishing or sharing the skills repo
  • When the skill catalog has grown and feels bloated

Instructions

0. Determine scope

If the user named a specific skill (e.g. "review cmd-pr-edgecase"), set TARGET=skills/cmd-pr-edgecase/SKILL.md. Otherwise, set TARGET=skills/cmd-*/SKILL.md (all personal skills).

1. Inventory

Read every SKILL.md in scope. For each skill, record:

FieldWhat to capture
Namename: from frontmatter
Description lengthword count (rough)
Has trigger phrasesyes / no
disable-model-invocationtrue / false / missing
Overlaps withlist any skills with similar purpose

Print the inventory table before proceeding so the user can orient.

2. Claude's analysis

For each skill (or the single target), produce a proposal row:

FieldValues
Issue typeverbose / weak-trigger / missing-trigger / redundant / rename / merge-candidate / looks-good
Suggested fixone concrete sentence — what to change and how
Priority🔴 breaking / 🟡 worth fixing / 🟢 minor

Flag pairs that substantially overlap and note which one should be canonical.

3. Codex review

Write the inventory + proposals to a tempfile, then invoke Codex for a second opinion:

PROPOSAL_FILE=$(mktemp -t skills-proposal.XXXXXX.md)
OUT_FILE=$(mktemp -t skills-codex.XXXXXX.md)

# Write proposal to tempfile using the Write tool, then:

codex exec \
  --sandbox read-only \
  --skip-git-repo-check \
  --color never \
  --output-last-message "$OUT_FILE" \
  "$(cat <<PROMPT
You are reviewing a set of Claude Code personal agent skills.

Read the proposal file at $PROPOSAL_FILE. It contains:
- An inventory table of each skill's name, trigger coverage, and flags
- Claude's proposed improvements (issue type + suggested fix)

Your job:
1. For each proposed change: agree / disagree / modify. One line per item.
2. Flag anything Claude missed — skills with weak or missing triggers, descriptions that won't auto-trigger reliably, overlaps Claude didn't catch.
3. Identify which descriptions are too long (agent descriptions should be scannable, not exhaustive).
4. Flag any skill whose purpose is fully covered by another skill.

Constraints:
- Do NOT suggest new skills. Focus on improving what exists.
- Be specific. Vague feedback ("make it better") is useless.
- If a skill looks solid, say so.

Output format (markdown, no preamble):

## Codex verdict per proposal
[table: Skill | Claude's proposal | Codex verdict (agree/disagree/modify) | Codex note]

## Missed issues
[bullets — things Claude didn't flag, with skill name and specific concern]

## Overall assessment
[2-3 sentences on the catalog health]
PROMPT
)" < /dev/null

Show Codex's raw output verbatim under a ## Codex review heading.

4. Synthesize

Merge Claude + Codex input into a final approval table. One row per proposed change:

| # | Skill | Change | Source | Priority |
|---|-------|--------|--------|----------|
| 1 | cmd-pr-edgecase | Tighten description — remove first two sentences | Both agree | 🟡 |
| 2 | cmd-codex-review-plan | Add trigger "second opinion on plan" | Codex flagged | 🟡 |
| 3 | cmd-pr-follow-up | Merge into cmd-pr-scope-sweep (near-duplicate) | Claude flagged, Codex agrees | 🔴 |

Where Claude and Codex disagree, include both positions and note the disagreement. Don't auto-resolve in Claude's favor.

5. Approval gate

Present the final table with per-item checkboxes using AskUserQuestion. Group by priority (🔴 first).

Ask: "Which changes should I apply?"

Options (multi-select):

  • Each item as its own checkbox: #N — <skill> — <one-line summary>
  • "Apply all 🔴 items"
  • "Apply all 🟡 items"
  • "Skip everything"

Do not proceed until the user responds. If the user selects nothing, stop and confirm.

6. Apply approved changes

For each approved item, edit the relevant SKILL.md in ~/workspace/agent-skills/skills/<skill-name>/.

After all edits:

  1. Update README.md — update the description in the skills table for any edited skill; remove the row for any deleted skill; add a row for any renamed skill.
  2. Update ~/.claude/CLAUDE.md — if the change affects how the skill is triggered or described, update the corresponding entry in the Custom Skills section.
  3. Update agents/AGENTS.md — same as above; both files should stay in sync.
  4. Run make link-skills from ~/workspace/agent-skills to re-link any renamed or new skill directories.

Report a summary table of what was applied:

SkillChange appliedFiles updated
cmd-pr-edgecaseDescription trimmedSKILL.md, README.md

Codex prompt

The exact prompt is embedded in step 3. Key requirements when adapting:

  • Feed Codex the inventory + proposals file — not raw SKILL.md content — so it reviews Claude's reasoning, not just the raw text.
  • Demand per-item verdicts so synthesis is mechanical, not interpretive.
  • Allow Codex to flag issues Claude missed; this is the main value of the second pass.
  • Read-only sandbox — Codex must not edit files.

Apply phase

  • Only edit files for approved items. No silent scope creep.
  • For merges or deletes, confirm once more with the user before destructive action (removing a SKILL.md directory).
  • If codex exec errors with auth, tell the user to run codex login and stop.

Proofread

You are a proofreader for posts about to be published.

Review workflow

  1. Read the complete file, including frontmatter, before suggesting or applying changes.
  2. Inspect the working-tree state and preserve unrelated user changes.
  3. Perform a deliberate mechanical pass line by line. Check spelling, homophones, word usage, missing or extra words, articles, prepositions, sentence boundaries, punctuation, spacing, capitalization, agreement, tense, parallel structure, dangling modifiers, idioms, quote punctuation, and repeated wording.
  4. Perform a second mechanical pass after editing. Read the revised text as prose, not just the changed lines, and check that every sentence is grammatical and that no typo or punctuation error remains.
  5. Inspect links, images, captions, dates, and filenames for consistency. Do not claim these are clean without checking whether they exist.
  6. Report findings grouped by category below. For every finding, cite the exact text, identify the location when practical, explain the issue briefly, and suggest a fix.
  7. Apply spelling, grammar, syntax, punctuation, word-usage, repetition, and link fixes in place — don't just report them, edit the file directly.
  8. Do not silently make substantive changes to the author's claims, evidence, argument, tone, or structure. Report those as recommendations and ask before changing them.
  9. Always include an "Other improvement opportunities" section. It must either list concrete suggestions for clarity, structure, pacing, specificity, audience fit, or emphasis, or explicitly say that no additional opportunities stood out.
  10. If a category is clean, say so — don't invent issues.
  11. After all edits are applied, offer the optional passes below (in order). Each is opt-in; the user may pick any combination or none: a. Skimmability pass — "Would you like me to make this ultra-skimmable?" b. Emphasis pass — "Want me to surface candidates for blockquote pullouts and bolded one-liners?" c. Hedge pass — "Want me to flag low-confidence phrasing ('I think', 'kind of', 'maybe', 'soon') so you can decide what to keep or cut?" d. Audience-target pass — "Is there a specific reader you want to impress? Name them and I'll shape the post to what they respect." e. Writing vibe pass — "What writing vibe do you want it to have?" (menu below)

Review Categories

Spelling and Typos

  • Identify misspellings, typos, transposed letters, malformed words, homophones, and incorrect word usage (e.g., "their" vs "there").
  • Pay special attention to words that look plausible but are wrong in context, such as a misspelled noun that changes the meaning of a sentence.
  • Fix these in place

Grammar

  • Identify grammar and syntax mistakes including subject-verb agreement, tense consistency, sentence fragments, dangling modifiers, parallel structure, missing words, article/preposition usage, punctuation, quotation punctuation, and stray spaces.
  • Check that coordinated phrases use the same grammatical form. For example, "capable, curious, resourceful, and live with..." needs a parallel construction.
  • Check that the grammatical subject performs every verb. For example, a sentence beginning with "I" should not shift into an unowned verb after a comma.
  • Fix these in place

Repetition

  • Watch for repeated terms and phrases (e.g., "It was interesting that X, and it was interesting that Y")
  • Flag overused words, filler phrases, redundant constructions, and repeated meaning (e.g., "end up turning out").
  • Fix these in place

Common missed-error patterns

Use these as a final trap list, not as an exhaustive checklist:

  • Plausible-looking misspellings: complacencity → complacency, deisre → desire.
  • Stray punctuation and malformed endings: proud of . and a much more difficult one when the sentence needs much more difficult.
  • Tense and subject drift: I would scoff ... and inadvertently, developed should be checked for a consistent subject and tense.
  • Broken syntax around quoted phrases: "I'm so glad it happened" sort of people should be checked as a complete sentence, not only for punctuation.
  • One-pass false confidence: do not stop after fixing the first typo; reread every sentence after the edits.

Logic and Factual Accuracy

  • Spot logical errors, contradictions, or factual mistakes
  • Flag claims that need a source or citation
  • Report these to the user for approval before editing

Weak Arguments

  • Highlight weak arguments that could be strengthened
  • Flag vague statements that lack supporting evidence
  • Report these to the user for approval before editing

Other improvement opportunities

  • Look beyond correctness for concrete improvements to clarity, structure, pacing, specificity, transitions, audience fit, emphasis, and reader takeaway.
  • Include the exact text, the opportunity, why it may help, and a proposed direction or rewrite when useful.
  • Keep this separate from mechanical fixes. These are recommendations, not silent edits, unless the user explicitly asks for a broader rewrite.

Links

  • Make sure there are no empty or placeholder links
  • Flag any links with suspicious or incomplete URLs
  • Verify visible link text matches the URL slug/title. Mismatches usually mean a typo in one or the other (e.g., link text says "Nonpayments" but URL slug is "nanopayments")
  • Fix or flag these in place

Image/Text Consistency

  • If the post includes screenshots, charts, or other generated graphics, verify any visible dates, captions, and labels against the surrounding post text and filename conventions
  • Flag mismatches that would make the post feel internally inconsistent or future-dated

Final report checklist

Before responding, confirm that the report includes:

  • The edits applied in place, grouped by mechanical category.
  • Any remaining logic, factual-accuracy, weak-argument, or improvement recommendations that were not applied.
  • A clear statement about links and images, including when none are present.
  • Validation performed after editing, such as a diff/whitespace check or project build when available.
  • The optional-pass questions in the order listed below.

Skimmability Pass (optional, user must opt in)

If the user says yes, present the proposed changes first and apply after approval. Offer the options below à la carte — the user may pick any combination.

Italicized TL;DR lead-in

  • Add a single-line _TL;DR: ..._ italicized summary directly under each section heading
  • The TL;DR should give skimmers the section's key takeaway in one sentence

Bolded one-liner summaries (alternative to TL;DR)

  • Each major section or subsection opens with a bolded one-line summary instead of, or in addition to, the italicized TL;DR

Emoji prefixes on lists

  • When a list conveys distinct categories or themes, add a relevant emoji prefix to each item
  • Don't overdo it — only use emojis on lists where they add visual distinction, not on every bullet in the post

Break up prose walls

  • If a paragraph contains a list of 3+ items, pull them into bullet points
  • If a paragraph is longer than 3 sentences and covers multiple ideas, break it into shorter paragraphs

Shorten dense paragraphs into scannable formats

  • Long comma-separated lists in prose → bullet lists
  • "If X, then Y" tradeoff patterns → one-line bullets (e.g., "Want reach? You give up revenue.")
  • Dense reference lists (tools, protocols, links) → bulleted with emoji prefixes

Preserve the author's voice

  • Do not rewrite sentences that already read well — only restructure for scannability
  • Keep the author's word choices, tone, and personality intact
  • The goal is reformatting, not rewriting

Emphasis Pass (optional, user must opt in)

Scan the post for visual landing points that reward skimmers and reinforce the thesis. Surface candidates; don't batch-apply.

Blockquote candidates

  • Thesis statements that summarize a section's argument in one sentence
  • Punchy verdicts that deserve to stand alone ("That is the perfect base layer. It can't be any simpler.")
  • Named patterns or framings that are quotable ("A vendor ships an SDK that quietly becomes the de facto protocol...")

Bold candidates

  • Short, confrontational sentences that challenge a reader's default ("Keys are not a cop-out.")
  • One-line verdicts closing a section ("I believe the middle path wins.")
  • Memorable phrases worth surfacing mid-paragraph ("follow the customer that comes back")

Guardrails

  • Cap at 3–4 bold/blockquote additions per post. More dilutes emphasis.
  • Do not bold or blockquote items that are already marked up.
  • Present candidates grouped by type; let the user pick which to apply.

Hedge Pass (optional, user must opt in)

Surface phrases that soften the claim without adding evidence. Flag; let the user keep or cut.

What to flag

  • Low-confidence verbs: "I think", "I feel like", "maybe", "kind of", "sort of"
  • Vague time markers without a source: "soon", "eventually", "at some point"
  • Self-deprecating appendices: "but I could be wrong", "and I'd love to be wrong"
  • Unsupported predictions: "X will need updating" without citing why or when
  • Credentialed vagueness: "If you've been in X long enough, you've seen this" — either name the specific pattern, or cut

How to decide

  • Keep the hedge if it genuinely calibrates a speculative claim (e.g., forecasts, judgment calls the author wants to signal as open).
  • Cut the hedge if the surrounding claim is load-bearing and the hedge is reflex, not calibration.
  • When unsure, present both versions and let the user choose.

Audience-Target Pass (optional, user must opt in)

Ask: "Is there a specific reader (named person or archetype) you want to reach? Tell me who, and I'll shape the post to what they respect."

How to apply

Once the user names a target:

  1. Infer their standards. What kind of argument does this reader find credible? What turns them off? (E.g., Patrick Collison respects fair critique, historical depth, concrete numbers — and skips past sneering, vague credentialing, or throwaway predictions.)
  2. Scan the post against those standards. For each section, identify:
    • Claims that would feel under-supported to this reader
    • Tonal shots (sneering, hedging, cheap jokes) that cost credibility
    • Detours that a busy target reader would skip
    • Missed opportunities to steelman the opposition
  3. Report findings as a prioritized list — highest signal first. For each finding, say why it matters to this reader specifically.
  4. Ask which to apply. Audience-target edits touch substance, so always get approval per item.

Guardrails

  • Don't rewrite the author into a different person. You're sharpening the existing argument for a specific audience, not ventriloquizing.
  • Preserve the author's evidence and core claims. Adjust framing, not facts.
  • If the target reader would be uncomfortable with the post entirely (e.g., it critiques them directly), surface that honestly — "This post will land harder if the target doesn't feel attacked; want me to reframe the critique?"

Writing Vibe Pass (optional, user must opt in)

After the skimmability pass, offer to shape the post's voice toward a known author's style. Present the menu below; the user picks one or says "other".

Menu

  • DHH (David Heinemeier Hansson) — opinionated, contrarian, declarative sentences, hot takes grounded in historical context
  • Simon Willison — understated, experiment-driven, lots of concrete examples, generous linking, "here's what I tried" framing
  • Andrej Karpathy — first-principles, pedagogical, analogies from ML to everyday life, dense but lucid
  • Mitchell Hashimoto — engineering-honest, tradeoff-forward, detail-rich without jargon, systems thinking
  • Sam Parr — punchy, conversational, story-first, bullet-heavy, ends with a takeaway
  • Shaan Puri — high-energy, pattern-spotting, frameworks and mental models, "here's the play" framing
  • Other — user names an author; ask for a reference text

Application

  • Use your internal knowledge of the chosen author's rhythm, sentence length, vocabulary, and structural habits
  • Optionally ask: "Got a specific piece of their writing you want me to use as reference?" — if yes, read it first before rewriting
  • Present proposed rewrites before applying — vibe changes touch voice, so always get approval per section rather than batch-applying
  • Preserve the author's (the user's) core points and evidence. You're adjusting delivery, not substance

Agents 2

Olshansky's AGENTS.md

Writing Code

  • Bias toward less code when it still solves the problem.
  • Prefer standard or open source libraries/tools over reinventing them.
  • Focus on solving the problem, not cleverness.
  • Optimize for simplicity and speed to resolution.

Python

Always use uv for Python projects unless explicitly told otherwise.

  • Use uv sync, not pip install.
  • Use uv run python, not python or .venv/bin/python.
  • Use uv run <tool> for pytest, ruff, mypy, and other tools.
  • Create pyproject.toml for dependencies, not requirements.txt.
  • Use uv add <package> to add dependencies.

Docstrings

  • Trivial helpers need only a one-line summary plus Args/Returns when useful.
  • Non-trivial functions require a How: section with numbered steps, one per logical action.
  • Trigger How: when a function:
    • Calls an external service.
    • Tolerates multiple input shapes or SDK versions.
    • Has fallback, retry, address normalization, or other non-obvious failure behavior.
    • Performs more than roughly five steps a reader cannot reconstruct from names.
    • Is the entry point for a flow spanning multiple modules.
  • Shape: summary, How:, Args, Returns.

CLI Tools

Prefer modern CLI tools over legacy alternatives:

TaskUseInstead of
Find filesfdfind
Search contentrggrep

Use command examples only when they add task-specific value; avoid long command tutorials in responses.

Documentation

  • Add a Table of Contents for documentation.
  • Ignore the top level or deeply nested headers using <!-- omit in toc -->.
  • Prefer bullets and subheaders over long paragraphs, without overdoing it.
  • Start with the payoff, then details. Do not add filler like "this is scalable" without concrete value.
  • Always add syntax highlighting to fenced code blocks.
  • Follow documentation patterns from great products.
  • Provide easy copy-paste onboarding instructions.
  • Do not put multiple commands plus comments in one code block. Use separate labeled blocks instead.
  • Reference specific functions with file_path:line_number.
  • Follow Keep a Changelog format for changelog updates.

Agent Rules Integration

@~/workspace/agent-rules

  • Use /check for comprehensive quality checks.
  • Use /commit for structured commits with conventional format and emoji prefixes.
  • Use /implement-task for methodical task implementation with planning phases.
  • Use /clean to fix formatting and linting issues across a codebase.
  • Use /context-prime to load comprehensive project understanding.

Git Workflow Integration

  • User commits manually: Do not ask "should I commit?" or offer to commit.
  • Conventional commit format: type(scope): description.
  • Emoji prefixes: ✨ feat, 🐛 fix, 📝 docs, ♻️ refactor.
  • Run quality checks before commits.
  • Do not commit during active quality check processes.

Global Configs

Source of truth for shell and system configuration: ~/workspace/configs

  • .zshrc — main zsh entrypoint; sources all zshrc.d/ modules in order.
  • zshrc.d/core/ — PATH setup, shared env, lazy-loaded tools.
  • zshrc.d/development/ — language toolchains (node at 005.node.sh, python, postgres, etc.).
  • zshrc.d/ai-tools/, zshrc.d/cloud/, zshrc.d/blockchain/, zshrc.d/utilities/ — domain-specific config.
  • scripts/ — shell utility scripts (benchmarking, validation, optimization).
  • claude/ — Claude-specific config, sessions, skills, tasks, plans.
  • AGENTS.md — repo-local agent notes for this config repo.

When debugging PATH, shell startup, or tool-not-found issues, check zshrc.d/ modules first. When modifying shell config, edit files in ~/workspace/configs/zshrc.d/ (not ~/.zshrc directly).

MCP Server Management

  • Use ~/workspace/agent-rules/global-rules/mcp-sync.sh to synchronize MCP configurations.
  • Review configuration differences across Claude Desktop, Cursor, and VS Code.
  • Switch between local development and global npm packages as needed.

Context Loading Strategy

  1. Read README.md and AGENTS.md or the tool-specific instruction file.
  2. List project structure with git ls-files | head -50.
  3. Review configuration files such as package.json, pyproject.toml, Cargo.toml, and equivalents.
  4. Understand the development workflow before editing.

Development Commands

Makefile First: Before suggesting raw commands, check make help.

  • Prefer make <target> over raw commands because project Makefiles source env files, activate the right venv, and stay aligned with CI.
  • Use make help-unclassified when a target may exist but is not listed in the main help.
  • If no Makefile exists, fall back to documented commands in AGENTS.md, CONTRIBUTING.md, or README.md.
  • If docs do not define a command, use the language-standard toolchain with the project package manager.

Custom Skills

Source of truth: ~/workspace/agent-skills/skills/ is canonical for personal skills.

  • When asked to update, edit, or create a skill, always work in ~/workspace/agent-skills/skills/<skill-name>/ regardless of current directory.
  • When any personal skill changes, update ~/workspace/agent-skills/README.md and relevant agent metadata so the skill stays discoverable.
  • Runtime path ~/.claude/skills/ contains symlinks back to the repo via make link-skills; never edit runtime symlink targets directly.
  • After npx skills add olshansk/agent-skills, run make link-skills in ~/workspace/agent-skills to restore direct symlinks.
  • Skill directories contain SKILL.md with YAML frontmatter. Most cmd-* skills have disable-model-invocation: true; cmd-plan-store may auto-trigger on phrases like "store this plan" or "save this plan for later".
  • Naming conventions:
    • Personal global skills always use cmd-.
    • Repo-specific skills use the repo name prefix, or ask if ambiguous.
  • See ../README.md#available-skills for the canonical skill catalog.
  • Reference skill: cmd-makefile/ contains Makefile conventions, templates, and patterns.
  • Review skill: cmd-makefile-improve/ audits that foundation and proposes approval-gated iterations.

Communication Format Preferences

Default to tables whenever presenting structured data. Prefer a table over a bullet list whenever there are 3+ items with 2+ attributes.

Always use color-coded severity emoji in a Severity column for any table that contains items needing attention. Add a numbered # column as the first column, then Severity, so rows are easy to reference. Never bury risk in prose paragraphs.

#SeverityMeaningWhen to use
1🔴Critical / blockingStop and act now; tests broken, data loss risk, merge blocked
2🟠HighFix before merging; likely regression or behavior change
3🟡MediumReview soon; non-blocking but needs eyes
4🟢Good / informationalNo action needed; explicit all-clear
5✅SuccessTask completed cleanly
6❌FailureTask failed or item is broken
7⚠️Cascading / unknownSide-effects outside the immediate scope

Rules:

  • Any output section that contains risk items MUST use this color system — not free-form prose.
  • For any risk, status, decision, or review table, the first column MUST be numbered #; put severity/status in the second column.
  • When a section has zero risk items, end it with an explicit 🟢 all-clear line rather than omitting the section.
  • Never mix severity into bullet prose when a table fits.

Markdown table preview files:

  • When a response includes a Markdown table that is wide or important enough to reuse/share, or has at least 4 columns or at least 6 rows, also write that table to /tmp/table_<YYYYMMDD_HHMMSS>_<randomsuffix>.md.
  • Write the exact Markdown table the user sees, preserving links, inline code, and emoji. If the table needs context, add one short Markdown heading above it in the temp file.
  • Immediately below the table in the chat response, add a preview tip using the actual file path.
  • Tip format: 💡 Tip: view the formatted table by running mdtt /tmp/table_20260516_143022_a7f3.md
  • Example filename: /tmp/table_20260516_143022_a7f3.md
  • Only show the mdtt tip after the file is created. Skip temp-file creation for small/simple tables, sensitive content, code/documentation examples, and tasks where the user explicitly requests no filesystem writes.
Use casePreferred shape
Test resultsMatrix with #, ✅/❌/🔴/⏭️ status, and one-line details
Before/after diffsFeature diff table with # and severity emoji
Behavioral matricesConfig/env combinations mapped to expected behavior
Bug summariesTable with #, 🔴/🟡 severity, Bug, Root Cause, Fix columns
Cascading impactTable with #, 🔴/🟡/🟢 Risk, File, Why, Action columns
Planning/comparisonTables when comparing 3+ items across 2+ dimensions

General Guidelines in Code

  • Be concise yet clear; do not sacrifice needed context.
  • Trim comment noise while preserving meaning.
  • Follow language best practices.
  • Break long paragraphs or run-on sentences into bullets.
  • Start standalone sentences on new lines.
  • Never remove content from the original input when transforming user-provided prose unless explicitly asked.
  • When responding to multiple questions or topics at once, number each item so follow-ups can reference them.
  • In prose, code comments, and docs, put each numbered or lettered list item on its own line.

Refactoring Safety

Carry forward all write paths. When refactoring code that persists data, verify all write paths are preserved, not only the happy-path read/response.

Audit every db.commit(), db.flush(), cache invalidation, and attribute assignment before and after extraction.

Avoid extracting a function that writes metadata_json into a callback that only returns data unless another finalization step writes the metadata.

Plan Files

When asked to "save this plan for later" or "document this for later", write to the project's plans/ directory:

plans/{name}_{yyyy}_{mm}_{dd}.md

Example: plans/frontend-logic-cleanup_2026_03_28.md.

Logging Conventions

When adding logging, establish and follow emoji plus color conventions for scannable output.

EmojiLevelWhen to use
🔍infoStarting a long analysis, search, or extraction
🔧infoGenerating or mutating artifacts
✅infoSuccessful completion with summary stats
⚠️warningPartial failure or non-fatal fallback
🚨warning/errorCritical failure, data loss risk, or broken dependency
ColorPriorityWhen to use
Red🔴 HighStop and fix now
Yellow🟡 MediumReview soon
Green🟢 InformationalNo action needed
CyanEntity namesSchema names, file names, IDs, dataset names

TODO Comment Standards

Use specific TODO prefixes:

PrefixUse
TODO:General improvements or future work
TODO_IMPROVE:Code quality and refactoring
TODO_OPTIMIZE:Performance improvements
TODO_IDEA:Potential features or enhancements
TODO_CONSIDERATION:Design decisions to revisit
TODO_TECHDEBT:Technical debt
TODO_IN_THIS_PR:Work to complete in the current PR
TODO_REMOVE_LATER:Temporary code removable after a named condition
FIXME:Known bugs
HACK:Temporary workarounds
NOTE:Important explanations or warnings

TODOs must include:

  • What needs to be done.
  • Why it is deferred or needed.
  • How to implement it when useful.
  • What blocks it when relevant.

When a deferred improvement, rejected suggestion, design tradeoff, or "maybe later" comes up:

  1. Check whether a relevant TODO already exists.
  2. If not, ask: "Should we add a TODO or TODO_{TYPE} for this? What priority/prefix?"
  3. Add the TODO with proper context if confirmed.

For TODO_REMOVE_LATER, place the TODO directly above the temporary branch and include what can be removed, when it is safe to remove, and why the branch exists. If unsure whether behavior is temporary, use TODO_TECHDEBT instead.

Response Status Tags

End every response with exactly one tag on its own line:

TagMeaning
[✅ AGENT - SUCCESS ✅]All done, all green
[🔴 AGENT - HIT AN ERROR 🔴]Task failed
[⚠️ AGENT - PARTIAL COMPLETION ⚠️]Some done, blockers remain
[🤔 AGENT - NEEDS HUMAN INPUT 🤔]Needs decision, approval, or clarification
[🚩 AGENT - FLAGGED & NEEDS REVIEW 🚩]Work complete but a specific item was flagged — review before treating as done

Use NEEDS HUMAN INPUT when the user still needs to approve a plan or code that has not been committed/deployed. Use FLAGGED & NEEDS REVIEW when the task is done but the response ends with a concrete note or caveat the user should act on (e.g. a placeholder command, an assumed value, a missing dependency). Use SUCCESS only when the requested work is fully applied with no open flags. When unsure, prefer NEEDS HUMAN INPUT.

Gemini Added Memories

  • The make ghd-pre-process-images target is implemented and fully functional, wrapping scripts/process_ghd_data.py to run the GHD pipeline with Surya OCR.
  • The GHD pipeline now supports single-image processing via the --image flag in scripts/process_ghd_data.py, and data cleaning is modularized in src/ghd_pipeline/steps/data_cleaner.py.
  • I've implemented robust orientation correction in src/ghd_pipeline/steps/orientation.py that uses EXIF data followed by Tesseract OSD (with Otsu thresholding preprocessing) to ensure images are upright based on text legibility.
  • I increased the Tesseract OSD confidence threshold to 2.0 in src/ghd_pipeline/steps/orientation.py to prevent false positive rotations on noisy soil images, as low-confidence detection (e.g., 1.01) was causing incorrect flips.
  • I've implemented a relaxed regex fallback in src/ghd_pipeline/steps/label_reader.py that can extract Lab IDs like WLT1321 from messy text (e.g., WLT1321 23-02...), logging a "🚨 Fuzzy match" warning when this occurs.
  • I've updated the regex in src/ghd_pipeline/steps/label_reader.py to support Lab IDs with hyphens between the prefix and number (e.g., WLT-1349-9).
  • The images IMG_1986.JPEG and IMG_2427.JPEG are unreadable by both Surya and Tesseract OCR despite upscaling (2x), rotation (180/EXIF), preprocessing (Otsu/CLAHE), and card cropping attempts, due to low contrast and noise.
  • The SQLite database cache/followers.db has a followers table with primary key (id, followed_username). It stores flattened follower data including followers_count, screen_name, etc. The script scripts/json_to_sqlite.py populates it from merged.json files.
  • Implemented src/vision/smart_crop.py which uses FastSAM (via ultralytics) to deterministically crop soil regions, avoiding labels and trays. It includes a fallback to texture-based sliding window. Run via uv run python src/vision/smart_crop.py <image>.
  • Updated GHD pipeline (scripts/process_ghd_data.py, src/ghd_pipeline/pipeline.py) to use SmartCropper by default. It now generates 4 crops per image using FastSAM (MPS/GPU enabled). Legacy contour cropping is available via --no-smart-crop.
  • The Grove API consists of three main areas: funding (x402 protocol), tipping (destinations: addresses, ENS, llms.txt, Twitter), and account management (balances, history). Funding is a 2-step process requiring a client-side signature. Tipping requires a JWT obtained during funding.
  • The file agent_sdk/grove.py is a standalone Python SDK I created to simplify agent onboarding. It handles the x402 payment protocol (signing EIP-712 messages) for the /fund endpoint and provides simple methods for tipping and checking balances, abstracting away cryptographic complexity for agent developers.
  • Updated SmartCropper to support strategy="roi" (default for pipeline), which produces a single, high-resolution crop of the entire soil region (based on segmentation mask) instead of multiple training tiles. Fixed naming convention to match legacy (IMG_XXXX_crop.jpg).
  • Updated training configuration: ResNet backbone is now unfrozen (FREEZE_BACKBONE=False) and input resolution increased to 512x512. VLM System Prompt now uses a "Geotechnical Engineer" persona with Chain-of-Thought reasoning ("Field Description" before JSON).
  • Added Substack integration: created SubstackProfile adapter using local substack-api library, updated SocialPlatform and resolver logic, added unit tests, and comprehensive E2E tests (make test_e2e_substack, make test_e2e_all). Updated project python requirement to >=3.12.
  • Verified Substack adapter handles all URL formats (subdomain, path, @handle) and extracts addresses from bio, display name, and handle/username. Added comprehensive unit tests for these cases.
  • Encountered DNS resolution error for 'substack.com' in user's environment, preventing E2E confirmation of Substack tipping. Code logic and unit tests are verified correct.
  • Updated ResNet training pipeline: froze backbone, increased resolution to 512x512, added RandomVerticalFlip, renamed 'grain' to 'gradation' in code, and implemented K-Fold Cross Validation. Added loss weighting (10.0 for gradation, 1.0 for Atterberg).
  • Unfroze ResNet backbone (FREEZE_BACKBONE=False) and switched to console.print for epoch logging to fix missing logs issue. Kept 512x512 resolution and loss weighting.
  • The "Unit Detection Summary" in the Units tab was refactored to remove the outer section wrapper and simplify nested evidence statistics boxes, matching the flatter style of the Mapping Workbench.
  • The "Prepare preview" (loadInlineDataPreview) returns empty results if the BoreDM target table (e.g., 'log', 'lithology') lacks a 'PointID' field after mapping, as 'join_comapped_rows' in 'server/core/normalization.py' depends on it to merge co-mapped tables. If 'PointID' is unmapped or missing, rows are skipped during normalization.

Sponsors

Details

Marketplace
Olshansk/agent-skills
Source
olshansk/agent-skills
Author
Daniel Olshansky
Category
Workflow