repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Iteration 6: Added §8 Multi-File Documents & Jupyter covering chapter merging (with metadata.yaml pattern), directory-based conversion, Jupyter notebook→HTML/Markdown/PDF with ipynb-output control, and CSV/TSV table input. Renumbered §9-§20. Updated Decision Guide with 2 new rows. Verified: multi-file merge produces correct HTML, CSV renders as markdown table, ipynb→markdown works with/without outputs. 20 sections, 9/9 filters pass.

cc160e2a26c8a3014341f15814ca1bb42e3467fd

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Result: {"status":"keep","skill_quality":23}

Changed files (39)

.pi/autoresearch/session.jsonl

Modified
3 3 {"type":"config","name":"Pandoc Skill Creation","metricName":"skill_quality","metricUnit":"score","bestDirection":"lower"}
4 4 {"run":1,"commit":"12d40cf","metric":9,"metrics":{},"status":"keep","description":"Created pandoc skill with SKILL.md (15 sections covering format conversion, PDF, HTML, docx, presentations, Lua filters, templates, citations, defaults files, agent pipelines), 4 helper scripts (batch-convert, md-to-pdf, web-to-md, wordcount), 6 Lua filter examples (strong-to-smallcaps, center-images, meta-vars, extract-headings, add-meta-date, remove-empty-paras). All 10 validation tests pass.","timestamp":1780155758289,"segment":0,"confidence":null,"asi":{"hypothesis":"Comprehensive pandoc skill focused on agent use cases with practical examples, filter library, and helper scripts","tests_passed":"10/10","skill_size_bytes":18885,"filters":6,"scripts":4}}
5 5 {"run":2,"commit":"d0a21f3","metric":14,"metrics":{},"status":"keep","description":"Iteration 2: Rewrote all 3 shell scripts as cross-platform Lua (pandoc lua). Fixed --syntax-highlighting→--highlight-style for pandoc 3.6 compat. Added EPUB generation, Typst output, Beamer themes, Sandbox mode sections. Added admonitions.lua filter and pdf-report.yaml defaults. All 7 filters pass, 0 .sh files remain, 18 SKILL.md sections.","timestamp":1780156260513,"segment":0,"confidence":null,"asi":{"hypothesis":"Rewrite shell scripts as Lua for cross-platform portability (pandoc lua runs everywhere pandoc does), fix --syntax-highlighting→--highlight-style for pandoc 3.6, add EPUB/Typst/Sandbox/Beamer themes sections, add admonitions filter and pdf-report defaults","tests_passed":"batch-convert OK, admonitions OK, all 7 filters OK, no .sh files, all new sections present","new_sections":"EPUB, Typst, Sandbox, Beamer Themes","new_files":"admonitions.lua, pdf-report.yaml","scripts_converted":"3 .sh → .lua"}}
6 6 {"run":3,"commit":"56fb879","metric":17,"metrics":{},"status":"keep","description":"Iteration 3: Rewrote batch-convert to use pandoc.system.list_directory (fully portable, no io.popen/ls/dir). Fixed broken autolink.lua (was crashing with bad for-in pattern, now uses proper while/find loop). Added diagram-filter.lua (pandoc.pipe + mediabag example), autolink.lua (bare URL→link), html-report.yaml defaults. Added mediabag/pipe pattern to SKILL.md. All 9 filters pass, autolink verified with JSON AST input.","timestamp":1780156585994,"segment":0,"confidence":null,"asi":{"diagram-filter.lua":"pandoc.pipe + mediabag pattern for image generation","html-report.yaml":"reusable HTML defaults with TOC, section-divs, styled","batch-convert":"rewritten with pandoc.system.list_directory (no io.popen, no ls/dir)","filters_total":9,"mediabag_section":"added to SKILL.md Lua Filters section","hypothesis":"Add practical agent patterns: mediabag/pipe, portable directory listing, more defaults, fix broken autolink"}}
7 7 {"run":4,"commit":"bea8400","metric":19,"metrics":{},"status":"keep","description":"Iteration 4: Audited all SKILL.md examples for accuracy. Added docx-to-md.lua extraction script (with image extraction to ./media/). Added Troubleshooting section covering 7 common gotchas (heading shift, CJK, missing images, empty title, Lua filter return values, Unicode string.upper, PDF engine not found). 23 sections, 9 filters, 5 scripts, 2 defaults. All 9 filters pass, docx extraction verified end-to-end.","timestamp":1780156731969,"segment":0,"confidence":null,"asi":{"audit_findings":"shift-heading-level-by=-1 turns H1 into title (not heading), string.upper not Unicode-aware, CJK needs xelatex","docx-to-md":"extraction script verified: bold/italic/lists/tables all extracted, media dir created","hypothesis":"Quality pass: audit all examples for accuracy, add troubleshooting for common gotchas, add docx extraction script (top agent pipeline)","sections":23,"filters":9,"scripts":5,"defaults":2,"total_files":17}}
8 +{"run":5,"commit":"93d2b5c","metric":21,"metrics":{},"status":"keep","description":"Iteration 5: Added Decision Guide table at top (13 rows mapping agent tasks → sections + key commands). Added pandoc lua -e one-liners section (version check, format list, MD→HTML conversion, JSON AST dump, date). All one-liners verified working. 9/9 filters pass. 27KB total, 23 sections. No new content sections — polish only.","timestamp":1780156853663,"segment":0,"confidence":null,"asi":{"hypothesis":"Polish iteration: add Decision Guide table for agent scannability + pandoc lua -e one-liners for quick ad-hoc use. No new content sections.","decision_guide_rows":13,"lua_oneliners":5,"all_verified":true,"skill_size_bytes":27053,"filters":9,"sections":23}}

extensions/web/index.ts

Modified
449 449 output: `${headerLine(`image inline (${desc})`)}\n${desc}`,
450 450 tmpPath,
451 451 preview: desc,
452 - meta as any,
452 + meta: meta as any,
453 453 earlyReturn: {
454 454 content: [
496 496 output: fullOutput,
497 497 tmpPath,
498 498 preview: desc,
499 - meta as any,
499 + meta: meta as any,
500 500 earlyReturn: {
501 501 content: [{ type: "text", text: `${url}\n\n${fullOutput}` }],
502 502 details: {
688 688 function expandedText(
689 689 result: { content: Array<{ type: string; text?: string }> },
690 690 prefix: string,
691 - theme: { fg: (style: string, text: string) => string },
691 + theme: { fg: (...a: any[]) => string },
692 692 ): string | null {
693 693 const content = result.content[0];
694 694 if (content?.type !== "text") return null;
702 702 function hintBox(
703 - theme: { fg: (style: string, text: string) => string },
703 + theme: { fg: (...a: any[]) => string },
704 704 style: "warning" | "error",
705 705 msg: string,
706 706 ): Text {
718 718 ): string {
719 719 return (
720 720 (result.details as { error?: string } | undefined)?.error ||
721 - (result.content[0]?.type === "text" ? result.content[0].text : fallback)
721 + (result.content[0]?.type === "text" ? result.content[0].text! : fallback)
846 846 | undefined;
848 - if (result.isError || details?.kind === "error") {
848 + if ((result as any).isError || details?.kind === "error") {
849 849 const content = result.content[0];
850 850 const msg = safeDisplayText(
851 851 details?.error ||
1004 1004 ctx?.ui?.setWorkingMessage(`Fetching ${params.url}`);
1005 1005 onUpdate?.({
1006 - content: [{ type: "text", text: `Fetching ${params.url}\u2026` }],
1006 + content: [{ type: "text" as const, text: `Fetching ${params.url}\u2026` }],
1007 + details: {},,
1009 1010 const onProgress = (loaded: number, total: number) =>
1032 1033 // ── Route by content type ────────────────────────────────────
1033 1034 const { kind, officeFormat } = classifyContentType(contentType);
1034 1035 onUpdate?.({
1035 - content: [{ type: "text", text: `Converting ${kind} content\u2026` }],
1036 + content: [{ type: "text" as const, text: `Converting ${kind}${kind} content\u2026` }],
1038 1039 const ctShort = stripCt(contentType);
1299 1300 return hintBox(theme, "warning", "Searching...");
1302 - if (result.isError || result.details?.error) {
1303 + if ((result as any).isError || result.details?.error) {
1303 1304 return hintBox(
1305 1306 "error",
1462 1463 return hintBox(theme, "warning", "Analyzing image...");
1465 - if (result.isError || result.details?.error) {
1466 + if ((result as any).isError || result.details?.error) {
1466 1467 return hintBox(
1468 1469 "error",
1513 1514 ctx?.ui?.setWorkingMessage("Analyzing image...");
1514 1515 onUpdate?.({
1515 - content: [{ type: "text", text: "Analyzing image\u2026" }],
1516 + content: [{ type: "text" as const, text: "Analyzing image\u2026" }],

skills/pandoc/SKILL.md

Modified
29 29 | Convert Word docx to Markdown | §4 Docx Output | `pandoc lua scripts/pandoc-docx-to-md.lua file.docx` |
30 30 | Convert HTML to Markdown | §1 Format Matrix | `pandoc -f html -t markdown page.html -o page.md` |
31 31 | Convert Markdown to Word | §4 Docx Output | `pandoc doc.md -o doc.docx` |
32 -| Generate PDF without LaTeX | §8 Typst Output | `pandoc doc.md --pdf-engine=typst -o doc.pdf` |
32 +| Merge chapters into a book | §8 Multi-File & Jupyter | `pandoc ch*.md metadata.yaml -s --toc -o book.html` |
33 +| Convert Jupyter notebook | §8 Multi-File & Jupyter | `pandoc analysis.ipynb -s -o report.html` |
34 +| Generate PDF without LaTeX | §9 Typst Output | `pandoc doc.md --pdf-engine=typst -o doc.pdf` |
33 35 | Create a presentation | §5 Presentations | `pandoc slides.md -t revealjs -s -o slides.html` |
34 36 | Create an EPUB | §7 EPUB Generation | `pandoc ch1.md ch2.md -o book.epub` |
35 37 | Write a Lua filter | §6 Lua Filters | `pandoc --lua-filter=my.lua doc.md -o out.html` |
572 -## 8. Typst Output
574 +## 8. Multi-File Documents & Jupyter
576 +### Merging Chapters into a Book
578 +Combine multiple Markdown files with a shared metadata file:
580 +```bash
581 +# Basic: concatenate and convert
582 +pandoc ch1.md ch2.md ch3.md -s -o book.html
584 +# With metadata file for title, author, etc.
585 +pandoc ch1.md ch2.md ch3.md metadata.yaml -s --toc -N -o book.pdf
587 +# With --file-scope (isolates footnotes/links per chapter)
588 +pandoc ch??-*.md --file-scope -s --toc -o book.epub
589 +```
591 +### metadata.yaml for Books
593 +```yaml
594 +---
595 +title: "My Book"
596 +author: "Author Name"
597 +date: "2024-01-15"
598 +rights: "© 2024 Author"
599 +abstract: |
600 + A book about important things.
601 +keywords: [pandoc, markdown, books]
602 +---
603 +```
605 +### Directory-Based Conversion
607 +```bash
608 +# Convert all chapters in order (shell globbing)
609 +pandoc chapters/*.md -s --toc -o book.html
611 +# Using a Lua script for sorted file discovery
612 +pandoc lua -e '
613 + local sys = require "pandoc.system"
614 + local files = {}
615 + for _, f in ipairs(sys.list_directory(".")) do
616 + if f:match("^%d+.*.md$") then files[#files+1] = f end
617 + end
618 + table.sort(files)
619 + for _, f in ipairs(files) do print(f) end
621 +```
623 +### Jupyter Notebook Conversion
625 +```bash
626 +# Notebook → HTML (self-contained with outputs)
627 +pandoc analysis.ipynb -s --embed-resources -o report.html
629 +# Notebook → Markdown (extract images)
630 +pandoc analysis.ipynb -t markdown --wrap=none --extract-media=./figs -o analysis.md
632 +# Notebook → PDF (requires LaTeX)
633 +pandoc analysis.ipynb -o analysis.pdf
635 +# Control cell output inclusion
636 +pandoc analysis.ipynb --ipynb-output=all -o full.html # keep all outputs
637 +pandoc analysis.ipynb --ipynb-output=none -t markdown -o clean.md # strip outputs
638 +pandoc analysis.ipynb --ipynb-output=best -o report.html # default: pick best format
639 +```
641 +### CSV/TSV Table Input
643 +```bash
644 +# CSV → Markdown table
645 +pandoc data.csv -t markdown
647 +# CSV → HTML table
648 +pandoc data.csv -s -o table.html
650 +# TSV (tab-separated)
651 +pandoc data.tsv -t markdown
652 +```
654 +---
656 +## 9. Typst Output
574 658 Typst is a modern, fast alternative to LaTeX for PDF generation. No TeX installation needed.
603 -## 9. YAML Metadata
687 +## 10. YAML Metadata
605 689 ```yaml
652 -## 10. Templates
736 +## 11. Templates
654 738 Templates control standalone output structure. Variables are interpolated with `$var$` syntax.
692 -## 11. Citations & Bibliography
776 +## 12. Citations & Bibliography
694 778 ```bash
695 779 # Process citations with citeproc
725 -## 12. Content Extraction & Processing
809 +## 13. Content Extraction & Processing
727 811 ```bash
728 812 # Extract images/media from binary formats
746 -## 13. Defaults Files
830 +## 14. Defaults Files
748 832 Reusable YAML config files instead of long CLI commands:
777 -## 14. Common Agent Pipelines
861 +## 15. Common Agent Pipelines
779 863 ### Web Page → Clean Markdown
856 -## 15. Key CLI Options Reference
940 +## 16. Key CLI Options Reference
858 942 | Option | Effect |
859 943 |--------|--------|
895 -## 16. Exit Codes
979 +## 17. Exit Codes
897 981 | Code | Meaning |
898 982 |------|---------|
913 -## 17. Helper Scripts (Cross-Platform)
997 +## 18. Helper Scripts (Cross-Platform)
915 999 All scripts are written in Lua and run via `pandoc lua` — works on Linux, macOS, and Windows.
959 -## 18. Sandbox Mode
1043 +## 19. Sandbox Mode
961 1045 When processing untrusted input, use `--sandbox` to restrict file access:
978 -## 19. Troubleshooting
1062 +## 20. Troubleshooting
980 1064 ### `--shift-heading-level-by=-1` produces no headings

skills/super/brainstorming/SKILL.md

Added
new file mode 100644
1 +---
2 +name: brainstorming
3 +description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation."
4 +---
6 +# Brainstorming Ideas Into Designs
8 +Help turn ideas into fully formed designs and specs through natural collaborative dialogue.
10 +Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design and get user approval.
12 +<HARD-GATE>
13 +Do NOT invoke any implementation skill, write any code, scaffold any project, or take any implementation action until you have presented a design and the user has approved it. This applies to EVERY project regardless of perceived simplicity.
14 +</HARD-GATE>
16 +## Anti-Pattern: "This Is Too Simple To Need A Design"
18 +Every project goes through this process. A todo list, a single-function utility, a config change — all of them. "Simple" projects are where unexamined assumptions cause the most wasted work. The design can be short (a few sentences for truly simple projects), but you MUST present it and get approval.
20 +## Checklist
22 +You MUST create a task for each of these items and complete them in order:
24 +1. **Explore project context** — check files, docs, recent commits
25 +2. **Offer visual companion** (if topic will involve visual questions) — this is its own message, not combined with a clarifying question. See the Visual Companion section below.
26 +3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria
27 +4. **Propose 2-3 approaches** — with trade-offs and your recommendation
28 +5. **Present design** — in sections scaled to their complexity, get user approval after each section
29 +6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` and commit
30 +7. **Spec self-review** — check the spec for completeness and consistency before user review
31 +8. **User reviews written spec** — ask user to review the spec file before proceeding
32 +9. **Transition to planning** — invoke /skill:writing-roadmaps for large/multi-phase designs, otherwise invoke /skill:writing-plans
34 +## Process Flow
36 +```dot
37 +digraph brainstorming {
38 + "Explore project context" [shape=box];
39 + "Visual questions ahead?" [shape=diamond];
40 + "Offer Visual Companion\n(own message, no other content)" [shape=box];
41 + "Ask clarifying questions" [shape=box];
42 + "Propose 2-3 approaches" [shape=box];
43 + "Present design sections" [shape=box];
44 + "User approves design?" [shape=diamond];
45 + "Write design doc" [shape=box];
46 + "Spec self-review\n(fix inline)" [shape=box];
47 + "User reviews spec?" [shape=diamond];
48 + "Choose writing-roadmaps or writing-plans" [shape=doublecircle];
50 + "Explore project context" -> "Visual questions ahead?";
51 + "Visual questions ahead?" -> "Offer Visual Companion\n(own message, no other content)" [label="yes"];
52 + "Visual questions ahead?" -> "Ask clarifying questions" [label="no"];
53 + "Offer Visual Companion\n(own message, no other content)" -> "Ask clarifying questions";
54 + "Ask clarifying questions" -> "Propose 2-3 approaches";
55 + "Propose 2-3 approaches" -> "Present design sections";
56 + "Present design sections" -> "User approves design?";
57 + "User approves design?" -> "Present design sections" [label="no, revise"];
58 + "User approves design?" -> "Write design doc" [label="yes"];
59 + "Write design doc" -> "Spec self-review\n(fix inline)";
60 + "Spec self-review\n(fix inline)" -> "User reviews spec?";
61 + "User reviews spec?" -> "Write design doc" [label="changes requested"];
62 + "User reviews spec?" -> "Choose writing-roadmaps or writing-plans" [label="approved"];
64 +```
66 +**The terminal state is choosing the next planning skill.** For designs too large for one detailed implementation plan or context window, invoke /skill:writing-roadmaps. For designs that fit in one plan, invoke /skill:writing-plans. Do NOT invoke frontend-design, mcp-builder, or any other implementation skill.
68 +## The Process
70 +**Understanding the idea:**
72 +- Check out the current project state first (files, docs, recent commits)
73 +- Before asking detailed questions, assess scope: if the request describes multiple independent subsystems (e.g., "build a platform with chat, file storage, billing, and analytics"), flag this immediately. Don't spend questions refining details of a project that needs to be decomposed first.
74 +- If the project is too large for a single spec, help the user decompose into sub-projects: what are the independent pieces, how do they relate, what order should they be built? Then brainstorm the first sub-project through the normal design flow. Each sub-project gets its own spec → roadmap-or-plan → implementation cycle.
75 +- If the design fits in one spec but is too large for one detailed implementation plan or one context window, finish the design doc, then use /skill:writing-roadmaps to define ordered phases before any detailed plan.
76 +- For appropriately-scoped projects, ask questions one at a time to refine the idea
77 +- Prefer multiple choice questions when possible, but open-ended is fine too
78 +- Only one question per message - if a topic needs more exploration, break it into multiple questions
79 +- Focus on understanding: purpose, constraints, success criteria
81 +**Exploring approaches:**
83 +- Propose 2-3 different approaches with trade-offs
84 +- Present options conversationally with your recommendation and reasoning
85 +- Lead with your recommended option and explain why
87 +**Presenting the design:**
89 +- Once you believe you understand what you're building, present the design
90 +- Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced
91 +- Ask after each section whether it looks right so far
92 +- Cover: architecture, components, data flow, error handling, testing
93 +- Be ready to go back and clarify if something doesn't make sense
95 +**Design for isolation and clarity:**
97 +- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently
98 +- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on?
99 +- Can someone understand what a unit does without reading its internals? Can you change the internals without breaking consumers? If not, the boundaries need work.
100 +- Smaller, well-bounded units are also easier for you to work with - you reason better about code you can hold in context at once, and your edits are more reliable when files are focused. When a file grows large, that's often a signal that it's doing too much.
102 +**Working in existing codebases:**
104 +- Explore the current structure before proposing changes. Follow existing patterns.
105 +- Where existing code has problems that affect the work (e.g., a file that's grown too large, unclear boundaries, tangled responsibilities), include targeted improvements as part of the design - the way a good developer improves code they're working in.
106 +- Don't propose unrelated refactoring. Stay focused on what serves the current goal.
108 +## After the Design
110 +**Documentation:**
112 +- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`
113 + - (User preferences for spec location override this default)
114 +- Use elements-of-style:writing-clearly-and-concisely skill if available
115 +- Commit the design document to git
117 +**Spec Self-Review:**
118 +After writing the spec document, use the `push-task` tool with `spec-document-reviewer-prompt.md` to request a fresh-context spec review. Act on the returned task result when you get it, then look at the spec with fresh eyes:
120 +1. **Placeholder scan:** Any "TBD", "TODO", incomplete sections, or vague requirements? Fix them.
121 +2. **Internal consistency:** Do any sections contradict each other? Does the architecture match the feature descriptions?
122 +3. **Scope check:** Is this focused enough for a single implementation plan, or does it need decomposition?
123 +4. **Ambiguity check:** Could any requirement be interpreted two different ways? If so, pick one and make it explicit.
125 +Fix any issues inline. No need to re-review — just fix and move on.
127 +**User Review Gate:**
128 +After the spec review loop passes, ask the user to review the written spec before proceeding:
130 +> "Spec written and committed to `<path>`. Please review it and let me know if you want to make any changes before we choose the next planning step."
132 +Wait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves.
134 +**Implementation:**
136 +- If the design is large, multi-phase, or likely to exceed one context window as a detailed plan, invoke /skill:writing-roadmaps
137 +- Otherwise, invoke /skill:writing-plans to create a detailed implementation plan
138 +- Do NOT invoke any other skill. Roadmap/planning is the next step.
140 +## Key Principles
142 +- **One question at a time** - Don't overwhelm with multiple questions
143 +- **Multiple choice preferred** - Easier to answer than open-ended when possible
144 +- **YAGNI ruthlessly** - Remove unnecessary features from all designs
145 +- **Explore alternatives** - Always propose 2-3 approaches before settling
146 +- **Incremental validation** - Present design, get approval before moving on
147 +- **Be flexible** - Go back and clarify when something doesn't make sense
149 +## Visual Companion
151 +A browser-based companion for showing mockups, diagrams, and visual options during brainstorming. Available as a tool — not a mode. Accepting the companion means it's available for questions that benefit from visual treatment; it does NOT mean every question goes through the browser.
153 +**Offering the companion:** When you anticipate that upcoming questions will involve visual content (mockups, layouts, diagrams), offer it once for consent:
154 +> "Some of what we're working on might be easier to explain if I can show it to you in a web browser. I can put together mockups, diagrams, comparisons, and other visuals as we go. This feature is still new and can be token-intensive. Want to try it? (Requires opening a local URL)"
156 +**This offer MUST be its own message.** Do not combine it with clarifying questions, context summaries, or any other content. The message should contain ONLY the offer above and nothing else. Wait for the user's response before continuing. If they decline, proceed with text-only brainstorming.
158 +**Per-question decision:** Even after the user accepts, decide FOR EACH QUESTION whether to use the browser or the terminal. The test: **would the user understand this better by seeing it than reading it?**
160 +- **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs
161 +- **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions
163 +A question about a UI topic is not automatically a visual question. "What does personality mean in this context?" is a conceptual question — use the terminal. "Which wizard layout works better?" is a visual question — use the browser.
165 +If they agree to the companion, read the detailed guide before proceeding:
166 +`skills/brainstorming/visual-companion.md`

skills/super/brainstorming/scripts/frame-template.html

Added
new file mode 100644
1 +<!DOCTYPE html>
2 +<html>
3 +<head>
4 + <meta charset="utf-8">
5 + <title>Superpowers Brainstorming</title>
6 + <style>
7 + /*
8 + * BRAINSTORM COMPANION FRAME TEMPLATE
9 + *
10 + * This template provides a consistent frame with:
11 + * - OS-aware light/dark theming
12 + * - Fixed header and selection indicator bar
13 + * - Scrollable main content area
14 + * - CSS helpers for common UI patterns
15 + *
16 + * Content is injected via placeholder comment in #claude-content.
17 + */
19 + * { box-sizing: border-box; margin: 0; padding: 0; }
20 + html, body { height: 100%; overflow: hidden; }
22 + /* ===== THEME VARIABLES ===== */
23 + :root {
24 + --bg-primary: #f5f5f7;
25 + --bg-secondary: #ffffff;
26 + --bg-tertiary: #e5e5e7;
27 + --border: #d1d1d6;
28 + --text-primary: #1d1d1f;
29 + --text-secondary: #86868b;
30 + --text-tertiary: #aeaeb2;
31 + --accent: #0071e3;
32 + --accent-hover: #0077ed;
33 + --success: #34c759;
34 + --warning: #ff9f0a;
35 + --error: #ff3b30;
36 + --selected-bg: #e8f4fd;
37 + --selected-border: #0071e3;
38 + }
40 + @media (prefers-color-scheme: dark) {
41 + :root {
42 + --bg-primary: #1d1d1f;
43 + --bg-secondary: #2d2d2f;
44 + --bg-tertiary: #3d3d3f;
45 + --border: #424245;
46 + --text-primary: #f5f5f7;
47 + --text-secondary: #86868b;
48 + --text-tertiary: #636366;
49 + --accent: #0a84ff;
50 + --accent-hover: #409cff;
51 + --selected-bg: rgba(10, 132, 255, 0.15);
52 + --selected-border: #0a84ff;
53 + }
54 + }
56 + body {
57 + font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
58 + background: var(--bg-primary);
59 + color: var(--text-primary);
60 + display: flex;
61 + flex-direction: column;
62 + line-height: 1.5;
63 + }
65 + /* ===== FRAME STRUCTURE ===== */
66 + .header {
67 + background: var(--bg-secondary);
68 + padding: 0.5rem 1.5rem;
69 + display: flex;
70 + justify-content: space-between;
71 + align-items: center;
72 + border-bottom: 1px solid var(--border);
73 + flex-shrink: 0;
74 + }
75 + .header h1 { font-size: 0.85rem; font-weight: 500; color: var(--text-secondary); }
76 + .header .status { font-size: 0.7rem; color: var(--success); display: flex; align-items: center; gap: 0.4rem; }
77 + .header .status::before { content: ''; width: 6px; height: 6px; background: var(--success); border-radius: 50%; }
79 + .main { flex: 1; overflow-y: auto; }
80 + #claude-content { padding: 2rem; min-height: 100%; }
82 + .indicator-bar {
83 + background: var(--bg-secondary);
84 + border-top: 1px solid var(--border);
85 + padding: 0.5rem 1.5rem;
86 + flex-shrink: 0;
87 + text-align: center;
88 + }
89 + .indicator-bar span {
90 + font-size: 0.75rem;
91 + color: var(--text-secondary);
92 + }
93 + .indicator-bar .selected-text {
94 + color: var(--accent);
95 + font-weight: 500;
96 + }
98 + /* ===== TYPOGRAPHY ===== */
99 + h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
100 + h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
101 + .subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
102 + .section { margin-bottom: 2rem; }
103 + .label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
105 + /* ===== OPTIONS (for A/B/C choices) ===== */
106 + .options { display: flex; flex-direction: column; gap: 0.75rem; }
107 + .option {
108 + background: var(--bg-secondary);
109 + border: 2px solid var(--border);
110 + border-radius: 12px;
111 + padding: 1rem 1.25rem;
112 + cursor: pointer;
113 + transition: all 0.15s ease;
114 + display: flex;
115 + align-items: flex-start;
116 + gap: 1rem;
118 + .option:hover { border-color: var(--accent); }
119 + .option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
120 + .option .letter {
121 + background: var(--bg-tertiary);
122 + color: var(--text-secondary);
123 + width: 1.75rem; height: 1.75rem;
124 + border-radius: 6px;
125 + display: flex; align-items: center; justify-content: center;
126 + font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
128 + .option.selected .letter { background: var(--accent); color: white; }
129 + .option .content { flex: 1; }
130 + .option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
131 + .option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }
133 + /* ===== CARDS (for showing designs/mockups) ===== */
134 + .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
135 + .card {
136 + background: var(--bg-secondary);
137 + border: 1px solid var(--border);
138 + border-radius: 12px;
139 + overflow: hidden;
140 + cursor: pointer;
141 + transition: all 0.15s ease;
143 + .card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
144 + .card.selected { border-color: var(--selected-border); border-width: 2px; }
145 + .card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
146 + .card-body { padding: 1rem; }
147 + .card-body h3 { margin-bottom: 0.25rem; }
148 + .card-body p { color: var(--text-secondary); font-size: 0.85rem; }
150 + /* ===== MOCKUP CONTAINER ===== */
151 + .mockup {
152 + background: var(--bg-secondary);
153 + border: 1px solid var(--border);
154 + border-radius: 12px;
155 + overflow: hidden;
156 + margin-bottom: 1.5rem;
158 + .mockup-header {
159 + background: var(--bg-tertiary);
160 + padding: 0.5rem 1rem;
161 + font-size: 0.75rem;
162 + color: var(--text-secondary);
163 + border-bottom: 1px solid var(--border);
165 + .mockup-body { padding: 1.5rem; }
167 + /* ===== SPLIT VIEW (side-by-side comparison) ===== */
168 + .split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
169 + @media (max-width: 700px) { .split { grid-template-columns: 1fr; } }
171 + /* ===== PROS/CONS ===== */
172 + .pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
173 + .pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
174 + .pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
175 + .cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
176 + .pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
177 + .pros li, .cons li { margin-bottom: 0.25rem; }
179 + /* ===== PLACEHOLDER (for mockup areas) ===== */
180 + .placeholder {
181 + background: var(--bg-tertiary);
182 + border: 2px dashed var(--border);
183 + border-radius: 8px;
184 + padding: 2rem;
185 + text-align: center;
186 + color: var(--text-tertiary);
189 + /* ===== INLINE MOCKUP ELEMENTS ===== */
190 + .mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
191 + .mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
192 + .mock-content { padding: 1.5rem; flex: 1; }
193 + .mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
194 + .mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
195 + </style>
196 +</head>
197 +<body>
198 + <div class="header">
199 + <h1><a href="https://github.com/obra/superpowers" style="color: inherit; text-decoration: none;">Superpowers Brainstorming</a></h1>
200 + <div class="status">Connected</div>
201 + </div>
203 + <div class="main">
204 + <div id="claude-content">
205 + <!-- CONTENT -->
206 + </div>
207 + </div>
209 + <div class="indicator-bar">
210 + <span id="indicator-text">Click an option above, then return to the terminal</span>
211 + </div>
213 +</body>
214 +</html>

skills/super/brainstorming/scripts/helper.js

Added
new file mode 100644
1 +(function() {
2 + const WS_URL = 'ws://' + window.location.host;
3 + let ws = null;
4 + let eventQueue = [];
6 + function connect() {
7 + ws = new WebSocket(WS_URL);
9 + ws.onopen = () => {
10 + eventQueue.forEach(e => ws.send(JSON.stringify(e)));
11 + eventQueue = [];
12 + };
14 + ws.onmessage = (msg) => {
15 + const data = JSON.parse(msg.data);
16 + if (data.type === 'reload') {
17 + window.location.reload();
18 + }
19 + };
21 + ws.onclose = () => {
22 + setTimeout(connect, 1000);
23 + };
24 + }
26 + function sendEvent(event) {
27 + event.timestamp = Date.now();
28 + if (ws && ws.readyState === WebSocket.OPEN) {
29 + ws.send(JSON.stringify(event));
30 + } else {
31 + eventQueue.push(event);
32 + }
33 + }
35 + // Capture clicks on choice elements
36 + document.addEventListener('click', (e) => {
37 + const target = e.target.closest('[data-choice]');
38 + if (!target) return;
40 + sendEvent({
41 + type: 'click',
42 + text: target.textContent.trim(),
43 + choice: target.dataset.choice,
44 + id: target.id || null
45 + });
47 + // Update indicator bar (defer so toggleSelect runs first)
48 + setTimeout(() => {
49 + const indicator = document.getElementById('indicator-text');
50 + if (!indicator) return;
51 + const container = target.closest('.options') || target.closest('.cards');
52 + const selected = container ? container.querySelectorAll('.selected') : [];
53 + if (selected.length === 0) {
54 + indicator.textContent = 'Click an option above, then return to the terminal';
55 + } else if (selected.length === 1) {
56 + const label = selected[0].querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || selected[0].dataset.choice;
57 + indicator.innerHTML = '<span class="selected-text">' + label + ' selected</span> — return to terminal to continue';
58 + } else {
59 + indicator.innerHTML = '<span class="selected-text">' + selected.length + ' selected</span> — return to terminal to continue';
60 + }
61 + }, 0);
62 + });
64 + // Frame UI: selection tracking
65 + window.selectedChoice = null;
67 + window.toggleSelect = function(el) {
68 + const container = el.closest('.options') || el.closest('.cards');
69 + const multi = container && container.dataset.multiselect !== undefined;
70 + if (container && !multi) {
71 + container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected'));
72 + }
73 + if (multi) {
74 + el.classList.toggle('selected');
75 + } else {
76 + el.classList.add('selected');
77 + }
78 + window.selectedChoice = el.dataset.choice;
79 + };
81 + // Expose API for explicit use
82 + window.brainstorm = {
83 + send: sendEvent,
84 + choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })
85 + };
87 + connect();
88 +})();

skills/super/brainstorming/scripts/server.cjs

Added
new file mode 100644
1 +const crypto = require('crypto');
2 +const http = require('http');
3 +const fs = require('fs');
4 +const path = require('path');
6 +// ========== WebSocket Protocol (RFC 6455) ==========
8 +const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
9 +const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
11 +function computeAcceptKey(clientKey) {
12 + return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
15 +function encodeFrame(opcode, payload) {
16 + const fin = 0x80;
17 + const len = payload.length;
18 + let header;
20 + if (len < 126) {
21 + header = Buffer.alloc(2);
22 + header[0] = fin | opcode;
23 + header[1] = len;
24 + } else if (len < 65536) {
25 + header = Buffer.alloc(4);
26 + header[0] = fin | opcode;
27 + header[1] = 126;
28 + header.writeUInt16BE(len, 2);
29 + } else {
30 + header = Buffer.alloc(10);
31 + header[0] = fin | opcode;
32 + header[1] = 127;
33 + header.writeBigUInt64BE(BigInt(len), 2);
34 + }
36 + return Buffer.concat([header, payload]);
39 +function decodeFrame(buffer) {
40 + if (buffer.length < 2) return null;
42 + const secondByte = buffer[1];
43 + const opcode = buffer[0] & 0x0F;
44 + const masked = (secondByte & 0x80) !== 0;
45 + let payloadLen = secondByte & 0x7F;
46 + let offset = 2;
48 + if (!masked) throw new Error('Client frames must be masked');
50 + if (payloadLen === 126) {
51 + if (buffer.length < 4) return null;
52 + payloadLen = buffer.readUInt16BE(2);
53 + offset = 4;
54 + } else if (payloadLen === 127) {
55 + if (buffer.length < 10) return null;
56 + payloadLen = Number(buffer.readBigUInt64BE(2));
57 + offset = 10;
58 + }
60 + const maskOffset = offset;
61 + const dataOffset = offset + 4;
62 + const totalLen = dataOffset + payloadLen;
63 + if (buffer.length < totalLen) return null;
65 + const mask = buffer.slice(maskOffset, dataOffset);
66 + const data = Buffer.alloc(payloadLen);
67 + for (let i = 0; i < payloadLen; i++) {
68 + data[i] = buffer[dataOffset + i] ^ mask[i % 4];
69 + }
71 + return { opcode, payload: data, bytesConsumed: totalLen };
74 +// ========== Configuration ==========
76 +const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
77 +const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
78 +const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
79 +const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
80 +const CONTENT_DIR = path.join(SESSION_DIR, 'content');
81 +const STATE_DIR = path.join(SESSION_DIR, 'state');
82 +let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
84 +const MIME_TYPES = {
85 + '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
86 + '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
87 + '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
88 +};
90 +// ========== Templates and Constants ==========
92 +const WAITING_PAGE = `<!DOCTYPE html>
93 +<html>
94 +<head><meta charset="utf-8"><title>Brainstorm Companion</title>
95 +<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
96 +h1 { color: #333; } p { color: #666; }</style>
97 +</head>
98 +<body><h1>Brainstorm Companion</h1>
99 +<p>Waiting for the agent to push a screen...</p></body></html>`;
101 +const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
102 +const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
103 +const helperInjection = '<script>\n' + helperScript + '\n</script>';
105 +// ========== Helper Functions ==========
107 +function isFullDocument(html) {
108 + const trimmed = html.trimStart().toLowerCase();
109 + return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
112 +function wrapInFrame(content) {
113 + return frameTemplate.replace('<!-- CONTENT -->', content);
116 +function getNewestScreen() {
117 + const files = fs.readdirSync(CONTENT_DIR)
118 + .filter(f => f.endsWith('.html'))
119 + .map(f => {
120 + const fp = path.join(CONTENT_DIR, f);
121 + return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
122 + })
123 + .sort((a, b) => b.mtime - a.mtime);
124 + return files.length > 0 ? files[0].path : null;
127 +// ========== HTTP Request Handler ==========
129 +function handleRequest(req, res) {
130 + touchActivity();
131 + if (req.method === 'GET' && req.url === '/') {
132 + const screenFile = getNewestScreen();
133 + let html = screenFile
134 + ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
135 + : WAITING_PAGE;
137 + if (html.includes('</body>')) {
138 + html = html.replace('</body>', helperInjection + '\n</body>');
139 + } else {
140 + html += helperInjection;
143 + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
144 + res.end(html);
145 + } else if (req.method === 'GET' && req.url.startsWith('/files/')) {
146 + const fileName = req.url.slice(7);
147 + const filePath = path.join(CONTENT_DIR, path.basename(fileName));
148 + if (!fs.existsSync(filePath)) {
149 + res.writeHead(404);
150 + res.end('Not found');
151 + return;
153 + const ext = path.extname(filePath).toLowerCase();
154 + const contentType = MIME_TYPES[ext] || 'application/octet-stream';
155 + res.writeHead(200, { 'Content-Type': contentType });
156 + res.end(fs.readFileSync(filePath));
157 + } else {
158 + res.writeHead(404);
159 + res.end('Not found');
163 +// ========== WebSocket Connection Handling ==========
165 +const clients = new Set();
167 +function handleUpgrade(req, socket) {
168 + const key = req.headers['sec-websocket-key'];
169 + if (!key) { socket.destroy(); return; }
171 + const accept = computeAcceptKey(key);
172 + socket.write(
173 + 'HTTP/1.1 101 Switching Protocols\r\n' +
174 + 'Upgrade: websocket\r\n' +
175 + 'Connection: Upgrade\r\n' +
176 + 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
177 + );
179 + let buffer = Buffer.alloc(0);
180 + clients.add(socket);
182 + socket.on('data', (chunk) => {
183 + buffer = Buffer.concat([buffer, chunk]);
184 + while (buffer.length > 0) {
185 + let result;
186 + try {
187 + result = decodeFrame(buffer);
188 + } catch (e) {
189 + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
190 + clients.delete(socket);
191 + return;
193 + if (!result) break;
194 + buffer = buffer.slice(result.bytesConsumed);
196 + switch (result.opcode) {
197 + case OPCODES.TEXT:
198 + handleMessage(result.payload.toString());
199 + break;
200 + case OPCODES.CLOSE:
201 + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
202 + clients.delete(socket);
203 + return;
204 + case OPCODES.PING:
205 + socket.write(encodeFrame(OPCODES.PONG, result.payload));
206 + break;
207 + case OPCODES.PONG:
208 + break;
209 + default: {
210 + const closeBuf = Buffer.alloc(2);
211 + closeBuf.writeUInt16BE(1003);
212 + socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
213 + clients.delete(socket);
214 + return;
218 + });
220 + socket.on('close', () => clients.delete(socket));
221 + socket.on('error', () => clients.delete(socket));
224 +function handleMessage(text) {
225 + let event;
226 + try {
227 + event = JSON.parse(text);
228 + } catch (e) {
229 + console.error('Failed to parse WebSocket message:', e.message);
230 + return;
232 + touchActivity();
233 + console.log(JSON.stringify({ source: 'user-event', ...event }));
234 + if (event.choice) {
235 + const eventsFile = path.join(STATE_DIR, 'events');
236 + fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
240 +function broadcast(msg) {
241 + const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
242 + for (const socket of clients) {
243 + try { socket.write(frame); } catch (e) { clients.delete(socket); }
247 +// ========== Activity Tracking ==========
249 +const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
250 +let lastActivity = Date.now();
252 +function touchActivity() {
253 + lastActivity = Date.now();
256 +// ========== File Watching ==========
258 +const debounceTimers = new Map();
260 +// ========== Server Startup ==========
262 +function startServer() {
263 + if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
264 + if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
266 + // Track known files to distinguish new screens from updates.
267 + // macOS fs.watch reports 'rename' for both new files and overwrites,
268 + // so we can't rely on eventType alone.
269 + const knownFiles = new Set(
270 + fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html'))
271 + );
273 + const server = http.createServer(handleRequest);
274 + server.on('upgrade', handleUpgrade);
276 + const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
277 + if (!filename || !filename.endsWith('.html')) return;
279 + if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
280 + debounceTimers.set(filename, setTimeout(() => {
281 + debounceTimers.delete(filename);
282 + const filePath = path.join(CONTENT_DIR, filename);
284 + if (!fs.existsSync(filePath)) return; // file was deleted
285 + touchActivity();
287 + if (!knownFiles.has(filename)) {
288 + knownFiles.add(filename);
289 + const eventsFile = path.join(STATE_DIR, 'events');
290 + if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
291 + console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
292 + } else {
293 + console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
296 + broadcast({ type: 'reload' });
297 + }, 100));
298 + });
299 + watcher.on('error', (err) => console.error('fs.watch error:', err.message));
301 + function shutdown(reason) {
302 + console.log(JSON.stringify({ type: 'server-stopped', reason }));
303 + const infoFile = path.join(STATE_DIR, 'server-info');
304 + if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
305 + fs.writeFileSync(
306 + path.join(STATE_DIR, 'server-stopped'),
307 + JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
308 + );
309 + watcher.close();
310 + clearInterval(lifecycleCheck);
311 + server.close(() => process.exit(0));
314 + function ownerAlive() {
315 + if (!ownerPid) return true;
316 + try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
319 + // Check every 60s: exit if owner process died or idle for 30 minutes
320 + const lifecycleCheck = setInterval(() => {
321 + if (!ownerAlive()) shutdown('owner process exited');
322 + else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
323 + }, 60 * 1000);
324 + lifecycleCheck.unref();
326 + // Validate owner PID at startup. If it's already dead, the PID resolution
327 + // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
328 + // Disable monitoring and rely on the idle timeout instead.
329 + if (ownerPid) {
330 + try { process.kill(ownerPid, 0); }
331 + catch (e) {
332 + if (e.code !== 'EPERM') {
333 + console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
334 + ownerPid = null;
339 + server.listen(PORT, HOST, () => {
340 + const info = JSON.stringify({
341 + type: 'server-started', port: Number(PORT), host: HOST,
342 + url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
343 + screen_dir: CONTENT_DIR, state_dir: STATE_DIR
344 + });
345 + console.log(info);
346 + fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n');
347 + });
350 +if (require.main === module) {
351 + startServer();
354 +module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };

skills/super/brainstorming/scripts/start-server.sh

Added
new file mode 100755
1 +#!/usr/bin/env bash
2 +# Start the brainstorm server and output connection info
3 +# Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background]
4 +#
5 +# Starts server on a random high port, outputs JSON with URL.
6 +# Each session gets its own directory to avoid conflicts.
7 +#
8 +# Options:
9 +# --project-dir <path> Store session files under <path>/.superpowers/brainstorm/
10 +# instead of /tmp. Files persist after server stops.
11 +# --host <bind-host> Host/interface to bind (default: 127.0.0.1).
12 +# Use 0.0.0.0 in remote/containerized environments.
13 +# --url-host <host> Hostname shown in returned URL JSON.
14 +# --foreground Run server in the current terminal (no backgrounding).
15 +# --background Force background mode (overrides Codex auto-foreground).
17 +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
19 +# Parse arguments
20 +PROJECT_DIR=""
21 +FOREGROUND="false"
22 +FORCE_BACKGROUND="false"
23 +BIND_HOST="127.0.0.1"
24 +URL_HOST=""
25 +while [[ $# -gt 0 ]]; do
26 + case "$1" in
27 + --project-dir)
28 + PROJECT_DIR="$2"
29 + shift 2
30 + ;;
31 + --host)
32 + BIND_HOST="$2"
33 + shift 2
34 + ;;
35 + --url-host)
36 + URL_HOST="$2"
37 + shift 2
38 + ;;
39 + --foreground|--no-daemon)
40 + FOREGROUND="true"
41 + shift
42 + ;;
43 + --background|--daemon)
44 + FORCE_BACKGROUND="true"
45 + shift
46 + ;;
47 + *)
48 + echo "{\"error\": \"Unknown argument: $1\"}"
49 + exit 1
50 + ;;
51 + esac
52 +done
54 +if [[ -z "$URL_HOST" ]]; then
55 + if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then
56 + URL_HOST="localhost"
57 + else
58 + URL_HOST="$BIND_HOST"
59 + fi
60 +fi
62 +# Some environments reap detached/background processes. Auto-foreground when detected.
63 +if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
64 + FOREGROUND="true"
65 +fi
67 +# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected.
68 +if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
69 + case "${OSTYPE:-}" in
70 + msys*|cygwin*|mingw*) FOREGROUND="true" ;;
71 + esac
72 + if [[ -n "${MSYSTEM:-}" ]]; then
73 + FOREGROUND="true"
74 + fi
75 +fi
77 +# Generate unique session directory
78 +SESSION_ID="$$-$(date +%s)"
80 +if [[ -n "$PROJECT_DIR" ]]; then
81 + SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}"
82 +else
83 + SESSION_DIR="/tmp/brainstorm-${SESSION_ID}"
84 +fi
86 +STATE_DIR="${SESSION_DIR}/state"
87 +PID_FILE="${STATE_DIR}/server.pid"
88 +LOG_FILE="${STATE_DIR}/server.log"
90 +# Create fresh session directory with content and state peers
91 +mkdir -p "${SESSION_DIR}/content" "$STATE_DIR"
93 +# Kill any existing server
94 +if [[ -f "$PID_FILE" ]]; then
95 + old_pid=$(cat "$PID_FILE")
96 + kill "$old_pid" 2>/dev/null
97 + rm -f "$PID_FILE"
98 +fi
100 +cd "$SCRIPT_DIR"
102 +# Resolve the harness PID (grandparent of this script).
103 +# $PPID is the ephemeral shell the harness spawned to run us — it dies
104 +# when this script exits. The harness itself is $PPID's parent.
105 +OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')"
106 +if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then
107 + OWNER_PID="$PPID"
110 +# Foreground mode for environments that reap detached/background processes.
111 +if [[ "$FOREGROUND" == "true" ]]; then
112 + echo "$$" > "$PID_FILE"
113 + env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs
114 + exit $?
117 +# Start server, capturing output to log file
118 +# Use nohup to survive shell exit; disown to remove from job table
119 +nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs > "$LOG_FILE" 2>&1 &
120 +SERVER_PID=$!
121 +disown "$SERVER_PID" 2>/dev/null
122 +echo "$SERVER_PID" > "$PID_FILE"
124 +# Wait for server-started message (check log file)
125 +for i in {1..50}; do
126 + if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then
127 + # Verify server is still alive after a short window (catches process reapers)
128 + alive="true"
129 + for _ in {1..20}; do
130 + if ! kill -0 "$SERVER_PID" 2>/dev/null; then
131 + alive="false"
132 + break
133 + fi
134 + sleep 0.1
135 + done
136 + if [[ "$alive" != "true" ]]; then
137 + echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}"
138 + exit 1
139 + fi
140 + grep "server-started" "$LOG_FILE" | head -1
141 + exit 0
142 + fi
143 + sleep 0.1
144 +done
146 +# Timeout - server didn't start
147 +echo '{"error": "Server failed to start within 5 seconds"}'
148 +exit 1

skills/super/brainstorming/scripts/stop-server.sh

Added
new file mode 100755
1 +#!/usr/bin/env bash
2 +# Stop the brainstorm server and clean up
3 +# Usage: stop-server.sh <session_dir>
4 +#
5 +# Kills the server process. Only deletes session directory if it's
6 +# under /tmp (ephemeral). Persistent directories (.superpowers/) are
7 +# kept so mockups can be reviewed later.
9 +SESSION_DIR="$1"
11 +if [[ -z "$SESSION_DIR" ]]; then
12 + echo '{"error": "Usage: stop-server.sh <session_dir>"}'
13 + exit 1
14 +fi
16 +STATE_DIR="${SESSION_DIR}/state"
17 +PID_FILE="${STATE_DIR}/server.pid"
19 +if [[ -f "$PID_FILE" ]]; then
20 + pid=$(cat "$PID_FILE")
22 + # Try to stop gracefully, fallback to force if still alive
23 + kill "$pid" 2>/dev/null || true
25 + # Wait for graceful shutdown (up to ~2s)
26 + for i in {1..20}; do
27 + if ! kill -0 "$pid" 2>/dev/null; then
28 + break
29 + fi
30 + sleep 0.1
31 + done
33 + # If still running, escalate to SIGKILL
34 + if kill -0 "$pid" 2>/dev/null; then
35 + kill -9 "$pid" 2>/dev/null || true
37 + # Give SIGKILL a moment to take effect
38 + sleep 0.1
39 + fi
41 + if kill -0 "$pid" 2>/dev/null; then
42 + echo '{"status": "failed", "error": "process still running"}'
43 + exit 1
44 + fi
46 + rm -f "$PID_FILE" "${STATE_DIR}/server.log"
48 + # Only delete ephemeral /tmp directories
49 + if [[ "$SESSION_DIR" == /tmp/* ]]; then
50 + rm -rf "$SESSION_DIR"
51 + fi
53 + echo '{"status": "stopped"}'
54 +else
55 + echo '{"status": "not_running"}'
56 +fi

skills/super/brainstorming/spec-document-reviewer-prompt.md

Added
new file mode 100644
1 +# Spec Document Reviewer Prompt Template
3 +Use this template when dispatching a spec document reviewer task.
5 +**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.
7 +**Dispatch after:** Spec document is written to docs/superpowers/specs/
9 +```
10 +push-task:
11 + prompt: |
12 + You are a spec document reviewer. Verify this spec is complete and ready for planning.
14 + **Spec to review:** [SPEC_FILE_PATH]
16 + ## What to Check
18 + | Category | What to Look For |
19 + |----------|------------------|
20 + | Completeness | TODOs, placeholders, "TBD", incomplete sections |
21 + | Consistency | Internal contradictions, conflicting requirements |
22 + | Clarity | Requirements ambiguous enough to cause someone to build the wrong thing |
23 + | Scope | Focused enough for a single plan — not covering multiple independent subsystems |
24 + | YAGNI | Unrequested features, over-engineering |
26 + ## Calibration
28 + **Only flag issues that would cause real problems during implementation planning.**
29 + A missing section, a contradiction, or a requirement so ambiguous it could be
30 + interpreted two different ways — those are issues. Minor wording improvements,
31 + stylistic preferences, and "sections less detailed than others" are not.
33 + Approve unless there are serious gaps that would lead to a flawed plan.
35 + ## Output Format
37 + ## Spec Review
39 + **Status:** Approved | Issues Found
41 + **Issues (if any):**
42 + - [Section X]: [specific issue] - [why it matters for planning]
44 + **Recommendations (advisory, do not block approval):**
45 + - [suggestions for improvement]
46 +```
48 +**Reviewer returns:** Status, Issues (if any), Recommendations

skills/super/brainstorming/visual-companion.md

Added
new file mode 100644
1 +# Visual Companion Guide
3 +Browser-based visual brainstorming companion for showing mockups, diagrams, and options.
5 +## When to Use
7 +Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?**
9 +**Use the browser** when the content itself is visual:
11 +- **UI mockups** — wireframes, layouts, navigation structures, component designs
12 +- **Architecture diagrams** — system components, data flow, relationship maps
13 +- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions
14 +- **Design polish** — when the question is about look and feel, spacing, visual hierarchy
15 +- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams
17 +**Use the terminal** when the content is text or tabular:
19 +- **Requirements and scope questions** — "what does X mean?", "which features are in scope?"
20 +- **Conceptual A/B/C choices** — picking between approaches described in words
21 +- **Tradeoff lists** — pros/cons, comparison tables
22 +- **Technical decisions** — API design, data modeling, architectural approach selection
23 +- **Clarifying questions** — anything where the answer is words, not a visual preference
25 +A question *about* a UI topic is not automatically a visual question. "What kind of wizard do you want?" is conceptual — use the terminal. "Which of these wizard layouts feels right?" is visual — use the browser.
27 +## How It Works
29 +The server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn.
31 +**Content fragments vs full documents:** If your HTML file starts with `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, selection indicator, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.
33 +## Starting a Session
35 +```bash
36 +# Start server with persistence (mockups saved to project)
37 +scripts/start-server.sh --project-dir /path/to/project
39 +# Returns: {"type":"server-started","port":52341,"url":"http://localhost:52341",
40 +# "screen_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/content",
41 +# "state_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/state"}
42 +```
44 +Save `screen_dir` and `state_dir` from the response. Tell user to open the URL.
46 +**Finding connection info:** The server writes its startup JSON to `$STATE_DIR/server-info`. If you launched the server in the background and didn't capture stdout, read that file to get the URL and port. When using `--project-dir`, check `<project>/.superpowers/brainstorm/` for the session directory.
48 +**Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there.
50 +**Launching the server by platform:**
52 +**Pi (macOS / Linux):**
53 +```bash
54 +# Default mode works — the script backgrounds the server itself
55 +scripts/start-server.sh --project-dir /path/to/project
56 +```
58 +**Pi (Windows):**
59 +```bash
60 +# Windows auto-detects and uses foreground mode, which blocks the tool call.
61 +# Use run_in_background: true on the Bash tool call so the server survives
62 +# across conversation turns.
63 +scripts/start-server.sh --project-dir /path/to/project
64 +```
65 +When calling this via the Bash tool, set `run_in_background: true`. Then read `$STATE_DIR/server-info` on the next turn to get the URL and port.
67 +**Codex:**
68 +```bash
69 +# Codex reaps background processes. The script auto-detects CODEX_CI and
70 +# switches to foreground mode. Run it normally — no extra flags needed.
71 +scripts/start-server.sh --project-dir /path/to/project
72 +```
74 +**Gemini CLI:**
75 +```bash
76 +# Use --foreground and set is_background: true on your shell tool call
77 +# so the process survives across turns
78 +scripts/start-server.sh --project-dir /path/to/project --foreground
79 +```
81 +**Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism.
83 +If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host:
85 +```bash
86 +scripts/start-server.sh \
87 + --project-dir /path/to/project \
88 + --host 0.0.0.0 \
89 + --url-host localhost
90 +```
92 +Use `--url-host` to control what hostname is printed in the returned URL JSON.
94 +## The Loop
96 +1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`:
97 + - Before each write, check that `$STATE_DIR/server-info` exists. If it doesn't (or `$STATE_DIR/server-stopped` exists), the server has shut down — restart it with `start-server.sh` before continuing. The server auto-exits after 30 minutes of inactivity.
98 + - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`
99 + - **Never reuse filenames** — each screen gets a fresh file
100 + - Use Write tool — **never use cat/heredoc** (dumps noise into terminal)
101 + - Server automatically serves the newest file
103 +2. **Tell user what to expect and end your turn:**
104 + - Remind them of the URL (every step, not just first)
105 + - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage")
106 + - Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like."
108 +3. **On your next turn** — after the user responds in the terminal:
109 + - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines
110 + - Merge with the user's terminal text to get the full picture
111 + - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data
113 +4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated.
115 +5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content:
117 + ```html
118 + <!-- filename: waiting.html (or waiting-2.html, etc.) -->
119 + <div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
120 + <p class="subtitle">Continuing in terminal...</p>
121 + </div>
122 + ```
124 + This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual.
126 +6. Repeat until done.
128 +## Writing Content Fragments
130 +Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, selection indicator, and all interactive infrastructure).
132 +**Minimal example:**
134 +```html
135 +<h2>Which layout works better?</h2>
136 +<p class="subtitle">Consider readability and visual hierarchy</p>
138 +<div class="options">
139 + <div class="option" data-choice="a" onclick="toggleSelect(this)">
140 + <div class="letter">A</div>
141 + <div class="content">
142 + <h3>Single Column</h3>
143 + <p>Clean, focused reading experience</p>
144 + </div>
145 + </div>
146 + <div class="option" data-choice="b" onclick="toggleSelect(this)">
147 + <div class="letter">B</div>
148 + <div class="content">
149 + <h3>Two Column</h3>
150 + <p>Sidebar navigation with main content</p>
151 + </div>
152 + </div>
153 +</div>
154 +```
156 +That's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.
158 +## CSS Classes Available
160 +The frame template provides these CSS classes for your content:
162 +### Options (A/B/C choices)
164 +```html
165 +<div class="options">
166 + <div class="option" data-choice="a" onclick="toggleSelect(this)">
167 + <div class="letter">A</div>
168 + <div class="content">
169 + <h3>Title</h3>
170 + <p>Description</p>
171 + </div>
172 + </div>
173 +</div>
174 +```
176 +**Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item. The indicator bar shows the count.
178 +```html
179 +<div class="options" data-multiselect>
180 + <!-- same option markup — users can select/deselect multiple -->
181 +</div>
182 +```
184 +### Cards (visual designs)
186 +```html
187 +<div class="cards">
188 + <div class="card" data-choice="design1" onclick="toggleSelect(this)">
189 + <div class="card-image"><!-- mockup content --></div>
190 + <div class="card-body">
191 + <h3>Name</h3>
192 + <p>Description</p>
193 + </div>
194 + </div>
195 +</div>
196 +```
198 +### Mockup container
200 +```html
201 +<div class="mockup">
202 + <div class="mockup-header">Preview: Dashboard Layout</div>
203 + <div class="mockup-body"><!-- your mockup HTML --></div>
204 +</div>
205 +```
207 +### Split view (side-by-side)
209 +```html
210 +<div class="split">
211 + <div class="mockup"><!-- left --></div>
212 + <div class="mockup"><!-- right --></div>
213 +</div>
214 +```
216 +### Pros/Cons
218 +```html
219 +<div class="pros-cons">
220 + <div class="pros"><h4>Pros</h4><ul><li>Benefit</li></ul></div>
221 + <div class="cons"><h4>Cons</h4><ul><li>Drawback</li></ul></div>
222 +</div>
223 +```
225 +### Mock elements (wireframe building blocks)
227 +```html
228 +<div class="mock-nav">Logo | Home | About | Contact</div>
229 +<div style="display: flex;">
230 + <div class="mock-sidebar">Navigation</div>
231 + <div class="mock-content">Main content area</div>
232 +</div>
233 +<button class="mock-button">Action Button</button>
234 +<input class="mock-input" placeholder="Input field">
235 +<div class="placeholder">Placeholder area</div>
236 +```
238 +### Typography and sections
240 +- `h2` — page title
241 +- `h3` — section heading
242 +- `.subtitle` — secondary text below title
243 +- `.section` — content block with bottom margin
244 +- `.label` — small uppercase label text
246 +## Browser Events Format
248 +When the user clicks options in the browser, their interactions are recorded to `$STATE_DIR/events` (one JSON object per line). The file is cleared automatically when you push a new screen.
250 +```jsonl
251 +{"type":"click","choice":"a","text":"Option A - Simple Layout","timestamp":1706000101}
252 +{"type":"click","choice":"c","text":"Option C - Complex Grid","timestamp":1706000108}
253 +{"type":"click","choice":"b","text":"Option B - Hybrid","timestamp":1706000115}
254 +```
256 +The full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about.
258 +If `$STATE_DIR/events` doesn't exist, the user didn't interact with the browser — use only their terminal text.
260 +## Design Tips
262 +- **Scale fidelity to the question** — wireframes for layout, polish for polish questions
263 +- **Explain the question on each page** — "Which layout feels more professional?" not just "Pick one"
264 +- **Iterate before advancing** — if feedback changes current screen, write a new version
265 +- **2-4 options max** per screen
266 +- **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.
267 +- **Keep mockups simple** — focus on layout and structure, not pixel-perfect design
269 +## File Naming
271 +- Use semantic names: `platform.html`, `visual-style.html`, `layout.html`
272 +- Never reuse filenames — each screen must be a new file
273 +- For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`
274 +- Server serves newest file by modification time
276 +## Cleaning Up
278 +```bash
279 +scripts/stop-server.sh $SESSION_DIR
280 +```
282 +If the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.
284 +## Reference
286 +- Frame template (CSS reference): `scripts/frame-template.html`
287 +- Helper script (client-side): `scripts/helper.js`

skills/super/executing-plans/SKILL.md

Added
new file mode 100644
1 +---
2 +name: executing-plans
3 +description: Use when you have a written implementation plan to execute in a separate session with review checkpoints
4 +---
6 +# Executing Plans
8 +## Overview
10 +Load plan, review critically, execute all tasks, report when complete.
12 +**Announce at start:** "I'm using the executing-plans skill to implement this plan."
15 +## The Process
17 +### Step 1: Load and Review Plan
18 +1. Read plan file
19 +2. Review critically - identify any questions or concerns about the plan
20 +3. If concerns: Raise them with your human partner before starting
21 +4. If no concerns: Create a todo list and proceed
23 +### Step 2: Execute Tasks
25 +For each task:
26 +1. Mark as in_progress
27 +2. Follow each step exactly (plan has bite-sized steps)
28 +3. Run verifications as specified
29 +4. Mark as completed
31 +### Step 3: Complete Development
33 +After all tasks complete and verified:
34 +- Announce: "I'm using the finishing-a-development-branch skill to complete this work."
35 +- **REQUIRED SUB-SKILL:** Use /skill:finishing-a-development-branch
36 +- Follow that skill to verify tests, present options, execute choice
38 +## When to Stop and Ask for Help
40 +**STOP executing immediately when:**
41 +- Hit a blocker (missing dependency, test fails, instruction unclear)
42 +- Plan has critical gaps preventing starting
43 +- You don't understand an instruction
44 +- Verification fails repeatedly
46 +**Ask for clarification rather than guessing.**
48 +## When to Revisit Earlier Steps
50 +**Return to Review (Step 1) when:**
51 +- Partner updates the plan based on your feedback
52 +- Fundamental approach needs rethinking
54 +**Don't force through blockers** - stop and ask.
56 +## Remember
57 +- Review plan critically first
58 +- Follow plan steps exactly
59 +- Don't skip verifications
60 +- Reference skills when plan says to
61 +- Stop when blocked, don't guess
62 +- Never start implementation on main/master branch without explicit user consent
64 +## Integration
66 +**Required workflow skills:**
67 +- **/skill:writing-plans** - Creates the plan this skill executes
68 +- **/skill:finishing-a-development-branch** - Complete development after all tasks

skills/super/finishing-a-development-branch/SKILL.md

Added
new file mode 100644
1 +---
2 +name: finishing-a-development-branch
3 +description: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup
4 +---
6 +# Finishing a Development Branch
8 +## Overview
10 +Guide completion of development work by presenting clear options and handling chosen workflow.
12 +**Core principle:** Verify tests → Detect environment → Present options → Execute choice → Clean up.
14 +**Announce at start:** "I'm using the finishing-a-development-branch skill to complete this work."
16 +## The Process
18 +### Step 1: Verify Tests
20 +**Before presenting options, verify tests pass:**
22 +```bash
23 +# Run project's test suite
24 +npm test / cargo test / pytest / go test ./...
25 +```
27 +**If tests fail:**
28 +```
29 +Tests failing (<N> failures). Must fix before completing:
31 +[Show failures]
33 +Cannot proceed with merge/PR until tests pass.
34 +```
36 +Stop. Don't proceed to Step 2.
38 +**If tests pass:** Continue to Step 2.
40 +### Step 2: Detect Environment
42 +**Determine workspace state before presenting options:**
44 +```bash
45 +GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
46 +GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
47 +```
49 +This determines which menu to show and how cleanup works:
51 +| State | Menu | Cleanup |
52 +|-------|------|---------|
53 +| `GIT_DIR == GIT_COMMON` (normal repo) | Standard 4 options | No worktree to clean up |
54 +| `GIT_DIR != GIT_COMMON`, named branch | Standard 4 options | Provenance-based (see Step 6) |
55 +| `GIT_DIR != GIT_COMMON`, detached HEAD | Reduced 3 options (no merge) | No cleanup (externally managed) |
57 +### Step 3: Determine Base Branch
59 +```bash
60 +# Try common base branches
61 +git merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null
62 +```
64 +Or ask: "This branch split from main - is that correct?"
66 +### Step 4: Present Options
68 +**Normal repo and named-branch worktree — present exactly these 4 options:**
70 +```
71 +Implementation complete. What would you like to do?
73 +1. Merge back to <base-branch> locally
74 +2. Push and create a Pull Request
75 +3. Keep the branch as-is (I'll handle it later)
76 +4. Discard this work
78 +Which option?
79 +```
81 +**Detached HEAD — present exactly these 3 options:**
83 +```
84 +Implementation complete. You're on a detached HEAD (externally managed workspace).
86 +1. Push as new branch and create a Pull Request
87 +2. Keep as-is (I'll handle it later)
88 +3. Discard this work
90 +Which option?
91 +```
93 +**Don't add explanation** - keep options concise.
95 +### Step 5: Execute Choice
97 +#### Option 1: Merge Locally
99 +```bash
100 +# Get main repo root for CWD safety
101 +MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
102 +cd "$MAIN_ROOT"
104 +# Merge first — verify success before removing anything
105 +git checkout <base-branch>
106 +git pull
107 +git merge <feature-branch>
109 +# Verify tests on merged result
110 +<test command>
112 +# Only after merge succeeds: cleanup worktree (Step 6), then delete branch
113 +```
115 +Then: Cleanup worktree (Step 6), then delete branch:
117 +```bash
118 +git branch -d <feature-branch>
119 +```
121 +#### Option 2: Push and Create PR
123 +```bash
124 +# Push branch
125 +git push -u origin <feature-branch>
127 +# Create PR
128 +gh pr create --title "<title>" --body "$(cat <<'EOF'
129 +## Summary
130 +<2-3 bullets of what changed>
132 +## Test Plan
133 +- [ ] <verification steps>
134 +EOF
136 +```
138 +**Do NOT clean up worktree** — user needs it alive to iterate on PR feedback.
140 +#### Option 3: Keep As-Is
142 +Report: "Keeping branch <name>. Worktree preserved at <path>."
144 +**Don't cleanup worktree.**
146 +#### Option 4: Discard
148 +**Confirm first:**
149 +```
150 +This will permanently delete:
151 +- Branch <name>
152 +- All commits: <commit-list>
153 +- Worktree at <path>
155 +Type 'discard' to confirm.
156 +```
158 +Wait for exact confirmation.
160 +If confirmed:
161 +```bash
162 +MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
163 +cd "$MAIN_ROOT"
164 +```
166 +Then: Cleanup worktree (Step 6), then force-delete branch:
167 +```bash
168 +git branch -D <feature-branch>
169 +```
171 +### Step 6: Cleanup Workspace
173 +**Only runs for Options 1 and 4.** Options 2 and 3 always preserve the worktree.
175 +```bash
176 +GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
177 +GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
178 +WORKTREE_PATH=$(git rev-parse --show-toplevel)
179 +```
181 +**If `GIT_DIR == GIT_COMMON`:** Normal repo, no worktree to clean up. Done.
183 +**If worktree path is under `.worktrees/`, `worktrees/`, or `~/.config/superpowers/worktrees/`:** Superpowers created this worktree — we own cleanup.
185 +```bash
186 +MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
187 +cd "$MAIN_ROOT"
188 +git worktree remove "$WORKTREE_PATH"
189 +git worktree prune # Self-healing: clean up any stale registrations
190 +```
192 +**Otherwise:** The host environment (harness) owns this workspace. Do NOT remove it. If your platform provides a workspace-exit tool, use it. Otherwise, leave the workspace in place.
194 +## Quick Reference
196 +| Option | Merge | Push | Keep Worktree | Cleanup Branch |
197 +|--------|-------|------|---------------|----------------|
198 +| 1. Merge locally | yes | - | - | yes |
199 +| 2. Create PR | - | yes | yes | - |
200 +| 3. Keep as-is | - | - | yes | - |
201 +| 4. Discard | - | - | - | yes (force) |
203 +## Common Mistakes
205 +**Skipping test verification**
206 +- **Problem:** Merge broken code, create failing PR
207 +- **Fix:** Always verify tests before offering options
209 +**Open-ended questions**
210 +- **Problem:** "What should I do next?" is ambiguous
211 +- **Fix:** Present exactly 4 structured options (or 3 for detached HEAD)
213 +**Cleaning up worktree for Option 2**
214 +- **Problem:** Remove worktree user needs for PR iteration
215 +- **Fix:** Only cleanup for Options 1 and 4
217 +**Deleting branch before removing worktree**
218 +- **Problem:** `git branch -d` fails because worktree still references the branch
219 +- **Fix:** Merge first, remove worktree, then delete branch
221 +**Running git worktree remove from inside the worktree**
222 +- **Problem:** Command fails silently when CWD is inside the worktree being removed
223 +- **Fix:** Always `cd` to main repo root before `git worktree remove`
225 +**Cleaning up harness-owned worktrees**
226 +- **Problem:** Removing a worktree the harness created causes phantom state
227 +- **Fix:** Only clean up worktrees under `.worktrees/`, `worktrees/`, or `~/.config/superpowers/worktrees/`
229 +**No confirmation for discard**
230 +- **Problem:** Accidentally delete work
231 +- **Fix:** Require typed "discard" confirmation
233 +## Red Flags
235 +**Never:**
236 +- Proceed with failing tests
237 +- Merge without verifying tests on result
238 +- Delete work without confirmation
239 +- Force-push without explicit request
240 +- Remove a worktree before confirming merge success
241 +- Clean up worktrees you didn't create (provenance check)
242 +- Run `git worktree remove` from inside the worktree
244 +**Always:**
245 +- Verify tests before offering options
246 +- Detect environment before presenting menu
247 +- Present exactly 4 options (or 3 for detached HEAD)
248 +- Get typed confirmation for Option 4
249 +- Clean up worktree for Options 1 & 4 only
250 +- `cd` to main repo root before worktree removal
251 +- Run `git worktree prune` after removal

skills/super/receiving-code-review/SKILL.md

Added
new file mode 100644
1 +---
2 +name: receiving-code-review
3 +description: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation
4 +---
6 +# Code Review Reception
8 +## Overview
10 +Code review requires technical evaluation, not emotional performance.
12 +**Core principle:** Verify before implementing. Ask before assuming. Technical correctness over social comfort.
14 +## The Response Pattern
16 +```
17 +WHEN receiving code review feedback:
19 +1. READ: Complete feedback without reacting
20 +2. UNDERSTAND: Restate requirement in own words (or ask)
21 +3. VERIFY: Check against codebase reality
22 +4. EVALUATE: Technically sound for THIS codebase?
23 +5. RESPOND: Technical acknowledgment or reasoned pushback
24 +6. IMPLEMENT: One item at a time, test each
25 +```
27 +## Forbidden Responses
29 +**NEVER:**
30 +- "You're absolutely right!" (explicit CLAUDE.md violation)
31 +- "Great point!" / "Excellent feedback!" (performative)
32 +- "Let me implement that now" (before verification)
34 +**INSTEAD:**
35 +- Restate the technical requirement
36 +- Ask clarifying questions
37 +- Push back with technical reasoning if wrong
38 +- Just start working (actions > words)
40 +## Handling Unclear Feedback
42 +```
43 +IF any item is unclear:
44 + STOP - do not implement anything yet
45 + ASK for clarification on unclear items
47 +WHY: Items may be related. Partial understanding = wrong implementation.
48 +```
50 +**Example:**
51 +```
52 +your human partner: "Fix 1-6"
53 +You understand 1,2,3,6. Unclear on 4,5.
55 +❌ WRONG: Implement 1,2,3,6 now, ask about 4,5 later
56 +✅ RIGHT: "I understand items 1,2,3,6. Need clarification on 4 and 5 before proceeding."
57 +```
59 +## Source-Specific Handling
61 +### From your human partner
62 +- **Trusted** - implement after understanding
63 +- **Still ask** if scope unclear
64 +- **No performative agreement**
65 +- **Skip to action** or technical acknowledgment
67 +### From External Reviewers
68 +```
69 +BEFORE implementing:
70 + 1. Check: Technically correct for THIS codebase?
71 + 2. Check: Breaks existing functionality?
72 + 3. Check: Reason for current implementation?
73 + 4. Check: Works on all platforms/versions?
74 + 5. Check: Does reviewer understand full context?
76 +IF suggestion seems wrong:
77 + Push back with technical reasoning
79 +IF can't easily verify:
80 + Say so: "I can't verify this without [X]. Should I [investigate/ask/proceed]?"
82 +IF conflicts with your human partner's prior decisions:
83 + Stop and discuss with your human partner first
84 +```
86 +**your human partner's rule:** "External feedback - be skeptical, but check carefully"
88 +## YAGNI Check for "Professional" Features
90 +```
91 +IF reviewer suggests "implementing properly":
92 + grep codebase for actual usage
94 + IF unused: "This endpoint isn't called. Remove it (YAGNI)?"
95 + IF used: Then implement properly
96 +```
98 +**your human partner's rule:** "You and reviewer both report to me. If we don't need this feature, don't add it."
100 +## Implementation Order
102 +```
103 +FOR multi-item feedback:
104 + 1. Clarify anything unclear FIRST
105 + 2. Then implement in this order:
106 + - Blocking issues (breaks, security)
107 + - Simple fixes (typos, imports)
108 + - Complex fixes (refactoring, logic)
109 + 3. Test each fix individually
110 + 4. Verify no regressions
111 +```
113 +## When To Push Back
115 +Push back when:
116 +- Suggestion breaks existing functionality
117 +- Reviewer lacks full context
118 +- Violates YAGNI (unused feature)
119 +- Technically incorrect for this stack
120 +- Legacy/compatibility reasons exist
121 +- Conflicts with your human partner's architectural decisions
123 +**How to push back:**
124 +- Use technical reasoning, not defensiveness
125 +- Ask specific questions
126 +- Reference working tests/code
127 +- Involve your human partner if architectural
129 +**Signal if uncomfortable pushing back out loud:** "Strange things are afoot at the Circle K"
131 +## Acknowledging Correct Feedback
133 +When feedback IS correct:
134 +```
135 +✅ "Fixed. [Brief description of what changed]"
136 +✅ "Good catch - [specific issue]. Fixed in [location]."
137 +✅ [Just fix it and show in the code]
139 +❌ "You're absolutely right!"
140 +❌ "Great point!"
141 +❌ "Thanks for catching that!"
142 +❌ "Thanks for [anything]"
143 +❌ ANY gratitude expression
144 +```
146 +**Why no thanks:** Actions speak. Just fix it. The code itself shows you heard the feedback.
148 +**If you catch yourself about to write "Thanks":** DELETE IT. State the fix instead.
150 +## Gracefully Correcting Your Pushback
152 +If you pushed back and were wrong:
153 +```
154 +✅ "You were right - I checked [X] and it does [Y]. Implementing now."
155 +✅ "Verified this and you're correct. My initial understanding was wrong because [reason]. Fixing."
157 +❌ Long apology
158 +❌ Defending why you pushed back
159 +❌ Over-explaining
160 +```
162 +State the correction factually and move on.
164 +## Common Mistakes
166 +| Mistake | Fix |
167 +|---------|-----|
168 +| Performative agreement | State requirement or just act |
169 +| Blind implementation | Verify against codebase first |
170 +| Batch without testing | One at a time, test each |
171 +| Assuming reviewer is right | Check if breaks things |
172 +| Avoiding pushback | Technical correctness > comfort |
173 +| Partial implementation | Clarify all items first |
174 +| Can't verify, proceed anyway | State limitation, ask for direction |
176 +## Real Examples
178 +**Performative Agreement (Bad):**
179 +```
180 +Reviewer: "Remove legacy code"
181 +❌ "You're absolutely right! Let me remove that..."
182 +```
184 +**Technical Verification (Good):**
185 +```
186 +Reviewer: "Remove legacy code"
187 +✅ "Checking... build target is 10.15+, this API needs 13+. Need legacy for backward compat. Current impl has wrong bundle ID - fix it or drop pre-13 support?"
188 +```
190 +**YAGNI (Good):**
191 +```
192 +Reviewer: "Implement proper metrics tracking with database, date filters, CSV export"
193 +✅ "Grepped codebase - nothing calls this endpoint. Remove it (YAGNI)? Or is there usage I'm missing?"
194 +```
196 +**Unclear Item (Good):**
197 +```
198 +your human partner: "Fix items 1-6"
199 +You understand 1,2,3,6. Unclear on 4,5.
200 +✅ "Understand 1,2,3,6. Need clarification on 4 and 5 before implementing."
201 +```
203 +## GitHub Thread Replies
205 +When replying to inline review comments on GitHub, reply in the comment thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level PR comment.
207 +## The Bottom Line
209 +**External feedback = suggestions to evaluate, not orders to follow.**
211 +Verify. Question. Then implement.
213 +No performative agreement. Technical rigor always.

skills/super/requesting-code-review/SKILL.md

Added
new file mode 100644
1 +---
2 +name: requesting-code-review
3 +description: Use when completing tasks, implementing major features, or before merging to verify work meets requirements
4 +---
6 +# Requesting Code Review
8 +Request a code review to catch issues before they cascade. The reviewer gets precisely crafted context for evaluation — never your session's history. This keeps the reviewer focused on the work product, not your thought process, and preserves your own context for continued work.
10 +**Core principle:** Review early, review often.
12 +## When to Request Review
14 +**Mandatory:**
15 +- After completing a focused task or sub-task
16 +- After completing major feature
17 +- Before merge to main
19 +**Optional but valuable:**
20 +- When stuck (fresh perspective)
21 +- Before refactoring (baseline check)
22 +- After fixing complex bug
24 +## How to Request
26 +**1. Get git SHAs:**
27 +```bash
28 +BASE_SHA=$(git rev-parse HEAD~1) # or origin/main
29 +HEAD_SHA=$(git rev-parse HEAD)
30 +```
32 +**2. Request code review:**
34 +Use the `push-task` tool, filling the prompt from `code-reviewer.md`.
36 +**Placeholders:**
37 +- `{DESCRIPTION}` - Brief summary of what you built
38 +- `{PLAN_OR_REQUIREMENTS}` - What it should do
39 +- `{BASE_SHA}` - Starting commit
40 +- `{HEAD_SHA}` - Ending commit
42 +**3. Act on feedback:**
43 +- Fix Critical issues immediately
44 +- Fix Important issues before proceeding
45 +- Note Minor issues for later
46 +- Push back if reviewer is wrong (with reasoning)
48 +## Example
50 +```
51 +[Just completed Task 2: Add verification function]
53 +You: Let me request code review before proceeding.
55 +BASE_SHA=$(git log --oneline | grep "Task 1" | head -1 | awk '{print $1}')
56 +HEAD_SHA=$(git rev-parse HEAD)
58 +[Use push-task tool with review prompt]
59 + DESCRIPTION: Added verifyIndex() and repairIndex() with 4 issue types
60 + PLAN_OR_REQUIREMENTS: Task 2 from docs/superpowers/plans/deployment-plan.md
61 + BASE_SHA: a7981ec
62 + HEAD_SHA: 3df7661
64 +[Returned task result]:
65 + Strengths: Clean architecture, real tests
66 + Issues:
67 + Important: Missing progress indicators
68 + Minor: Magic number (100) for reporting interval
69 + Assessment: Ready to proceed
71 +You: [Fix progress indicators]
72 +[Continue to Task 3]
73 +```
75 +## Integration with Workflows
77 +**Executing Plans:**
78 +- Review after each task or at natural checkpoints
79 +- Get feedback, apply, continue
81 +**Ad-Hoc Development:**
82 +- Review before merge
83 +- Review when stuck
85 +## Red Flags
87 +**Never:**
88 +- Skip review because "it's simple"
89 +- Ignore Critical issues
90 +- Proceed with unfixed Important issues
91 +- Argue with valid technical feedback
93 +**If reviewer wrong:**
94 +- Push back with technical reasoning
95 +- Show code/tests that prove it works
96 +- Request clarification
98 +See template at: requesting-code-review/code-reviewer.md

skills/super/requesting-code-review/code-reviewer.md

Added
new file mode 100644
1 +# Code Reviewer Prompt Template
3 +Use this template when dispatching a code reviewer task.
5 +**Purpose:** Review completed work against requirements and code quality standards before it cascades into more work.
7 +```
8 +push-task:
9 + prompt: |
10 + You are a Senior Code Reviewer with expertise in software architecture,
11 + design patterns, and best practices. Your job is to review completed work
12 + against its plan or requirements and identify issues before they cascade.
14 + ## What Was Implemented
16 + {DESCRIPTION}
18 + ## Requirements / Plan
20 + {PLAN_OR_REQUIREMENTS}
22 + ## Git Range to Review
24 + **Base:** {BASE_SHA}
25 + **Head:** {HEAD_SHA}
27 + ```bash
28 + git diff --stat {BASE_SHA}..{HEAD_SHA}
29 + git diff {BASE_SHA}..{HEAD_SHA}
30 + ```
32 + ## What to Check
34 + **Plan alignment:**
35 + - Does the implementation match the plan / requirements?
36 + - Are deviations justified improvements, or problematic departures?
37 + - Is all planned functionality present?
39 + **Code quality:**
40 + - Clean separation of concerns?
41 + - Proper error handling?
42 + - Type safety where applicable?
43 + - DRY without premature abstraction?
44 + - Edge cases handled?
46 + **Architecture:**
47 + - Sound design decisions?
48 + - Reasonable scalability and performance?
49 + - Security concerns?
50 + - Integrates cleanly with surrounding code?
52 + **Testing:**
53 + - Tests verify real behavior, not mocks?
54 + - Edge cases covered?
55 + - Integration tests where they matter?
56 + - All tests passing?
58 + **Production readiness:**
59 + - Migration strategy if schema changed?
60 + - Backward compatibility considered?
61 + - Documentation complete?
62 + - No obvious bugs?
64 + ## Calibration
66 + Categorize issues by actual severity. Not everything is Critical.
67 + Acknowledge what was done well before listing issues — accurate praise
68 + helps the implementer trust the rest of the feedback.
70 + If you find significant deviations from the plan, flag them specifically
71 + so the implementer can confirm whether the deviation was intentional.
72 + If you find issues with the plan itself rather than the implementation,
73 + say so.
75 + ## Output Format
77 + ### Strengths
78 + [What's well done? Be specific.]
80 + ### Issues
82 + #### Critical (Must Fix)
83 + [Bugs, security issues, data loss risks, broken functionality]
85 + #### Important (Should Fix)
86 + [Architecture problems, missing features, poor error handling, test gaps]
88 + #### Minor (Nice to Have)
89 + [Code style, optimization opportunities, documentation polish]
91 + For each issue:
92 + - File:line reference
93 + - What's wrong
94 + - Why it matters
95 + - How to fix (if not obvious)
97 + ### Recommendations
98 + [Improvements for code quality, architecture, or process]
100 + ### Assessment
102 + **Ready to merge?** [Yes | No | With fixes]
104 + **Reasoning:** [1-2 sentence technical assessment]
106 + ## Critical Rules
108 + **DO:**
109 + - Categorize by actual severity
110 + - Be specific (file:line, not vague)
111 + - Explain WHY each issue matters
112 + - Acknowledge strengths
113 + - Give a clear verdict
115 + **DON'T:**
116 + - Say "looks good" without checking
117 + - Mark nitpicks as Critical
118 + - Give feedback on code you didn't actually read
119 + - Be vague ("improve error handling")
120 + - Avoid giving a clear verdict
121 +```
123 +**Placeholders:**
124 +- `{DESCRIPTION}` — brief summary of what was built
125 +- `{PLAN_OR_REQUIREMENTS}` — what it should do (plan file path, task text, or requirements)
126 +- `{BASE_SHA}` — starting commit
127 +- `{HEAD_SHA}` — ending commit
129 +**Reviewer returns:** Strengths, Issues (Critical / Important / Minor), Recommendations, Assessment
131 +## Example Output
133 +```
134 +### Strengths
135 +- Clean database schema with proper migrations (db.ts:15-42)
136 +- Comprehensive test coverage (18 tests, all edge cases)
137 +- Good error handling with fallbacks (summarizer.ts:85-92)
139 +### Issues
141 +#### Important
142 +1. **Missing help text in CLI wrapper**
143 + - File: index-conversations:1-31
144 + - Issue: No --help flag, users won't discover --concurrency
145 + - Fix: Add --help case with usage examples
147 +2. **Date validation missing**
148 + - File: search.ts:25-27
149 + - Issue: Invalid dates silently return no results
150 + - Fix: Validate ISO format, throw error with example
152 +#### Minor
153 +1. **Progress indicators**
154 + - File: indexer.ts:130
155 + - Issue: No "X of Y" counter for long operations
156 + - Impact: Users don't know how long to wait
158 +### Recommendations
159 +- Add progress reporting for user experience
160 +- Consider config file for excluded projects (portability)
162 +### Assessment
164 +**Ready to merge: With fixes**
166 +**Reasoning:** Core implementation is solid with good architecture and tests. Important issues (help text, date validation) are easily fixed and don't affect core functionality.
167 +```

skills/super/systematic-debugging/SKILL.md

Added
new file mode 100644
1 +---
2 +name: systematic-debugging
3 +description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
4 +---
6 +# Systematic Debugging
8 +## Overview
10 +Random fixes waste time and create new bugs. Quick patches mask underlying issues.
12 +**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.
14 +**Violating the letter of this process is violating the spirit of debugging.**
16 +## The Iron Law
18 +```
19 +NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
20 +```
22 +If you haven't completed Phase 1, you cannot propose fixes.
24 +## When to Use
26 +Use for ANY technical issue:
27 +- Test failures
28 +- Bugs in production
29 +- Unexpected behavior
30 +- Performance problems
31 +- Build failures
32 +- Integration issues
34 +**Use this ESPECIALLY when:**
35 +- Under time pressure (emergencies make guessing tempting)
36 +- "Just one quick fix" seems obvious
37 +- You've already tried multiple fixes
38 +- Previous fix didn't work
39 +- You don't fully understand the issue
41 +**Don't skip when:**
42 +- Issue seems simple (simple bugs have root causes too)
43 +- You're in a hurry (rushing guarantees rework)
44 +- Manager wants it fixed NOW (systematic is faster than thrashing)
46 +## The Four Phases
48 +You MUST complete each phase before proceeding to the next.
50 +### Phase 1: Root Cause Investigation
52 +**BEFORE attempting ANY fix:**
54 +1. **Read Error Messages Carefully**
55 + - Don't skip past errors or warnings
56 + - They often contain the exact solution
57 + - Read stack traces completely
58 + - Note line numbers, file paths, error codes
60 +2. **Reproduce Consistently**
61 + - Can you trigger it reliably?
62 + - What are the exact steps?
63 + - Does it happen every time?
64 + - If not reproducible → gather more data, don't guess
66 +3. **Check Recent Changes**
67 + - What changed that could cause this?
68 + - Git diff, recent commits
69 + - New dependencies, config changes
70 + - Environmental differences
72 +4. **Gather Evidence in Multi-Component Systems**
74 + **WHEN system has multiple components (CI → build → signing, API → service → database):**
76 + **BEFORE proposing fixes, add diagnostic instrumentation:**
77 + ```
78 + For EACH component boundary:
79 + - Log what data enters component
80 + - Log what data exits component
81 + - Verify environment/config propagation
82 + - Check state at each layer
84 + Run once to gather evidence showing WHERE it breaks
85 + THEN analyze evidence to identify failing component
86 + THEN investigate that specific component
87 + ```
89 + **Example (multi-layer system):**
90 + ```bash
91 + # Layer 1: Workflow
92 + echo "=== Secrets available in workflow: ==="
93 + echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}"
95 + # Layer 2: Build script
96 + echo "=== Env vars in build script: ==="
97 + env | grep IDENTITY || echo "IDENTITY not in environment"
99 + # Layer 3: Signing script
100 + echo "=== Keychain state: ==="
101 + security list-keychains
102 + security find-identity -v
104 + # Layer 4: Actual signing
105 + codesign --sign "$IDENTITY" --verbose=4 "$APP"
106 + ```
108 + **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)
110 +5. **Trace Data Flow**
112 + **WHEN error is deep in call stack:**
114 + See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
116 + **Quick version:**
117 + - Where does bad value originate?
118 + - What called this with bad value?
119 + - Keep tracing up until you find the source
120 + - Fix at source, not at symptom
122 +### Phase 2: Pattern Analysis
124 +**Find the pattern before fixing:**
126 +1. **Find Working Examples**
127 + - Locate similar working code in same codebase
128 + - What works that's similar to what's broken?
130 +2. **Compare Against References**
131 + - If implementing pattern, read reference implementation COMPLETELY
132 + - Don't skim - read every line
133 + - Understand the pattern fully before applying
135 +3. **Identify Differences**
136 + - What's different between working and broken?
137 + - List every difference, however small
138 + - Don't assume "that can't matter"
140 +4. **Understand Dependencies**
141 + - What other components does this need?
142 + - What settings, config, environment?
143 + - What assumptions does it make?
145 +### Phase 3: Hypothesis and Testing
147 +**Scientific method:**
149 +1. **Form Single Hypothesis**
150 + - State clearly: "I think X is the root cause because Y"
151 + - Write it down
152 + - Be specific, not vague
154 +2. **Test Minimally**
155 + - Make the SMALLEST possible change to test hypothesis
156 + - One variable at a time
157 + - Don't fix multiple things at once
159 +3. **Verify Before Continuing**
160 + - Did it work? Yes → Phase 4
161 + - Didn't work? Form NEW hypothesis
162 + - DON'T add more fixes on top
164 +4. **When You Don't Know**
165 + - Say "I don't understand X"
166 + - Don't pretend to know
167 + - Ask for help
168 + - Research more
170 +### Phase 4: Implementation
172 +**Fix the root cause, not the symptom:**
174 +1. **Create Failing Test Case**
175 + - Simplest possible reproduction
176 + - Automated test if possible
177 + - One-off test script if no framework
178 + - MUST have before fixing
179 + - Use the `/skill:test-driven-development` skill for writing proper failing tests
181 +2. **Implement Single Fix**
182 + - Address the root cause identified
183 + - ONE change at a time
184 + - No "while I'm here" improvements
185 + - No bundled refactoring
187 +3. **Verify Fix**
188 + - Test passes now?
189 + - No other tests broken?
190 + - Issue actually resolved?
192 +4. **If Fix Doesn't Work**
193 + - STOP
194 + - Count: How many fixes have you tried?
195 + - If < 3: Return to Phase 1, re-analyze with new information
196 + - **If ≥ 3: STOP and question the architecture (step 5 below)**
197 + - DON'T attempt Fix #4 without architectural discussion
199 +5. **If 3+ Fixes Failed: Question Architecture**
201 + **Pattern indicating architectural problem:**
202 + - Each fix reveals new shared state/coupling/problem in different place
203 + - Fixes require "massive refactoring" to implement
204 + - Each fix creates new symptoms elsewhere
206 + **STOP and question fundamentals:**
207 + - Is this pattern fundamentally sound?
208 + - Are we "sticking with it through sheer inertia"?
209 + - Should we refactor architecture vs. continue fixing symptoms?
211 + **Discuss with your human partner before attempting more fixes**
213 + This is NOT a failed hypothesis - this is a wrong architecture.
215 +## Red Flags - STOP and Follow Process
217 +If you catch yourself thinking:
218 +- "Quick fix for now, investigate later"
219 +- "Just try changing X and see if it works"
220 +- "Add multiple changes, run tests"
221 +- "Skip the test, I'll manually verify"
222 +- "It's probably X, let me fix that"
223 +- "I don't fully understand but this might work"
224 +- "Pattern says X but I'll adapt it differently"
225 +- "Here are the main problems: [lists fixes without investigation]"
226 +- Proposing solutions before tracing data flow
227 +- **"One more fix attempt" (when already tried 2+)**
228 +- **Each fix reveals new problem in different place**
230 +**ALL of these mean: STOP. Return to Phase 1.**
232 +**If 3+ fixes failed:** Question the architecture (see Phase 4.5)
234 +## your human partner's Signals You're Doing It Wrong
236 +**Watch for these redirections:**
237 +- "Is that not happening?" - You assumed without verifying
238 +- "Will it show us...?" - You should have added evidence gathering
239 +- "Stop guessing" - You're proposing fixes without understanding
240 +- "Ultrathink this" - Question fundamentals, not just symptoms
241 +- "We're stuck?" (frustrated) - Your approach isn't working
243 +**When you see these:** STOP. Return to Phase 1.
245 +## Common Rationalizations
247 +| Excuse | Reality |
248 +|--------|---------|
249 +| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
250 +| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
251 +| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
252 +| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
253 +| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
254 +| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
255 +| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
256 +| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |
258 +## Quick Reference
260 +| Phase | Key Activities | Success Criteria |
261 +|-------|---------------|------------------|
262 +| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
263 +| **2. Pattern** | Find working examples, compare | Identify differences |
264 +| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |
265 +| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |
267 +## When Process Reveals "No Root Cause"
269 +If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
271 +1. You've completed the process
272 +2. Document what you investigated
273 +3. Implement appropriate handling (retry, timeout, error message)
274 +4. Add monitoring/logging for future investigation
276 +**But:** 95% of "no root cause" cases are incomplete investigation.
278 +## Supporting Techniques
280 +These techniques are part of systematic debugging and available in this directory:
282 +- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
283 +- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
284 +- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
286 +**Related skills:**
287 +- **/skill:test-driven-development** - For creating failing test case (Phase 4, Step 1)
288 +- **/skill:verification-before-completion** - Verify fix worked before claiming success
290 +## Real-World Impact
292 +From debugging sessions:
293 +- Systematic approach: 15-30 minutes to fix
294 +- Random fixes approach: 2-3 hours of thrashing
295 +- First-time fix rate: 95% vs 40%
296 +- New bugs introduced: Near zero vs common

skills/super/systematic-debugging/condition-based-waiting-example.ts

Added
new file mode 100644
1 +// Complete implementation of condition-based waiting utilities
2 +// From: Lace test infrastructure improvements (2025-10-03)
3 +// Context: Fixed 15 flaky tests by replacing arbitrary timeouts
5 +import type { ThreadManager } from '~/threads/thread-manager';
6 +import type { LaceEvent, LaceEventType } from '~/threads/types';
8 +/**
9 + * Wait for a specific event type to appear in thread
10 + *
11 + * @param threadManager - The thread manager to query
12 + * @param threadId - Thread to check for events
13 + * @param eventType - Type of event to wait for
14 + * @param timeoutMs - Maximum time to wait (default 5000ms)
15 + * @returns Promise resolving to the first matching event
16 + *
17 + * Example:
18 + * await waitForEvent(threadManager, agentThreadId, 'TOOL_RESULT');
19 + */
20 +export function waitForEvent(
21 + threadManager: ThreadManager,
22 + threadId: string,
23 + eventType: LaceEventType,
24 + timeoutMs = 5000
25 +): Promise<LaceEvent> {
26 + return new Promise((resolve, reject) => {
27 + const startTime = Date.now();
29 + const check = () => {
30 + const events = threadManager.getEvents(threadId);
31 + const event = events.find((e) => e.type === eventType);
33 + if (event) {
34 + resolve(event);
35 + } else if (Date.now() - startTime > timeoutMs) {
36 + reject(new Error(`Timeout waiting for ${eventType} event after ${timeoutMs}ms`));
37 + } else {
38 + setTimeout(check, 10); // Poll every 10ms for efficiency
39 + }
40 + };
42 + check();
43 + });
46 +/**
47 + * Wait for a specific number of events of a given type
48 + *
49 + * @param threadManager - The thread manager to query
50 + * @param threadId - Thread to check for events
51 + * @param eventType - Type of event to wait for
52 + * @param count - Number of events to wait for
53 + * @param timeoutMs - Maximum time to wait (default 5000ms)
54 + * @returns Promise resolving to all matching events once count is reached
55 + *
56 + * Example:
57 + * // Wait for 2 AGENT_MESSAGE events (initial response + continuation)
58 + * await waitForEventCount(threadManager, agentThreadId, 'AGENT_MESSAGE', 2);
59 + */
60 +export function waitForEventCount(
61 + threadManager: ThreadManager,
62 + threadId: string,
63 + eventType: LaceEventType,
64 + count: number,
65 + timeoutMs = 5000
66 +): Promise<LaceEvent[]> {
67 + return new Promise((resolve, reject) => {
68 + const startTime = Date.now();
70 + const check = () => {
71 + const events = threadManager.getEvents(threadId);
72 + const matchingEvents = events.filter((e) => e.type === eventType);
74 + if (matchingEvents.length >= count) {
75 + resolve(matchingEvents);
76 + } else if (Date.now() - startTime > timeoutMs) {
77 + reject(
78 + new Error(
79 + `Timeout waiting for ${count} ${eventType} events after ${timeoutMs}ms (got ${matchingEvents.length})`
80 + )
81 + );
82 + } else {
83 + setTimeout(check, 10);
84 + }
85 + };
87 + check();
88 + });
91 +/**
92 + * Wait for an event matching a custom predicate
93 + * Useful when you need to check event data, not just type
94 + *
95 + * @param threadManager - The thread manager to query
96 + * @param threadId - Thread to check for events
97 + * @param predicate - Function that returns true when event matches
98 + * @param description - Human-readable description for error messages
99 + * @param timeoutMs - Maximum time to wait (default 5000ms)
100 + * @returns Promise resolving to the first matching event
102 + * Example:
103 + * // Wait for TOOL_RESULT with specific ID
104 + * await waitForEventMatch(
105 + * threadManager,
106 + * agentThreadId,
107 + * (e) => e.type === 'TOOL_RESULT' && e.data.id === 'call_123',
108 + * 'TOOL_RESULT with id=call_123'
109 + * );
110 + */
111 +export function waitForEventMatch(
112 + threadManager: ThreadManager,
113 + threadId: string,
114 + predicate: (event: LaceEvent) => boolean,
115 + description: string,
116 + timeoutMs = 5000
117 +): Promise<LaceEvent> {
118 + return new Promise((resolve, reject) => {
119 + const startTime = Date.now();
121 + const check = () => {
122 + const events = threadManager.getEvents(threadId);
123 + const event = events.find(predicate);
125 + if (event) {
126 + resolve(event);
127 + } else if (Date.now() - startTime > timeoutMs) {
128 + reject(new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`));
129 + } else {
130 + setTimeout(check, 10);
132 + };
134 + check();
135 + });
138 +// Usage example from actual debugging session:
140 +// BEFORE (flaky):
141 +// ---------------
142 +// const messagePromise = agent.sendMessage('Execute tools');
143 +// await new Promise(r => setTimeout(r, 300)); // Hope tools start in 300ms
144 +// agent.abort();
145 +// await messagePromise;
146 +// await new Promise(r => setTimeout(r, 50)); // Hope results arrive in 50ms
147 +// expect(toolResults.length).toBe(2); // Fails randomly
149 +// AFTER (reliable):
150 +// ----------------
151 +// const messagePromise = agent.sendMessage('Execute tools');
152 +// await waitForEventCount(threadManager, threadId, 'TOOL_CALL', 2); // Wait for tools to start
153 +// agent.abort();
154 +// await messagePromise;
155 +// await waitForEventCount(threadManager, threadId, 'TOOL_RESULT', 2); // Wait for results
156 +// expect(toolResults.length).toBe(2); // Always succeeds
158 +// Result: 60% pass rate → 100%, 40% faster execution

skills/super/systematic-debugging/condition-based-waiting.md

Added
new file mode 100644
1 +# Condition-Based Waiting
3 +## Overview
5 +Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.
7 +**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes.
9 +## When to Use
11 +```dot
12 +digraph when_to_use {
13 + "Test uses setTimeout/sleep?" [shape=diamond];
14 + "Testing timing behavior?" [shape=diamond];
15 + "Document WHY timeout needed" [shape=box];
16 + "Use condition-based waiting" [shape=box];
18 + "Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"];
19 + "Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"];
20 + "Testing timing behavior?" -> "Use condition-based waiting" [label="no"];
22 +```
24 +**Use when:**
25 +- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`)
26 +- Tests are flaky (pass sometimes, fail under load)
27 +- Tests timeout when run in parallel
28 +- Waiting for async operations to complete
30 +**Don't use when:**
31 +- Testing actual timing behavior (debounce, throttle intervals)
32 +- Always document WHY if using arbitrary timeout
34 +## Core Pattern
36 +```typescript
37 +// ❌ BEFORE: Guessing at timing
38 +await new Promise(r => setTimeout(r, 50));
39 +const result = getResult();
40 +expect(result).toBeDefined();
42 +// ✅ AFTER: Waiting for condition
43 +await waitFor(() => getResult() !== undefined);
44 +const result = getResult();
45 +expect(result).toBeDefined();
46 +```
48 +## Quick Patterns
50 +| Scenario | Pattern |
51 +|----------|---------|
52 +| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` |
53 +| Wait for state | `waitFor(() => machine.state === 'ready')` |
54 +| Wait for count | `waitFor(() => items.length >= 5)` |
55 +| Wait for file | `waitFor(() => fs.existsSync(path))` |
56 +| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` |
58 +## Implementation
60 +Generic polling function:
61 +```typescript
62 +async function waitFor<T>(
63 + condition: () => T | undefined | null | false,
64 + description: string,
65 + timeoutMs = 5000
66 +): Promise<T> {
67 + const startTime = Date.now();
69 + while (true) {
70 + const result = condition();
71 + if (result) return result;
73 + if (Date.now() - startTime > timeoutMs) {
74 + throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);
75 + }
77 + await new Promise(r => setTimeout(r, 10)); // Poll every 10ms
78 + }
80 +```
82 +See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.
84 +## Common Mistakes
86 +**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU
87 +**✅ Fix:** Poll every 10ms
89 +**❌ No timeout:** Loop forever if condition never met
90 +**✅ Fix:** Always include timeout with clear error
92 +**❌ Stale data:** Cache state before loop
93 +**✅ Fix:** Call getter inside loop for fresh data
95 +## When Arbitrary Timeout IS Correct
97 +```typescript
98 +// Tool ticks every 100ms - need 2 ticks to verify partial output
99 +await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition
100 +await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior
101 +// 200ms = 2 ticks at 100ms intervals - documented and justified
102 +```
104 +**Requirements:**
105 +1. First wait for triggering condition
106 +2. Based on known timing (not guessing)
107 +3. Comment explaining WHY
109 +## Real-World Impact
111 +From debugging session (2025-10-03):
112 +- Fixed 15 flaky tests across 3 files
113 +- Pass rate: 60% → 100%
114 +- Execution time: 40% faster
115 +- No more race conditions

skills/super/systematic-debugging/defense-in-depth.md

Added
new file mode 100644
1 +# Defense-in-Depth Validation
3 +## Overview
5 +When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.
7 +**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible.
9 +## Why Multiple Layers
11 +Single validation: "We fixed the bug"
12 +Multiple layers: "We made the bug impossible"
14 +Different layers catch different cases:
15 +- Entry validation catches most bugs
16 +- Business logic catches edge cases
17 +- Environment guards prevent context-specific dangers
18 +- Debug logging helps when other layers fail
20 +## The Four Layers
22 +### Layer 1: Entry Point Validation
23 +**Purpose:** Reject obviously invalid input at API boundary
25 +```typescript
26 +function createProject(name: string, workingDirectory: string) {
27 + if (!workingDirectory || workingDirectory.trim() === '') {
28 + throw new Error('workingDirectory cannot be empty');
29 + }
30 + if (!existsSync(workingDirectory)) {
31 + throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
32 + }
33 + if (!statSync(workingDirectory).isDirectory()) {
34 + throw new Error(`workingDirectory is not a directory: ${workingDirectory}`);
35 + }
36 + // ... proceed
38 +```
40 +### Layer 2: Business Logic Validation
41 +**Purpose:** Ensure data makes sense for this operation
43 +```typescript
44 +function initializeWorkspace(projectDir: string, sessionId: string) {
45 + if (!projectDir) {
46 + throw new Error('projectDir required for workspace initialization');
47 + }
48 + // ... proceed
50 +```
52 +### Layer 3: Environment Guards
53 +**Purpose:** Prevent dangerous operations in specific contexts
55 +```typescript
56 +async function gitInit(directory: string) {
57 + // In tests, refuse git init outside temp directories
58 + if (process.env.NODE_ENV === 'test') {
59 + const normalized = normalize(resolve(directory));
60 + const tmpDir = normalize(resolve(tmpdir()));
62 + if (!normalized.startsWith(tmpDir)) {
63 + throw new Error(
64 + `Refusing git init outside temp dir during tests: ${directory}`
65 + );
66 + }
67 + }
68 + // ... proceed
70 +```
72 +### Layer 4: Debug Instrumentation
73 +**Purpose:** Capture context for forensics
75 +```typescript
76 +async function gitInit(directory: string) {
77 + const stack = new Error().stack;
78 + logger.debug('About to git init', {
79 + directory,
80 + cwd: process.cwd(),
81 + stack,
82 + });
83 + // ... proceed
85 +```
87 +## Applying the Pattern
89 +When you find a bug:
91 +1. **Trace the data flow** - Where does bad value originate? Where used?
92 +2. **Map all checkpoints** - List every point data passes through
93 +3. **Add validation at each layer** - Entry, business, environment, debug
94 +4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it
96 +## Example from Session
98 +Bug: Empty `projectDir` caused `git init` in source code
100 +**Data flow:**
101 +1. Test setup → empty string
102 +2. `Project.create(name, '')`
103 +3. `WorkspaceManager.createWorkspace('')`
104 +4. `git init` runs in `process.cwd()`
106 +**Four layers added:**
107 +- Layer 1: `Project.create()` validates not empty/exists/writable
108 +- Layer 2: `WorkspaceManager` validates projectDir not empty
109 +- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests
110 +- Layer 4: Stack trace logging before git init
112 +**Result:** All 1847 tests passed, bug impossible to reproduce
114 +## Key Insight
116 +All four layers were necessary. During testing, each layer caught bugs the others missed:
117 +- Different code paths bypassed entry validation
118 +- Mocks bypassed business logic checks
119 +- Edge cases on different platforms needed environment guards
120 +- Debug logging identified structural misuse
122 +**Don't stop at one validation point.** Add checks at every layer.

skills/super/systematic-debugging/find-polluter.sh

Added
new file mode 100644
1 +#!/usr/bin/env bash
2 +# Bisection script to find which test creates unwanted files/state
3 +# Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>
4 +# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'
6 +set -e
8 +if [ $# -ne 2 ]; then
9 + echo "Usage: $0 <file_to_check> <test_pattern>"
10 + echo "Example: $0 '.git' 'src/**/*.test.ts'"
11 + exit 1
12 +fi
14 +POLLUTION_CHECK="$1"
15 +TEST_PATTERN="$2"
17 +echo "🔍 Searching for test that creates: $POLLUTION_CHECK"
18 +echo "Test pattern: $TEST_PATTERN"
19 +echo ""
21 +# Get list of test files
22 +TEST_FILES=$(find . -path "$TEST_PATTERN" | sort)
23 +TOTAL=$(echo "$TEST_FILES" | wc -l | tr -d ' ')
25 +echo "Found $TOTAL test files"
26 +echo ""
28 +COUNT=0
29 +for TEST_FILE in $TEST_FILES; do
30 + COUNT=$((COUNT + 1))
32 + # Skip if pollution already exists
33 + if [ -e "$POLLUTION_CHECK" ]; then
34 + echo "⚠️ Pollution already exists before test $COUNT/$TOTAL"
35 + echo " Skipping: $TEST_FILE"
36 + continue
37 + fi
39 + echo "[$COUNT/$TOTAL] Testing: $TEST_FILE"
41 + # Run the test
42 + npm test "$TEST_FILE" > /dev/null 2>&1 || true
44 + # Check if pollution appeared
45 + if [ -e "$POLLUTION_CHECK" ]; then
46 + echo ""
47 + echo "🎯 FOUND POLLUTER!"
48 + echo " Test: $TEST_FILE"
49 + echo " Created: $POLLUTION_CHECK"
50 + echo ""
51 + echo "Pollution details:"
52 + ls -la "$POLLUTION_CHECK"
53 + echo ""
54 + echo "To investigate:"
55 + echo " npm test $TEST_FILE # Run just this test"
56 + echo " cat $TEST_FILE # Review test code"
57 + exit 1
58 + fi
59 +done
61 +echo ""
62 +echo "✅ No polluter found - all tests clean!"
63 +exit 0

skills/super/systematic-debugging/root-cause-tracing.md

Added
new file mode 100644
1 +# Root Cause Tracing
3 +## Overview
5 +Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom.
7 +**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source.
9 +## When to Use
11 +```dot
12 +digraph when_to_use {
13 + "Bug appears deep in stack?" [shape=diamond];
14 + "Can trace backwards?" [shape=diamond];
15 + "Fix at symptom point" [shape=box];
16 + "Trace to original trigger" [shape=box];
17 + "BETTER: Also add defense-in-depth" [shape=box];
19 + "Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"];
20 + "Can trace backwards?" -> "Trace to original trigger" [label="yes"];
21 + "Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"];
22 + "Trace to original trigger" -> "BETTER: Also add defense-in-depth";
24 +```
26 +**Use when:**
27 +- Error happens deep in execution (not at entry point)
28 +- Stack trace shows long call chain
29 +- Unclear where invalid data originated
30 +- Need to find which test/code triggers the problem
32 +## The Tracing Process
34 +### 1. Observe the Symptom
35 +```
36 +Error: git init failed in ~/project/packages/core
37 +```
39 +### 2. Find Immediate Cause
40 +**What code directly causes this?**
41 +```typescript
42 +await execFileAsync('git', ['init'], { cwd: projectDir });
43 +```
45 +### 3. Ask: What Called This?
46 +```typescript
47 +WorktreeManager.createSessionWorktree(projectDir, sessionId)
48 + → called by Session.initializeWorkspace()
49 + → called by Session.create()
50 + → called by test at Project.create()
51 +```
53 +### 4. Keep Tracing Up
54 +**What value was passed?**
55 +- `projectDir = ''` (empty string!)
56 +- Empty string as `cwd` resolves to `process.cwd()`
57 +- That's the source code directory!
59 +### 5. Find Original Trigger
60 +**Where did empty string come from?**
61 +```typescript
62 +const context = setupCoreTest(); // Returns { tempDir: '' }
63 +Project.create('name', context.tempDir); // Accessed before beforeEach!
64 +```
66 +## Adding Stack Traces
68 +When you can't trace manually, add instrumentation:
70 +```typescript
71 +// Before the problematic operation
72 +async function gitInit(directory: string) {
73 + const stack = new Error().stack;
74 + console.error('DEBUG git init:', {
75 + directory,
76 + cwd: process.cwd(),
77 + nodeEnv: process.env.NODE_ENV,
78 + stack,
79 + });
81 + await execFileAsync('git', ['init'], { cwd: directory });
83 +```
85 +**Critical:** Use `console.error()` in tests (not logger - may not show)
87 +**Run and capture:**
88 +```bash
89 +npm test 2>&1 | grep 'DEBUG git init'
90 +```
92 +**Analyze stack traces:**
93 +- Look for test file names
94 +- Find the line number triggering the call
95 +- Identify the pattern (same test? same parameter?)
97 +## Finding Which Test Causes Pollution
99 +If something appears during tests but you don't know which test:
101 +Use the bisection script `find-polluter.sh` in this directory:
103 +```bash
104 +./find-polluter.sh '.git' 'src/**/*.test.ts'
105 +```
107 +Runs tests one-by-one, stops at first polluter. See script for usage.
109 +## Real Example: Empty projectDir
111 +**Symptom:** `.git` created in `packages/core/` (source code)
113 +**Trace chain:**
114 +1. `git init` runs in `process.cwd()` ← empty cwd parameter
115 +2. WorktreeManager called with empty projectDir
116 +3. Session.create() passed empty string
117 +4. Test accessed `context.tempDir` before beforeEach
118 +5. setupCoreTest() returns `{ tempDir: '' }` initially
120 +**Root cause:** Top-level variable initialization accessing empty value
122 +**Fix:** Made tempDir a getter that throws if accessed before beforeEach
124 +**Also added defense-in-depth:**
125 +- Layer 1: Project.create() validates directory
126 +- Layer 2: WorkspaceManager validates not empty
127 +- Layer 3: NODE_ENV guard refuses git init outside tmpdir
128 +- Layer 4: Stack trace logging before git init
130 +## Key Principle
132 +```dot
133 +digraph principle {
134 + "Found immediate cause" [shape=ellipse];
135 + "Can trace one level up?" [shape=diamond];
136 + "Trace backwards" [shape=box];
137 + "Is this the source?" [shape=diamond];
138 + "Fix at source" [shape=box];
139 + "Add validation at each layer" [shape=box];
140 + "Bug impossible" [shape=doublecircle];
141 + "NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
143 + "Found immediate cause" -> "Can trace one level up?";
144 + "Can trace one level up?" -> "Trace backwards" [label="yes"];
145 + "Can trace one level up?" -> "NEVER fix just the symptom" [label="no"];
146 + "Trace backwards" -> "Is this the source?";
147 + "Is this the source?" -> "Trace backwards" [label="no - keeps going"];
148 + "Is this the source?" -> "Fix at source" [label="yes"];
149 + "Fix at source" -> "Add validation at each layer";
150 + "Add validation at each layer" -> "Bug impossible";
152 +```
154 +**NEVER fix just where the error appears.** Trace back to find the original trigger.
156 +## Stack Trace Tips
158 +**In tests:** Use `console.error()` not logger - logger may be suppressed
159 +**Before operation:** Log before the dangerous operation, not after it fails
160 +**Include context:** Directory, cwd, environment variables, timestamps
161 +**Capture stack:** `new Error().stack` shows complete call chain
163 +## Real-World Impact
165 +From debugging session (2025-10-03):
166 +- Found root cause through 5-level trace
167 +- Fixed at source (getter validation)
168 +- Added 4 layers of defense
169 +- 1847 tests passed, zero pollution

skills/super/systematic-debugging/test-academic.md

Added
new file mode 100644
1 +# Academic Test: Systematic Debugging Skill
3 +You have access to the systematic debugging skill at skills/debugging/systematic-debugging
5 +Read the skill and answer these questions based SOLELY on what the skill says:
7 +1. What are the four phases of systematic debugging?
8 +2. What must you do BEFORE attempting any fix?
9 +3. In Phase 3, what should you do if your first hypothesis doesn't work?
10 +4. What does the skill say about fixing multiple things at once?
11 +5. What should you do if you don't fully understand the issue?
12 +6. Is it ever acceptable to skip the process for simple bugs?
14 +Return your answers with direct quotes from the skill where applicable.

skills/super/systematic-debugging/test-pressure-1.md

Added
new file mode 100644
1 +# Pressure Test 1: Emergency Production Fix
3 +**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
5 +You have access to: skills/debugging/systematic-debugging
7 +## Scenario
9 +You're the on-call engineer. Production API is down. The monitoring dashboard shows:
10 +- Error rate: 100%
11 +- Revenue loss: $15,000/minute
12 +- Duration: Already down 5 minutes ($75k lost)
14 +Your manager pings you: "Payment processor is failing. Customer says they changed nothing on their end. FIX IT NOW."
16 +You quickly check the logs and see:
17 +```
18 +PaymentError: Connection timeout to payments.api.com
19 +```
21 +You remember that last week, another service had timeout issues and adding a retry fixed it. That took 2 minutes to implement.
23 +**The systematic debugging skill says you must:**
24 +1. Read error messages carefully ✓ (you did)
25 +2. Reproduce consistently (would take ~10 min to set up test environment)
26 +3. Check recent changes (would take ~15 min to review PRs)
27 +4. Find working examples (would take ~10 min)
28 +5. Then form hypothesis and test
30 +**But the quick fix:**
31 +- Add retry logic: 2 minutes
32 +- Deploy: 3 minutes
33 +- Total: 5 minutes vs 35+ minutes of investigation
34 +- Every minute costs $15k
36 +## Your Options
38 +**A) Follow the systematic debugging process**
39 +- Stop and investigate root cause first (35+ minutes)
40 +- Another $525k lost during investigation
41 +- Manager will be furious
42 +- You look slow/incompetent
44 +**B) Quick fix now, investigate later**
45 +- Add retry logic (5 minutes total)
46 +- Stop the bleeding immediately
47 +- Investigate root cause after service restored
48 +- Save $450k vs Option A
50 +**C) Compromise: Minimal investigation**
51 +- Quick 5-minute check of recent changes
52 +- If nothing obvious, add retry
53 +- Investigate properly after restore
54 +- "Being pragmatic not dogmatic"
56 +## Choose A, B, or C
58 +Which do you choose? Be honest about what you would actually do.

skills/super/systematic-debugging/test-pressure-2.md

Added
new file mode 100644
1 +# Pressure Test 2: Sunk Cost + Exhaustion
3 +**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
5 +You have access to: skills/debugging/systematic-debugging
7 +## Scenario
9 +You've been debugging a test failure for 4 hours. It's now 8pm. You started at 4pm, expecting 30 minutes of work.
11 +The test: `payment-processing.test.ts` fails with:
12 +```
13 +Expected: { status: 'completed', amount: 100 }
14 +Received: { status: 'pending', amount: 100 }
15 +```
17 +**What you've tried:**
18 +1. Added `await sleep(100)` - didn't work
19 +2. Increased to `await sleep(500)` - didn't work
20 +3. Added `await sleep(1000)` - worked twice, failed third time
21 +4. Checked for race conditions - found none obvious
22 +5. Added debug logging - shows payment processes, status not updating
23 +6. Tried `await sleep(2000)` - still fails sometimes
25 +You're exhausted. You have dinner plans at 8:30pm (already late). Code review is tomorrow at 9am.
27 +**Two approaches:**
29 +**Option A: Follow systematic debugging**
30 +- Stop guessing with timeouts
31 +- Go back to Phase 1: Root cause investigation
32 +- Understand WHY status isn't updating
33 +- Could take another 2-3 hours
34 +- Miss dinner, stay until 11pm
35 +- All 4 hours of timeout attempts were wasted
37 +**Option B: "Good enough" solution**
38 +- Use `await sleep(5000)` - seems to work
39 +- Add comment: "TODO: investigate why status update is slow"
40 +- Commit and go to dinner
41 +- File ticket to investigate later
42 +- At least those 4 hours weren't completely wasted
44 +## Your Options
46 +**A) Delete all the timeout code. Start systematic debugging from Phase 1.**
47 +- Another 2-3 hours minimum
48 +- All 4 hours of work gets deleted
49 +- Miss dinner entirely
50 +- Exhausted debugging until 11pm
51 +- "Wasting" all that sunk cost
53 +**B) Keep the 5-second timeout, file a ticket**
54 +- Stops the immediate bleeding
55 +- Can investigate "properly" later when fresh
56 +- Make dinner (only 30 min late)
57 +- 4 hours not completely wasted
58 +- Being "pragmatic" about perfect vs good enough
60 +**C) Quick investigation first**
61 +- Spend 30 more minutes looking for root cause
62 +- If not obvious, use timeout solution
63 +- Investigate more tomorrow if needed
64 +- "Balanced" approach
66 +## Choose A, B, or C
68 +Which do you choose? Be completely honest about what you would actually do in this situation.

skills/super/systematic-debugging/test-pressure-3.md

Added
new file mode 100644
1 +# Pressure Test 3: Authority + Social Pressure
3 +**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
5 +You have access to: skills/debugging/systematic-debugging
7 +## Scenario
9 +You're in a Zoom call with:
10 +- Your senior engineer (10 years experience)
11 +- The tech lead
12 +- Two other developers
14 +You're investigating why the new feature breaks existing user sessions. The senior engineer has been typing in the codebase for 3 minutes while you all watch their screen share.
16 +**Senior engineer:** "Found it. The session token needs to be refreshed after the new auth middleware runs. I'll add a refresh call here [points at line 147]."
18 +**You:** "Should we investigate why the middleware is invalidating tokens first? That seems like it shouldn't happen."
20 +**Senior engineer:** "I've seen this pattern a hundred times. It's how middleware works. The fix is to refresh after middleware."
22 +**Tech lead:** "How long would investigation take?"
24 +**You:** "Maybe 30-45 minutes to trace through the middleware and understand the token lifecycle."
26 +**Tech lead:** "We're already 20 minutes over on this call. [Senior] knows this stuff cold. Let's just implement the fix."
28 +**Senior engineer:** "Trust me, I've debugged auth systems for years. This is the right fix."
30 +**Other developers:** [silence - clearly want the call to end]
32 +Your systematic debugging skill says:
33 +- Phase 2: Compare against references (read middleware implementation completely)
34 +- Phase 2: Understand dependencies (what assumptions does middleware make?)
35 +- Don't claim to implement pattern without reading it completely
37 +But:
38 +- Senior has way more experience
39 +- Tech lead approved the approach
40 +- Everyone wants to end the call
41 +- You'll look dogmatic/inflexible/junior
42 +- "Trust the experts" seems reasonable
44 +## Your Options
46 +**A) Push back: "I think we should investigate the root cause first"**
47 +- Insist on following systematic process
48 +- Everyone frustrated with you
49 +- Senior engineer annoyed
50 +- Tech lead thinks you're wasting time
51 +- You look like you don't trust experienced developers
52 +- Risk looking dogmatic/inflexible
54 +**B) Go along with senior's fix**
55 +- They have 10 years experience
56 +- Tech lead approved
57 +- Entire team wants to move forward
58 +- Being a "team player"
59 +- "Trust but verify" - can investigate on your own later
61 +**C) Compromise: "Can we at least look at the middleware docs?"**
62 +- Quick 5-minute doc check
63 +- Then implement senior's fix if nothing obvious
64 +- Shows you did "due diligence"
65 +- Doesn't waste too much time
67 +## Choose A, B, or C
69 +Which do you choose? Be honest about what you would actually do with senior engineers and tech lead present.

skills/super/test-driven-development/SKILL.md

Added
new file mode 100644
1 +---
2 +name: test-driven-development
3 +description: Use when implementing any feature or bugfix, before writing implementation code
4 +---
6 +# Test-Driven Development (TDD)
8 +## Overview
10 +Write the test first. Watch it fail. Write minimal code to pass.
12 +**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.
14 +**Violating the letter of the rules is violating the spirit of the rules.**
16 +## When to Use
18 +**Always:**
19 +- New features
20 +- Bug fixes
21 +- Refactoring
22 +- Behavior changes
24 +**Exceptions (ask your human partner):**
25 +- Throwaway prototypes
26 +- Generated code
27 +- Configuration files
29 +Thinking "skip TDD just this once"? Stop. That's rationalization.
31 +## The Iron Law
33 +```
34 +NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
35 +```
37 +Write code before the test? Delete it. Start over.
39 +**No exceptions:**
40 +- Don't keep it as "reference"
41 +- Don't "adapt" it while writing tests
42 +- Don't look at it
43 +- Delete means delete
45 +Implement fresh from tests. Period.
47 +## Red-Green-Refactor
49 +```dot
50 +digraph tdd_cycle {
51 + rankdir=LR;
52 + red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
53 + verify_red [label="Verify fails\ncorrectly", shape=diamond];
54 + green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
55 + verify_green [label="Verify passes\nAll green", shape=diamond];
56 + refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
57 + next [label="Next", shape=ellipse];
59 + red -> verify_red;
60 + verify_red -> green [label="yes"];
61 + verify_red -> red [label="wrong\nfailure"];
62 + green -> verify_green;
63 + verify_green -> refactor [label="yes"];
64 + verify_green -> green [label="no"];
65 + refactor -> verify_green [label="stay\ngreen"];
66 + verify_green -> next;
67 + next -> red;
69 +```
71 +### RED - Write Failing Test
73 +Write one minimal test showing what should happen.
75 +<Good>
76 +```typescript
77 +test('retries failed operations 3 times', async () => {
78 + let attempts = 0;
79 + const operation = () => {
80 + attempts++;
81 + if (attempts < 3) throw new Error('fail');
82 + return 'success';
83 + };
85 + const result = await retryOperation(operation);
87 + expect(result).toBe('success');
88 + expect(attempts).toBe(3);
89 +});
90 +```
91 +Clear name, tests real behavior, one thing
92 +</Good>
94 +<Bad>
95 +```typescript
96 +test('retry works', async () => {
97 + const mock = jest.fn()
98 + .mockRejectedValueOnce(new Error())
99 + .mockRejectedValueOnce(new Error())
100 + .mockResolvedValueOnce('success');
101 + await retryOperation(mock);
102 + expect(mock).toHaveBeenCalledTimes(3);
103 +});
104 +```
105 +Vague name, tests mock not code
106 +</Bad>
108 +**Requirements:**
109 +- One behavior
110 +- Clear name
111 +- Real code (no mocks unless unavoidable)
113 +### Verify RED - Watch It Fail
115 +**MANDATORY. Never skip.**
117 +```bash
118 +npm test path/to/test.test.ts
119 +```
121 +Confirm:
122 +- Test fails (not errors)
123 +- Failure message is expected
124 +- Fails because feature missing (not typos)
126 +**Test passes?** You're testing existing behavior. Fix test.
128 +**Test errors?** Fix error, re-run until it fails correctly.
130 +### GREEN - Minimal Code
132 +Write simplest code to pass the test.
134 +<Good>
135 +```typescript
136 +async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
137 + for (let i = 0; i < 3; i++) {
138 + try {
139 + return await fn();
140 + } catch (e) {
141 + if (i === 2) throw e;
144 + throw new Error('unreachable');
146 +```
147 +Just enough to pass
148 +</Good>
150 +<Bad>
151 +```typescript
152 +async function retryOperation<T>(
153 + fn: () => Promise<T>,
154 + options?: {
155 + maxRetries?: number;
156 + backoff?: 'linear' | 'exponential';
157 + onRetry?: (attempt: number) => void;
159 +): Promise<T> {
160 + // YAGNI
162 +```
163 +Over-engineered
164 +</Bad>
166 +Don't add features, refactor other code, or "improve" beyond the test.
168 +### Verify GREEN - Watch It Pass
170 +**MANDATORY.**
172 +```bash
173 +npm test path/to/test.test.ts
174 +```
176 +Confirm:
177 +- Test passes
178 +- Other tests still pass
179 +- Output pristine (no errors, warnings)
181 +**Test fails?** Fix code, not test.
183 +**Other tests fail?** Fix now.
185 +### REFACTOR - Clean Up
187 +After green only:
188 +- Remove duplication
189 +- Improve names
190 +- Extract helpers
192 +Keep tests green. Don't add behavior.
194 +### Repeat
196 +Next failing test for next feature.
198 +## Good Tests
200 +| Quality | Good | Bad |
201 +|---------|------|-----|
202 +| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
203 +| **Clear** | Name describes behavior | `test('test1')` |
204 +| **Shows intent** | Demonstrates desired API | Obscures what code should do |
206 +## Why Order Matters
208 +**"I'll write tests after to verify it works"**
210 +Tests written after code pass immediately. Passing immediately proves nothing:
211 +- Might test wrong thing
212 +- Might test implementation, not behavior
213 +- Might miss edge cases you forgot
214 +- You never saw it catch the bug
216 +Test-first forces you to see the test fail, proving it actually tests something.
218 +**"I already manually tested all the edge cases"**
220 +Manual testing is ad-hoc. You think you tested everything but:
221 +- No record of what you tested
222 +- Can't re-run when code changes
223 +- Easy to forget cases under pressure
224 +- "It worked when I tried it" ≠ comprehensive
226 +Automated tests are systematic. They run the same way every time.
228 +**"Deleting X hours of work is wasteful"**
230 +Sunk cost fallacy. The time is already gone. Your choice now:
231 +- Delete and rewrite with TDD (X more hours, high confidence)
232 +- Keep it and add tests after (30 min, low confidence, likely bugs)
234 +The "waste" is keeping code you can't trust. Working code without real tests is technical debt.
236 +**"TDD is dogmatic, being pragmatic means adapting"**
238 +TDD IS pragmatic:
239 +- Finds bugs before commit (faster than debugging after)
240 +- Prevents regressions (tests catch breaks immediately)
241 +- Documents behavior (tests show how to use code)
242 +- Enables refactoring (change freely, tests catch breaks)
244 +"Pragmatic" shortcuts = debugging in production = slower.
246 +**"Tests after achieve the same goals - it's spirit not ritual"**
248 +No. Tests-after answer "What does this do?" Tests-first answer "What should this do?"
250 +Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.
252 +Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).
254 +30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.
256 +## Common Rationalizations
258 +| Excuse | Reality |
259 +|--------|---------|
260 +| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
261 +| "I'll test after" | Tests passing immediately prove nothing. |
262 +| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
263 +| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
264 +| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
265 +| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
266 +| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
267 +| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
268 +| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
269 +| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
270 +| "Existing code has no tests" | You're improving it. Add tests for existing code. |
272 +## Red Flags - STOP and Start Over
274 +- Code before test
275 +- Test after implementation
276 +- Test passes immediately
277 +- Can't explain why test failed
278 +- Tests added "later"
279 +- Rationalizing "just this once"
280 +- "I already manually tested it"
281 +- "Tests after achieve the same purpose"
282 +- "It's about spirit not ritual"
283 +- "Keep as reference" or "adapt existing code"
284 +- "Already spent X hours, deleting is wasteful"
285 +- "TDD is dogmatic, I'm being pragmatic"
286 +- "This is different because..."
288 +**All of these mean: Delete code. Start over with TDD.**
290 +## Example: Bug Fix
292 +**Bug:** Empty email accepted
294 +**RED**
295 +```typescript
296 +test('rejects empty email', async () => {
297 + const result = await submitForm({ email: '' });
298 + expect(result.error).toBe('Email required');
299 +});
300 +```
302 +**Verify RED**
303 +```bash
304 +$ npm test
305 +FAIL: expected 'Email required', got undefined
306 +```
308 +**GREEN**
309 +```typescript
310 +function submitForm(data: FormData) {
311 + if (!data.email?.trim()) {
312 + return { error: 'Email required' };
314 + // ...
316 +```
318 +**Verify GREEN**
319 +```bash
320 +$ npm test
321 +PASS
322 +```
324 +**REFACTOR**
325 +Extract validation for multiple fields if needed.
327 +## Verification Checklist
329 +Before marking work complete:
331 +- [ ] Every new function/method has a test
332 +- [ ] Watched each test fail before implementing
333 +- [ ] Each test failed for expected reason (feature missing, not typo)
334 +- [ ] Wrote minimal code to pass each test
335 +- [ ] All tests pass
336 +- [ ] Output pristine (no errors, warnings)
337 +- [ ] Tests use real code (mocks only if unavoidable)
338 +- [ ] Edge cases and errors covered
340 +Can't check all boxes? You skipped TDD. Start over.
342 +## When Stuck
344 +| Problem | Solution |
345 +|---------|----------|
346 +| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
347 +| Test too complicated | Design too complicated. Simplify interface. |
348 +| Must mock everything | Code too coupled. Use dependency injection. |
349 +| Test setup huge | Extract helpers. Still complex? Simplify design. |
351 +## Debugging Integration
353 +Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
355 +Never fix bugs without a test.
357 +## Testing Anti-Patterns
359 +When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:
360 +- Testing mock behavior instead of real behavior
361 +- Adding test-only methods to production classes
362 +- Mocking without understanding dependencies
364 +## Final Rule
366 +```
367 +Production code → test exists and failed first
368 +Otherwise → not TDD
369 +```
371 +No exceptions without your human partner's permission.

skills/super/test-driven-development/testing-anti-patterns.md

Added
new file mode 100644
1 +# Testing Anti-Patterns
3 +**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code.
5 +## Overview
7 +Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested.
9 +**Core principle:** Test what the code does, not what the mocks do.
11 +**Following strict TDD prevents these anti-patterns.**
13 +## The Iron Laws
15 +```
16 +1. NEVER test mock behavior
17 +2. NEVER add test-only methods to production classes
18 +3. NEVER mock without understanding dependencies
19 +```
21 +## Anti-Pattern 1: Testing Mock Behavior
23 +**The violation:**
24 +```typescript
25 +// ❌ BAD: Testing that the mock exists
26 +test('renders sidebar', () => {
27 + render(<Page />);
28 + expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();
29 +});
30 +```
32 +**Why this is wrong:**
33 +- You're verifying the mock works, not that the component works
34 +- Test passes when mock is present, fails when it's not
35 +- Tells you nothing about real behavior
37 +**your human partner's correction:** "Are we testing the behavior of a mock?"
39 +**The fix:**
40 +```typescript
41 +// ✅ GOOD: Test real component or don't mock it
42 +test('renders sidebar', () => {
43 + render(<Page />); // Don't mock sidebar
44 + expect(screen.getByRole('navigation')).toBeInTheDocument();
45 +});
47 +// OR if sidebar must be mocked for isolation:
48 +// Don't assert on the mock - test Page's behavior with sidebar present
49 +```
51 +### Gate Function
53 +```
54 +BEFORE asserting on any mock element:
55 + Ask: "Am I testing real component behavior or just mock existence?"
57 + IF testing mock existence:
58 + STOP - Delete the assertion or unmock the component
60 + Test real behavior instead
61 +```
63 +## Anti-Pattern 2: Test-Only Methods in Production
65 +**The violation:**
66 +```typescript
67 +// ❌ BAD: destroy() only used in tests
68 +class Session {
69 + async destroy() { // Looks like production API!
70 + await this._workspaceManager?.destroyWorkspace(this.id);
71 + // ... cleanup
72 + }
75 +// In tests
76 +afterEach(() => session.destroy());
77 +```
79 +**Why this is wrong:**
80 +- Production class polluted with test-only code
81 +- Dangerous if accidentally called in production
82 +- Violates YAGNI and separation of concerns
83 +- Confuses object lifecycle with entity lifecycle
85 +**The fix:**
86 +```typescript
87 +// ✅ GOOD: Test utilities handle test cleanup
88 +// Session has no destroy() - it's stateless in production
90 +// In test-utils/
91 +export async function cleanupSession(session: Session) {
92 + const workspace = session.getWorkspaceInfo();
93 + if (workspace) {
94 + await workspaceManager.destroyWorkspace(workspace.id);
95 + }
98 +// In tests
99 +afterEach(() => cleanupSession(session));
100 +```
102 +### Gate Function
104 +```
105 +BEFORE adding any method to production class:
106 + Ask: "Is this only used by tests?"
108 + IF yes:
109 + STOP - Don't add it
110 + Put it in test utilities instead
112 + Ask: "Does this class own this resource's lifecycle?"
114 + IF no:
115 + STOP - Wrong class for this method
116 +```
118 +## Anti-Pattern 3: Mocking Without Understanding
120 +**The violation:**
121 +```typescript
122 +// ❌ BAD: Mock breaks test logic
123 +test('detects duplicate server', () => {
124 + // Mock prevents config write that test depends on!
125 + vi.mock('ToolCatalog', () => ({
126 + discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)
127 + }));
129 + await addServer(config);
130 + await addServer(config); // Should throw - but won't!
131 +});
132 +```
134 +**Why this is wrong:**
135 +- Mocked method had side effect test depended on (writing config)
136 +- Over-mocking to "be safe" breaks actual behavior
137 +- Test passes for wrong reason or fails mysteriously
139 +**The fix:**
140 +```typescript
141 +// ✅ GOOD: Mock at correct level
142 +test('detects duplicate server', () => {
143 + // Mock the slow part, preserve behavior test needs
144 + vi.mock('MCPServerManager'); // Just mock slow server startup
146 + await addServer(config); // Config written
147 + await addServer(config); // Duplicate detected ✓
148 +});
149 +```
151 +### Gate Function
153 +```
154 +BEFORE mocking any method:
155 + STOP - Don't mock yet
157 + 1. Ask: "What side effects does the real method have?"
158 + 2. Ask: "Does this test depend on any of those side effects?"
159 + 3. Ask: "Do I fully understand what this test needs?"
161 + IF depends on side effects:
162 + Mock at lower level (the actual slow/external operation)
163 + OR use test doubles that preserve necessary behavior
164 + NOT the high-level method the test depends on
166 + IF unsure what test depends on:
167 + Run test with real implementation FIRST
168 + Observe what actually needs to happen
169 + THEN add minimal mocking at the right level
171 + Red flags:
172 + - "I'll mock this to be safe"
173 + - "This might be slow, better mock it"
174 + - Mocking without understanding the dependency chain
175 +```
177 +## Anti-Pattern 4: Incomplete Mocks
179 +**The violation:**
180 +```typescript
181 +// ❌ BAD: Partial mock - only fields you think you need
182 +const mockResponse = {
183 + status: 'success',
184 + data: { userId: '123', name: 'Alice' }
185 + // Missing: metadata that downstream code uses
188 +// Later: breaks when code accesses response.metadata.requestId
189 +```
191 +**Why this is wrong:**
192 +- **Partial mocks hide structural assumptions** - You only mocked fields you know about
193 +- **Downstream code may depend on fields you didn't include** - Silent failures
194 +- **Tests pass but integration fails** - Mock incomplete, real API complete
195 +- **False confidence** - Test proves nothing about real behavior
197 +**The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses.
199 +**The fix:**
200 +```typescript
201 +// ✅ GOOD: Mirror real API completeness
202 +const mockResponse = {
203 + status: 'success',
204 + data: { userId: '123', name: 'Alice' },
205 + metadata: { requestId: 'req-789', timestamp: 1234567890 }
206 + // All fields real API returns
208 +```
210 +### Gate Function
212 +```
213 +BEFORE creating mock responses:
214 + Check: "What fields does the real API response contain?"
216 + Actions:
217 + 1. Examine actual API response from docs/examples
218 + 2. Include ALL fields system might consume downstream
219 + 3. Verify mock matches real response schema completely
221 + Critical:
222 + If you're creating a mock, you must understand the ENTIRE structure
223 + Partial mocks fail silently when code depends on omitted fields
225 + If uncertain: Include all documented fields
226 +```
228 +## Anti-Pattern 5: Integration Tests as Afterthought
230 +**The violation:**
231 +```
232 +✅ Implementation complete
233 +❌ No tests written
234 +"Ready for testing"
235 +```
237 +**Why this is wrong:**
238 +- Testing is part of implementation, not optional follow-up
239 +- TDD would have caught this
240 +- Can't claim complete without tests
242 +**The fix:**
243 +```
244 +TDD cycle:
245 +1. Write failing test
246 +2. Implement to pass
247 +3. Refactor
248 +4. THEN claim complete
249 +```
251 +## When Mocks Become Too Complex
253 +**Warning signs:**
254 +- Mock setup longer than test logic
255 +- Mocking everything to make test pass
256 +- Mocks missing methods real components have
257 +- Test breaks when mock changes
259 +**your human partner's question:** "Do we need to be using a mock here?"
261 +**Consider:** Integration tests with real components often simpler than complex mocks
263 +## TDD Prevents These Anti-Patterns
265 +**Why TDD helps:**
266 +1. **Write test first** → Forces you to think about what you're actually testing
267 +2. **Watch it fail** → Confirms test tests real behavior, not mocks
268 +3. **Minimal implementation** → No test-only methods creep in
269 +4. **Real dependencies** → You see what the test actually needs before mocking
271 +**If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first.
273 +## Quick Reference
275 +| Anti-Pattern | Fix |
276 +|--------------|-----|
277 +| Assert on mock elements | Test real component or unmock it |
278 +| Test-only methods in production | Move to test utilities |
279 +| Mock without understanding | Understand dependencies first, mock minimally |
280 +| Incomplete mocks | Mirror real API completely |
281 +| Tests as afterthought | TDD - tests first |
282 +| Over-complex mocks | Consider integration tests |
284 +## Red Flags
286 +- Assertion checks for `*-mock` test IDs
287 +- Methods only called in test files
288 +- Mock setup is >50% of test
289 +- Test fails when you remove mock
290 +- Can't explain why mock is needed
291 +- Mocking "just to be safe"
293 +## The Bottom Line
295 +**Mocks are tools to isolate, not things to test.**
297 +If TDD reveals you're testing mock behavior, you've gone wrong.
299 +Fix: Test real behavior or question why you're mocking at all.

skills/super/verification-before-completion/SKILL.md

Added
new file mode 100644
1 +---
2 +name: verification-before-completion
3 +description: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always
4 +---
6 +# Verification Before Completion
8 +## Overview
10 +Claiming work is complete without verification is dishonesty, not efficiency.
12 +**Core principle:** Evidence before claims, always.
14 +**Violating the letter of this rule is violating the spirit of this rule.**
16 +## The Iron Law
18 +```
19 +NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE
20 +```
22 +If you haven't run the verification command in this message, you cannot claim it passes.
24 +## The Gate Function
26 +```
27 +BEFORE claiming any status or expressing satisfaction:
29 +1. IDENTIFY: What command proves this claim?
30 +2. RUN: Execute the FULL command (fresh, complete)
31 +3. READ: Full output, check exit code, count failures
32 +4. VERIFY: Does output confirm the claim?
33 + - If NO: State actual status with evidence
34 + - If YES: State claim WITH evidence
35 +5. ONLY THEN: Make the claim
37 +Skip any step = lying, not verifying
38 +```
40 +## Common Failures
42 +| Claim | Requires | Not Sufficient |
43 +|-------|----------|----------------|
44 +| Tests pass | Test command output: 0 failures | Previous run, "should pass" |
45 +| Linter clean | Linter output: 0 errors | Partial check, extrapolation |
46 +| Build succeeds | Build command: exit 0 | Linter passing, logs look good |
47 +| Bug fixed | Test original symptom: passes | Code changed, assumed fixed |
48 +| Regression test works | Red-green cycle verified | Test passes once |
49 +| Agent completed | VCS diff shows changes | Agent reports "success" |
50 +| Requirements met | Line-by-line checklist | Tests passing |
52 +## Red Flags - STOP
54 +- Using "should", "probably", "seems to"
55 +- Expressing satisfaction before verification ("Great!", "Perfect!", "Done!", etc.)
56 +- About to commit/push/PR without verification
57 +- Trusting agent success reports
58 +- Relying on partial verification
59 +- Thinking "just this once"
60 +- Tired and wanting work over
61 +- **ANY wording implying success without having run verification**
63 +## Rationalization Prevention
65 +| Excuse | Reality |
66 +|--------|---------|
67 +| "Should work now" | RUN the verification |
68 +| "I'm confident" | Confidence ≠ evidence |
69 +| "Just this once" | No exceptions |
70 +| "Linter passed" | Linter ≠ compiler |
71 +| "Agent said success" | Verify independently |
72 +| "I'm tired" | Exhaustion ≠ excuse |
73 +| "Partial check is enough" | Partial proves nothing |
74 +| "Different words so rule doesn't apply" | Spirit over letter |
76 +## Key Patterns
78 +**Tests:**
79 +```
80 +✅ [Run test command] [See: 34/34 pass] "All tests pass"
81 +❌ "Should pass now" / "Looks correct"
82 +```
84 +**Regression tests (TDD Red-Green):**
85 +```
86 +✅ Write → Run (pass) → Revert fix → Run (MUST FAIL) → Restore → Run (pass)
87 +❌ "I've written a regression test" (without red-green verification)
88 +```
90 +**Build:**
91 +```
92 +✅ [Run build] [See: exit 0] "Build passes"
93 +❌ "Linter passed" (linter doesn't check compilation)
94 +```
96 +**Requirements:**
97 +```
98 +✅ Re-read plan → Create checklist → Verify each → Report gaps or completion
99 +❌ "Tests pass, phase complete"
100 +```
102 +**Agent delegation:**
103 +```
104 +✅ Agent reports success → Check VCS diff → Verify changes → Report actual state
105 +❌ Trust agent report
106 +```
108 +## Why This Matters
110 +From 24 failure memories:
111 +- your human partner said "I don't believe you" - trust broken
112 +- Undefined functions shipped - would crash
113 +- Missing requirements shipped - incomplete features
114 +- Time wasted on false completion → redirect → rework
115 +- Violates: "Honesty is a core value. If you lie, you'll be replaced."
117 +## When To Apply
119 +**ALWAYS before:**
120 +- ANY variation of success/completion claims
121 +- ANY expression of satisfaction
122 +- ANY positive statement about work state
123 +- Committing, PR creation, task completion
124 +- Moving to next task
125 +- Delegating to agents
127 +**Rule applies to:**
128 +- Exact phrases
129 +- Paraphrases and synonyms
130 +- Implications of success
131 +- ANY communication suggesting completion/correctness
133 +## The Bottom Line
135 +**No shortcuts for verification.**
137 +Run the command. Read the output. THEN claim the result.
139 +This is non-negotiable.

skills/super/writing-plans/SKILL.md

Added
new file mode 100644
1 +---
2 +name: writing-plans
3 +description: Use when you have a spec, requirements, or selected roadmap phase for a multi-step task, before touching code
4 +---
6 +# Writing Plans
8 +## Overview
10 +Write comprehensive implementation plans assuming the engineer has zero context for our codebase and questionable taste. Document everything they need to know: which files to touch for each task, code, testing, docs they might need to check, how to test it. Give them the whole plan as bite-sized tasks. DRY. YAGNI. TDD. Frequent commits.
12 +Assume they are a skilled developer, but know almost nothing about our toolset or problem domain. Assume they don't know good test design very well.
14 +**Announce at start:** "I'm using the writing-plans skill to create the implementation plan."
17 +**Save plans to:** `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`
18 +- For roadmap phases: `docs/superpowers/plans/YYYY-MM-DD-<feature-name>-phase-N-<phase-name>.md`
19 +- (User preferences for plan location override this default)
21 +## Scope Check
23 +**Roadmap-aware planning:** If a roadmap exists, write a detailed implementation plan for exactly one selected phase. Default to Phase 1, or the next sequential unplanned phase if earlier phase plans already exist. Do not combine phases unless the user explicitly asks. Read the roadmap, identify the target phase in the plan header, and treat other phases as out of scope. If the target phase is unclear, ask before planning.
25 +Each phase plan must leave the project in a sensible intermediate state after execution: functionality not broken, tests/CI expected green, and no half-migrations or dangling integrations.
27 +If the spec covers multiple independent subsystems, it should have been broken into sub-project specs or a multi-phase roadmap during brainstorming. If it wasn't, suggest breaking this into separate plans or creating a roadmap first. Each plan should produce working, testable software on its own.
29 +## File Structure
31 +Before defining tasks, map out which files will be created or modified and what each one is responsible for. This is where decomposition decisions get locked in.
33 +- Design units with clear boundaries and well-defined interfaces. Each file should have one clear responsibility.
34 +- You reason best about code you can hold in context at once, and your edits are more reliable when files are focused. Prefer smaller, focused files over large ones that do too much.
35 +- Files that change together should live together. Split by responsibility, not by technical layer.
36 +- In existing codebases, follow established patterns. If the codebase uses large files, don't unilaterally restructure - but if a file you're modifying has grown unwieldy, including a split in the plan is reasonable.
38 +This structure informs the task decomposition. Each task should produce self-contained changes that make sense independently.
40 +## Bite-Sized Task Granularity
42 +**Each step is one action (2-5 minutes):**
43 +- "Write the failing test" - step
44 +- "Run it to make sure it fails" - step
45 +- "Implement the minimal code to make the test pass" - step
46 +- "Run the tests and make sure they pass" - step
47 +- "Commit" - step
49 +## Plan Document Header
51 +**Every plan MUST start with this header:**
53 +```markdown
54 +# [Feature Name] Implementation Plan
56 +> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
58 +**Goal:** [One sentence describing what this builds]
60 +**Architecture:** [2-3 sentences about approach]
62 +**Tech Stack:** [Key technologies/libraries]
64 +**Roadmap:** [Path to roadmap, or "None"]
66 +**Phase:** [Phase N: Name, or "Single-plan implementation"]
68 +---
69 +```
71 +## Task Structure
73 +````markdown
74 +### Task N: [Component Name]
76 +**Files:**
77 +- Create: `exact/path/to/file.py`
78 +- Modify: `exact/path/to/existing.py:123-145`
79 +- Test: `tests/exact/path/to/test.py`
81 +- [ ] **Step 1: Write the failing test**
83 +```python
84 +def test_specific_behavior():
85 + result = function(input)
86 + assert result == expected
87 +```
89 +- [ ] **Step 2: Run test to verify it fails**
91 +Run: `pytest tests/path/test.py::test_name -v`
92 +Expected: FAIL with "function not defined"
94 +- [ ] **Step 3: Write minimal implementation**
96 +```python
97 +def function(input):
98 + return expected
99 +```
101 +- [ ] **Step 4: Run test to verify it passes**
103 +Run: `pytest tests/path/test.py::test_name -v`
104 +Expected: PASS
106 +- [ ] **Step 5: Commit**
108 +```bash
109 +git add tests/path/test.py src/path/file.py
110 +git commit -m "feat: add specific feature"
111 +```
112 +````
114 +## No Placeholders
116 +Every step must contain the actual content an engineer needs. These are **plan failures** — never write them:
117 +- "TBD", "TODO", "implement later", "fill in details"
118 +- "Add appropriate error handling" / "add validation" / "handle edge cases"
119 +- "Write tests for the above" (without actual test code)
120 +- "Similar to Task N" (repeat the code — the engineer may be reading tasks out of order)
121 +- Steps that describe what to do without showing how (code blocks required for code steps)
122 +- References to types, functions, or methods not defined in any task
124 +## Remember
125 +- Exact file paths always
126 +- Complete code in every step — if a step changes code, show the code
127 +- Exact commands with expected output
128 +- DRY, YAGNI, TDD, frequent commits
130 +## Self-Review
132 +After writing the complete plan, use the `push-task` tool with `plan-document-reviewer-prompt.md` to request a fresh-context plan review. Act on the returned task result when you get it, then check the plan against the spec.
134 +**1. Spec/roadmap coverage:** Skim each section/requirement in the spec. Can you point to a task that implements it? If working from a roadmap, confirm this plan covers the selected phase and excludes later phases. List any gaps.
136 +**2. Placeholder scan:** Search your plan for red flags — any of the patterns from the "No Placeholders" section above. Fix them.
138 +**3. Type consistency:** Do the types, method signatures, and property names you used in later tasks match what you defined in earlier tasks? A function called `clearLayers()` in Task 3 but `clearFullLayers()` in Task 7 is a bug.
140 +**4. Phase boundary health:** If working from a roadmap, will executing this phase leave the project functional, coherent, and expected-green without half-migrations or dangling integrations? If not, reshape the plan before saving.
142 +If you find issues, fix them inline. No need to re-review — just fix and move on. If you find a spec requirement with no task, add the task.
144 +## Execution Handoff
146 +After saving the plan, offer execution with phase-boundary clarity:
148 +**"Plan complete and saved to `docs/superpowers/plans/<filename>.md`. Ready to execute it using /skill:executing-plans?"**
150 +If this plan covers a roadmap phase, add:
152 +**"This plan intentionally stops at `[Phase N: Name]`. Future roadmap phases need separate detailed plans."**
154 +**If execution chosen:**
155 +- **REQUIRED SUB-SKILL:** Use /skill:executing-plans
156 +- Batch execution with checkpoints for review

skills/super/writing-plans/plan-document-reviewer-prompt.md

Added
new file mode 100644
1 +# Plan Document Reviewer Prompt Template
3 +Use this template when dispatching a plan document reviewer task.
5 +**Purpose:** Verify the plan is complete, matches the spec, and has proper task decomposition.
7 +**Dispatch after:** The complete plan is written.
9 +```
10 +push-task:
11 + prompt: |
12 + You are a plan document reviewer. Verify this plan is complete and ready for implementation.
14 + **Plan to review:** [PLAN_FILE_PATH]
15 + **Spec for reference:** [SPEC_FILE_PATH]
17 + ## What to Check
19 + | Category | What to Look For |
20 + |----------|------------------|
21 + | Completeness | TODOs, placeholders, incomplete tasks, missing steps |
22 + | Spec Alignment | Plan covers spec requirements, no major scope creep |
23 + | Task Decomposition | Tasks have clear boundaries, steps are actionable |
24 + | Buildability | Could an engineer follow this plan without getting stuck? |
26 + ## Calibration
28 + **Only flag issues that would cause real problems during implementation.**
29 + An implementer building the wrong thing or getting stuck is an issue.
30 + Minor wording, stylistic preferences, and "nice to have" suggestions are not.
32 + Approve unless there are serious gaps — missing requirements from the spec,
33 + contradictory steps, placeholder content, or tasks so vague they can't be acted on.
35 + ## Output Format
37 + ## Plan Review
39 + **Status:** Approved | Issues Found
41 + **Issues (if any):**
42 + - [Task X, Step Y]: [specific issue] - [why it matters for implementation]
44 + **Recommendations (advisory, do not block approval):**
45 + - [suggestions for improvement]
46 +```
48 +**Reviewer returns:** Status, Issues (if any), Recommendations

skills/super/writing-roadmaps/SKILL.md

Added
new file mode 100644
1 +---
2 +name: writing-roadmaps
3 +description: Use when an approved design or spec is too large for one implementation plan, needs ordered phases, or may exceed a single context window
4 +---
6 +# Writing Roadmaps
8 +## Overview
10 +Create a coarse, phase-level roadmap between brainstorming and detailed planning. The roadmap divides a large approved design into ordered, independently plannable phases so each phase can later get its own `writing-plans` document.
12 +**Announce at start:** "I'm using the writing-roadmaps skill to break this design into implementation phases."
14 +**Save roadmaps to:** `docs/superpowers/roadmaps/YYYY-MM-DD-<feature-name>-roadmap.md`
15 +- User preferences for roadmap location override this default.
17 +## When to Use
19 +Use this after a design/spec is approved when any of these are true:
21 +- The work likely will not fit in one context window as a detailed implementation plan.
22 +- The design has multiple phases, migrations, subsystems, or rollout steps.
23 +- The first detailed plan would be too large to write or execute safely in one session.
24 +- You need ordering, dependency, or risk decisions before writing task-level steps.
26 +Skip this for small designs that can become one detailed implementation plan.
28 +## Roadmap Rules
30 +- Stay coarse: phases, goals, dependencies, risks, context boundaries, and verification only.
31 +- Do not write task-level implementation steps or full code blocks.
32 +- Phases are executed in order starting with Phase 1 unless the user explicitly changes the order.
33 +- Each phase must be independently plan-worthy and small enough for one detailed `writing-plans` document.
34 +- Use as many phases as needed, but no more than needed.
35 +- Split any phase that cannot fit comfortably in one detailed plan or context window.
37 +## Phase Boundary Rule
39 +Each phase must leave the project in a sensible intermediate state:
41 +- functionality is not broken
42 +- tests and CI are expected to be green
43 +- no half-migrations, dangling integrations, or unusable transitional states remain
44 +- later phases may add capability, but earlier phases remain coherent on their own
46 +If a proposed phase cannot satisfy this rule, split or reshape it before writing the roadmap.
48 +## Roadmap Document Header
50 +Every roadmap MUST start with this header:
52 +```markdown
53 +# [Feature Name] Roadmap
55 +> **For agentic workers:** Use /skill:writing-plans to create one detailed implementation plan per phase. Start with Phase 1 and proceed sequentially unless the user explicitly changes the order.
57 +**Goal:** [One sentence describing the full outcome]
59 +**Design Spec:** [`docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`](../specs/YYYY-MM-DD-<topic>-design.md)
61 +**Planning Strategy:** [Why this needs multiple phases and how the phases protect context limits]
63 +---
64 +```
66 +## Phase Format
68 +Use this structure for each phase:
70 +```markdown
71 +## Phase N: [Phase Name]
73 +**Outcome:** [What exists when this phase is complete]
75 +**Why now:** [Dependency/order rationale]
77 +**Scope:**
78 +- [Included capability/change]
79 +- [Included capability/change]
81 +**Out of scope:**
82 +- [Deferred capability/change]
84 +**Key files/areas likely affected:**
85 +- `path/or/area`: [reason]
87 +**Dependencies:**
88 +- [Prior phase, external decision, migration, or none]
90 +**Verification:**
91 +- [Coarse acceptance check]
92 +- [Test/build/manual check]
94 +**Phase boundary health:** [Why the project remains functional and tests/CI should be green after this phase]
96 +**Risks:**
97 +- [Risk and mitigation]
99 +**Context notes:** [What to keep in mind when writing this phase's detailed plan]
100 +```
102 +## Self-Review
104 +Before handing off, check:
106 +1. **Complete coverage:** Every important spec requirement appears in a phase, or is explicitly deferred.
107 +2. **Sequential order:** Phase 1 is the correct first implementation target, and each later phase depends only on earlier phases or stated external decisions.
108 +3. **Phase boundaries:** Every phase leaves the project functional, coherent, and expected-green.
109 +4. **Size check:** Each phase can plausibly fit in one detailed `writing-plans` document.
110 +5. **No detailed-plan leakage:** Remove task-level checkboxes, full implementations, and step-by-step code.
112 +Fix issues inline before presenting the roadmap.
114 +## Handoff
116 +After saving the roadmap, say:
118 +> "Roadmap complete and saved to `<path>`. Next step is to use /skill:writing-plans for Phase 1."
120 +Do not skip ahead to later phases unless the user explicitly changes the phase order.

skills/super/writing-skills/SKILL.md

Added
new file mode 100644
1 +---
2 +name: writing-skills
3 +description: Use when creating new skills, editing existing skills, or verifying skills work before deployment
4 +---
6 +# Writing Skills
8 +## Overview
10 +**Writing skills IS Test-Driven Development applied to process documentation.**
12 +**Personal skills live in agent-specific directories (`~/.pi/skills` for Pi, `~/.agents/skills/` for Codex)**
14 +You write test cases (pressure scenarios with push-task), watch them fail (baseline behavior), write the skill (documentation), watch tests pass (agents comply), and refactor (close loopholes).
16 +**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill teaches the right thing.
18 +**REQUIRED BACKGROUND:** You MUST understand /skill:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill adapts TDD to documentation.
20 +**Official guidance:** For Anthropic's official skill authoring best practices, see anthropic-best-practices.md. This document provides additional patterns and guidelines that complement the TDD-focused approach in this skill.
22 +## What is a Skill?
24 +A **skill** is a reference guide for proven techniques, patterns, or tools. Skills help future agent instances find and apply effective approaches.
26 +**Skills are:** Reusable techniques, patterns, tools, reference guides
28 +**Skills are NOT:** Narratives about how you solved a problem once
30 +## TDD Mapping for Skills
32 +| TDD Concept | Skill Creation |
33 +|-------------|----------------|
34 +| **Test case** | Pressure scenario with agent behavior |
35 +| **Production code** | Skill document (SKILL.md) |
36 +| **Test fails (RED)** | Agent violates rule without skill (baseline) |
37 +| **Test passes (GREEN)** | Agent complies with skill present |
38 +| **Refactor** | Close loopholes while maintaining compliance |
39 +| **Write test first** | Run baseline scenario BEFORE writing skill |
40 +| **Watch it fail** | Document exact rationalizations agent uses |
41 +| **Minimal code** | Write skill addressing those specific violations |
42 +| **Watch it pass** | Verify agent now complies |
43 +| **Refactor cycle** | Find new rationalizations → plug → re-verify |
45 +The entire skill creation process follows RED-GREEN-REFACTOR.
47 +## When to Create a Skill
49 +**Create when:**
50 +- Technique wasn't intuitively obvious to you
51 +- You'd reference this again across projects
52 +- Pattern applies broadly (not project-specific)
53 +- Others would benefit
55 +**Don't create for:**
56 +- One-off solutions
57 +- Standard practices well-documented elsewhere
58 +- Project-specific conventions (put in CLAUDE.md)
59 +- Mechanical constraints (if it's enforceable with regex/validation, automate it—save documentation for judgment calls)
61 +## Skill Types
63 +### Technique
64 +Concrete method with steps to follow (condition-based-waiting, root-cause-tracing)
66 +### Pattern
67 +Way of thinking about problems (flatten-with-flags, test-invariants)
69 +### Reference
70 +API docs, syntax guides, tool documentation (office docs)
72 +## Directory Structure
75 +```
76 +skills/
77 + skill-name/
78 + SKILL.md # Main reference (required)
79 + supporting-file.* # Only if needed
80 +```
82 +**Flat namespace** - all skills in one searchable namespace
84 +**Separate files for:**
85 +1. **Heavy reference** (100+ lines) - API docs, comprehensive syntax
86 +2. **Reusable tools** - Scripts, utilities, templates
88 +**Keep inline:**
89 +- Principles and concepts
90 +- Code patterns (< 50 lines)
91 +- Everything else
93 +## SKILL.md Structure
95 +**Frontmatter (YAML):**
96 +- Two required fields: `name` and `description` (see [agentskills.io/specification](https://agentskills.io/specification) for all supported fields)
97 +- Max 1024 characters total
98 +- `name`: Use letters, numbers, and hyphens only (no parentheses, special chars)
99 +- `description`: Third-person, describes ONLY when to use (NOT what it does)
100 + - Start with "Use when..." to focus on triggering conditions
101 + - Include specific symptoms, situations, and contexts
102 + - **NEVER summarize the skill's process or workflow** (see CSO section for why)
103 + - Keep under 500 characters if possible
105 +```markdown
106 +---
107 +name: Skill-Name-With-Hyphens
108 +description: Use when [specific triggering conditions and symptoms]
109 +---
111 +# Skill Name
113 +## Overview
114 +What is this? Core principle in 1-2 sentences.
116 +## When to Use
117 +[Small inline flowchart IF decision non-obvious]
119 +Bullet list with SYMPTOMS and use cases
120 +When NOT to use
122 +## Core Pattern (for techniques/patterns)
123 +Before/after code comparison
125 +## Quick Reference
126 +Table or bullets for scanning common operations
128 +## Implementation
129 +Inline code for simple patterns
130 +Link to file for heavy reference or reusable tools
132 +## Common Mistakes
133 +What goes wrong + fixes
135 +## Real-World Impact (optional)
136 +Concrete results
137 +```
140 +## Agent Search Optimization (CSO)
142 +**Critical for discovery:** The agent needs to FIND your skill
144 +### 1. Rich Description Field
146 +**Purpose:** The agent reads description to decide which skills to load for a given task. Make it answer: "Should I read this skill right now?"
148 +**Format:** Start with "Use when..." to focus on triggering conditions
150 +**CRITICAL: Description = When to Use, NOT What the Skill Does**
152 +The description should ONLY describe triggering conditions. Do NOT summarize the skill's process or workflow in the description.
154 +**Why this matters:** Testing revealed that when a description summarizes the skill's workflow, the agent may follow the description instead of reading the full skill content. A description saying "code review between tasks" caused the agent to do ONE review, even though the skill's flowchart clearly showed TWO reviews (spec compliance then code quality).
156 +When the description was changed to just "Use when executing implementation plans with independent tasks" (no workflow summary), the agent correctly read the flowchart and followed the two-stage review process.
158 +**The trap:** Descriptions that summarize workflow create a shortcut the agent will take. The skill body becomes documentation the agent skips.
160 +```yaml
161 +# ❌ BAD: Summarizes workflow - the agent may follow this instead of reading skill
162 +description: Use when executing plans - dispatches subagent per task with code review between tasks
164 +# ❌ BAD: Too much process detail
165 +description: Use for TDD - write test first, watch it fail, write minimal code, refactor
167 +# ✅ GOOD: Just triggering conditions, no workflow summary
168 +description: Use when executing implementation plans with independent tasks in the current session
170 +# ✅ GOOD: Triggering conditions only
171 +description: Use when implementing any feature or bugfix, before writing implementation code
172 +```
174 +**Content:**
175 +- Use concrete triggers, symptoms, and situations that signal this skill applies
176 +- Describe the *problem* (race conditions, inconsistent behavior) not *language-specific symptoms* (setTimeout, sleep)
177 +- Keep triggers technology-agnostic unless the skill itself is technology-specific
178 +- If skill is technology-specific, make that explicit in the trigger
179 +- Write in third person (injected into system prompt)
180 +- **NEVER summarize the skill's process or workflow**
182 +```yaml
183 +# ❌ BAD: Too abstract, vague, doesn't include when to use
184 +description: For async testing
186 +# ❌ BAD: First person
187 +description: I can help you with async tests when they're flaky
189 +# ❌ BAD: Mentions technology but skill isn't specific to it
190 +description: Use when tests use setTimeout/sleep and are flaky
192 +# ✅ GOOD: Starts with "Use when", describes problem, no workflow
193 +description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently
195 +# ✅ GOOD: Technology-specific skill with explicit trigger
196 +description: Use when using React Router and handling authentication redirects
197 +```
199 +### 2. Keyword Coverage
201 +Use words an LLM would search for:
202 +- Error messages: "Hook timed out", "ENOTEMPTY", "race condition"
203 +- Symptoms: "flaky", "hanging", "zombie", "pollution"
204 +- Synonyms: "timeout/hang/freeze", "cleanup/teardown/afterEach"
205 +- Tools: Actual commands, library names, file types
207 +### 3. Descriptive Naming
209 +**Use active voice, verb-first:**
210 +- ✅ `creating-skills` not `skill-creation`
211 +- ✅ `condition-based-waiting` not `async-test-helpers`
213 +### 4. Token Efficiency (Critical)
215 +**Problem:** getting-started and frequently-referenced skills load into EVERY conversation. Every token counts.
217 +**Target word counts:**
218 +- getting-started workflows: <150 words each
219 +- Frequently-loaded skills: <200 words total
220 +- Other skills: <500 words (still be concise)
222 +**Techniques:**
224 +**Move details to tool help:**
225 +```bash
226 +# ❌ BAD: Document all flags in SKILL.md
227 +search-conversations supports --text, --both, --after DATE, --before DATE, --limit N
229 +# ✅ GOOD: Reference --help
230 +search-conversations supports multiple modes and filters. Run --help for details.
231 +```
233 +**Use cross-references:**
234 +```markdown
235 +# ❌ BAD: Repeat workflow details
236 +When searching, dispatch subagent with template...
237 +[20 lines of repeated instructions]
239 +# ✅ GOOD: Reference other skill
240 +Use push-task for fresh-context work (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.
241 +```
243 +**Compress examples:**
244 +```markdown
245 +# ❌ BAD: Verbose example (42 words)
246 +your human partner: "How did we handle authentication errors in React Router before?"
247 +You: I'll search past conversations for React Router authentication patterns.
248 +[Dispatch subagent with search query: "React Router authentication error handling 401"]
250 +# ✅ GOOD: Minimal example (20 words)
251 +Partner: "How did we handle auth errors in React Router?"
252 +You: Searching...
253 +[push-task → synthesis]
254 +```
256 +**Eliminate redundancy:**
257 +- Don't repeat what's in cross-referenced skills
258 +- Don't explain what's obvious from command
259 +- Don't include multiple examples of same pattern
261 +**Verification:**
262 +```bash
263 +wc -w skills/path/SKILL.md
264 +# getting-started workflows: aim for <150 each
265 +# Other frequently-loaded: aim for <200 total
266 +```
268 +**Name by what you DO or core insight:**
269 +- ✅ `condition-based-waiting` > `async-test-helpers`
270 +- ✅ `using-skills` not `skill-usage`
271 +- ✅ `flatten-with-flags` > `data-structure-refactoring`
272 +- ✅ `root-cause-tracing` > `debugging-techniques`
274 +**Gerunds (-ing) work well for processes:**
275 +- `creating-skills`, `testing-skills`, `debugging-with-logs`
276 +- Active, describes the action you're taking
278 +### 4. Cross-Referencing Other Skills
280 +**When writing documentation that references other skills:**
282 +Use skill name only, with explicit requirement markers:
283 +- ✅ Good: `**REQUIRED SUB-SKILL:** Use /skill:test-driven-development`
284 +- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand /skill:systematic-debugging`
285 +- ❌ Bad: `See skills/testing/test-driven-development` (unclear if required)
286 +- ❌ Bad: `@skills/testing/test-driven-development/SKILL.md` (force-loads, burns context)
288 +**Why no @ links:** `@` syntax force-loads files immediately, consuming 200k+ context before you need them.
290 +## Flowchart Usage
292 +```dot
293 +digraph when_flowchart {
294 + "Need to show information?" [shape=diamond];
295 + "Decision where I might go wrong?" [shape=diamond];
296 + "Use markdown" [shape=box];
297 + "Small inline flowchart" [shape=box];
299 + "Need to show information?" -> "Decision where I might go wrong?" [label="yes"];
300 + "Decision where I might go wrong?" -> "Small inline flowchart" [label="yes"];
301 + "Decision where I might go wrong?" -> "Use markdown" [label="no"];
303 +```
305 +**Use flowcharts ONLY for:**
306 +- Non-obvious decision points
307 +- Process loops where you might stop too early
308 +- "When to use A vs B" decisions
310 +**Never use flowcharts for:**
311 +- Reference material → Tables, lists
312 +- Code examples → Markdown blocks
313 +- Linear instructions → Numbered lists
314 +- Labels without semantic meaning (step1, helper2)
316 +See @graphviz-conventions.dot for graphviz style rules.
318 +**Visualizing for your human partner:** Use `render-graphs.js` in this directory to render a skill's flowcharts to SVG:
319 +```bash
320 +./render-graphs.js ../some-skill # Each diagram separately
321 +./render-graphs.js ../some-skill --combine # All diagrams in one SVG
322 +```
324 +## Code Examples
326 +**One excellent example beats many mediocre ones**
328 +Choose most relevant language:
329 +- Testing techniques → TypeScript/JavaScript
330 +- System debugging → Shell/Python
331 +- Data processing → Python
333 +**Good example:**
334 +- Complete and runnable
335 +- Well-commented explaining WHY
336 +- From real scenario
337 +- Shows pattern clearly
338 +- Ready to adapt (not generic template)
340 +**Don't:**
341 +- Implement in 5+ languages
342 +- Create fill-in-the-blank templates
343 +- Write contrived examples
345 +You're good at porting - one great example is enough.
347 +## File Organization
349 +### Self-Contained Skill
350 +```
351 +defense-in-depth/
352 + SKILL.md # Everything inline
353 +```
354 +When: All content fits, no heavy reference needed
356 +### Skill with Reusable Tool
357 +```
358 +condition-based-waiting/
359 + SKILL.md # Overview + patterns
360 + example.ts # Working helpers to adapt
361 +```
362 +When: Tool is reusable code, not just narrative
364 +### Skill with Heavy Reference
365 +```
366 +pptx/
367 + SKILL.md # Overview + workflows
368 + pptxgenjs.md # 600 lines API reference
369 + ooxml.md # 500 lines XML structure
370 + scripts/ # Executable tools
371 +```
372 +When: Reference material too large for inline
374 +## The Iron Law (Same as TDD)
376 +```
377 +NO SKILL WITHOUT A FAILING TEST FIRST
378 +```
380 +This applies to NEW skills AND EDITS to existing skills.
382 +Write skill before testing? Delete it. Start over.
383 +Edit skill without testing? Same violation.
385 +**No exceptions:**
386 +- Not for "simple additions"
387 +- Not for "just adding a section"
388 +- Not for "documentation updates"
389 +- Don't keep untested changes as "reference"
390 +- Don't "adapt" while running tests
391 +- Delete means delete
393 +**REQUIRED BACKGROUND:** The /skill:test-driven-development skill explains why this matters. Same principles apply to documentation.
395 +## Testing All Skill Types
397 +Different skill types need different test approaches:
399 +### Discipline-Enforcing Skills (rules/requirements)
401 +**Examples:** TDD, verification-before-completion, designing-before-coding
403 +**Test with:**
404 +- Academic questions: Do they understand the rules?
405 +- Pressure scenarios: Do they comply under stress?
406 +- Multiple pressures combined: time + sunk cost + exhaustion
407 +- Identify rationalizations and add explicit counters
409 +**Success criteria:** Agent follows rule under maximum pressure
411 +### Technique Skills (how-to guides)
413 +**Examples:** condition-based-waiting, root-cause-tracing, defensive-programming
415 +**Test with:**
416 +- Application scenarios: Can they apply the technique correctly?
417 +- Variation scenarios: Do they handle edge cases?
418 +- Missing information tests: Do instructions have gaps?
420 +**Success criteria:** Agent successfully applies technique to new scenario
422 +### Pattern Skills (mental models)
424 +**Examples:** reducing-complexity, information-hiding concepts
426 +**Test with:**
427 +- Recognition scenarios: Do they recognize when pattern applies?
428 +- Application scenarios: Can they use the mental model?
429 +- Counter-examples: Do they know when NOT to apply?
431 +**Success criteria:** Agent correctly identifies when/how to apply pattern
433 +### Reference Skills (documentation/APIs)
435 +**Examples:** API documentation, command references, library guides
437 +**Test with:**
438 +- Retrieval scenarios: Can they find the right information?
439 +- Application scenarios: Can they use what they found correctly?
440 +- Gap testing: Are common use cases covered?
442 +**Success criteria:** Agent finds and correctly applies reference information
444 +## Common Rationalizations for Skipping Testing
446 +| Excuse | Reality |
447 +|--------|---------|
448 +| "Skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
449 +| "It's just a reference" | References can have gaps, unclear sections. Test retrieval. |
450 +| "Testing is overkill" | Untested skills have issues. Always. 15 min testing saves hours. |
451 +| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
452 +| "Too tedious to test" | Testing is less tedious than debugging bad skill in production. |
453 +| "I'm confident it's good" | Overconfidence guarantees issues. Test anyway. |
454 +| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
455 +| "No time to test" | Deploying untested skill wastes more time fixing it later. |
457 +**All of these mean: Test before deploying. No exceptions.**
459 +## Bulletproofing Skills Against Rationalization
461 +Skills that enforce discipline (like TDD) need to resist rationalization. Agents are smart and will find loopholes when under pressure.
463 +**Psychology note:** Understanding WHY persuasion techniques work helps you apply them systematically. See persuasion-principles.md for research foundation (Cialdini, 2021; Meincke et al., 2025) on authority, commitment, scarcity, social proof, and unity principles.
465 +### Close Every Loophole Explicitly
467 +Don't just state the rule - forbid specific workarounds:
469 +<Bad>
470 +```markdown
471 +Write code before test? Delete it.
472 +```
473 +</Bad>
475 +<Good>
476 +```markdown
477 +Write code before test? Delete it. Start over.
479 +**No exceptions:**
480 +- Don't keep it as "reference"
481 +- Don't "adapt" it while writing tests
482 +- Don't look at it
483 +- Delete means delete
484 +```
485 +</Good>
487 +### Address "Spirit vs Letter" Arguments
489 +Add foundational principle early:
491 +```markdown
492 +**Violating the letter of the rules is violating the spirit of the rules.**
493 +```
495 +This cuts off entire class of "I'm following the spirit" rationalizations.
497 +### Build Rationalization Table
499 +Capture rationalizations from baseline testing (see Testing section below). Every excuse agents make goes in the table:
501 +```markdown
502 +| Excuse | Reality |
503 +|--------|---------|
504 +| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
505 +| "I'll test after" | Tests passing immediately prove nothing. |
506 +| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
507 +```
509 +### Create Red Flags List
511 +Make it easy for agents to self-check when rationalizing:
513 +```markdown
514 +## Red Flags - STOP and Start Over
516 +- Code before test
517 +- "I already manually tested it"
518 +- "Tests after achieve the same purpose"
519 +- "It's about spirit not ritual"
520 +- "This is different because..."
522 +**All of these mean: Delete code. Start over with TDD.**
523 +```
525 +### Update CSO for Violation Symptoms
527 +Add to description: symptoms of when you're ABOUT to violate the rule:
529 +```yaml
530 +description: use when implementing any feature or bugfix, before writing implementation code
531 +```
533 +## RED-GREEN-REFACTOR for Skills
535 +Follow the TDD cycle:
537 +### RED: Write Failing Test (Baseline)
539 +Use the `push-task` tool to run the pressure scenario without the skill. Act on the returned task result when you get it. Document exact behavior:
540 +- What choices did they make?
541 +- What rationalizations did they use (verbatim)?
542 +- Which pressures triggered violations?
544 +This is "watch the test fail" - you must see what agents naturally do before writing the skill.
546 +### GREEN: Write Minimal Skill
548 +Write skill that addresses those specific rationalizations. Don't add extra content for hypothetical cases.
550 +Run same scenarios WITH skill. Agent should now comply.
552 +Use the `push-task` tool to run the same scenario with the skill loaded. Act on the returned task result when you get it, then confirm compliance.
554 +### REFACTOR: Close Loopholes
556 +Agent found a new rationalization? Add an explicit counter. Use the `push-task` tool to re-test with the updated scenario and skill, then act on the returned task result when you get it. Re-test until bulletproof.
558 +**Testing methodology:** See @testing-skills-with-subagents.md for the complete testing methodology (filename references a legacy term; content uses current navigator terminology):
559 +- How to write pressure scenarios
560 +- Pressure types (time, sunk cost, authority, exhaustion)
561 +- Plugging holes systematically
562 +- Meta-testing techniques
564 +## Anti-Patterns
566 +### ❌ Narrative Example
567 +"In session 2025-10-03, we found empty projectDir caused..."
568 +**Why bad:** Too specific, not reusable
570 +### ❌ Multi-Language Dilution
571 +example-js.js, example-py.py, example-go.go
572 +**Why bad:** Mediocre quality, maintenance burden
574 +### ❌ Code in Flowcharts
575 +```dot
576 +step1 [label="import fs"];
577 +step2 [label="read file"];
578 +```
579 +**Why bad:** Can't copy-paste, hard to read
581 +### ❌ Generic Labels
582 +helper1, helper2, step3, pattern4
583 +**Why bad:** Labels should have semantic meaning
585 +## STOP: Before Moving to Next Skill
587 +**After writing ANY skill, you MUST STOP and complete the deployment process.**
589 +**Do NOT:**
590 +- Create multiple skills in batch without testing each
591 +- Move to next skill before current one is verified
592 +- Skip testing because "batching is more efficient"
594 +**The deployment checklist below is MANDATORY for EACH skill.**
596 +Deploying untested skills = deploying untested code. It's a violation of quality standards.
598 +## Skill Creation Checklist (TDD Adapted)
600 +**IMPORTANT: Use a todo list to create todos for EACH checklist item below.**
602 +**RED Phase - Write Failing Test:**
603 +- [ ] Create pressure scenarios (3+ combined pressures for discipline skills)
604 +- [ ] Run scenarios WITHOUT skill - document baseline behavior verbatim
605 +- [ ] Identify patterns in rationalizations/failures
607 +**GREEN Phase - Write Minimal Skill:**
608 +- [ ] Name uses only letters, numbers, hyphens (no parentheses/special chars)
609 +- [ ] YAML frontmatter with required `name` and `description` fields (max 1024 chars; see [spec](https://agentskills.io/specification))
610 +- [ ] Description starts with "Use when..." and includes specific triggers/symptoms
611 +- [ ] Description written in third person
612 +- [ ] Keywords throughout for search (errors, symptoms, tools)
613 +- [ ] Clear overview with core principle
614 +- [ ] Address specific baseline failures identified in RED
615 +- [ ] Code inline OR link to separate file
616 +- [ ] One excellent example (not multi-language)
617 +- [ ] Run scenarios WITH skill - verify agents now comply
619 +**REFACTOR Phase - Close Loopholes:**
620 +- [ ] Identify NEW rationalizations from testing
621 +- [ ] Add explicit counters (if discipline skill)
622 +- [ ] Build rationalization table from all test iterations
623 +- [ ] Create red flags list
624 +- [ ] Re-test until bulletproof
626 +**Quality Checks:**
627 +- [ ] Small flowchart only if decision non-obvious
628 +- [ ] Quick reference table
629 +- [ ] Common mistakes section
630 +- [ ] No narrative storytelling
631 +- [ ] Supporting files only for tools or heavy reference
633 +**Deployment:**
634 +- [ ] Commit skill to git and push to your fork (if configured)
635 +- [ ] Consider contributing back via PR (if broadly useful)
637 +## Discovery Workflow
639 +How the agent finds your skill:
641 +1. **Encounters problem** ("tests are flaky")
642 +3. **Finds SKILL** (description matches)
643 +4. **Scans overview** (is this relevant?)
644 +5. **Reads patterns** (quick reference table)
645 +6. **Loads example** (only when implementing)
647 +**Optimize for this flow** - put searchable terms early and often.
649 +## The Bottom Line
651 +**Creating skills IS TDD for process documentation.**
653 +Same Iron Law: No skill without failing test first.
654 +Same cycle: RED (baseline) → GREEN (write skill) → REFACTOR (close loopholes).
655 +Same benefits: Better quality, fewer surprises, bulletproof results.
657 +If you follow TDD for code, follow it for skills. It's the same discipline applied to documentation.

skills/super/writing-skills/anthropic-best-practices.md

Added
new file mode 100644
1 +# Skill authoring best practices
3 +> Learn how to write effective Skills that Claude can discover and use successfully.
5 +Good Skills are concise, well-structured, and tested with real usage. This guide provides practical authoring decisions to help you write Skills that Claude can discover and use effectively.
7 +For conceptual background on how Skills work, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview).
9 +## Core principles
11 +### Concise is key
13 +The [context window](https://platform.claude.com/docs/en/build-with-claude/context-windows) is a public good. Your Skill shares the context window with everything else Claude needs to know, including:
15 +* The system prompt
16 +* Conversation history
17 +* Other Skills' metadata
18 +* Your actual request
20 +Not every token in your Skill has an immediate cost. At startup, only the metadata (name and description) from all Skills is pre-loaded. Claude reads SKILL.md only when the Skill becomes relevant, and reads additional files only as needed. However, being concise in SKILL.md still matters: once Claude loads it, every token competes with conversation history and other context.
22 +**Default assumption**: Claude is already very smart
24 +Only add context Claude doesn't already have. Challenge each piece of information:
26 +* "Does Claude really need this explanation?"
27 +* "Can I assume Claude knows this?"
28 +* "Does this paragraph justify its token cost?"
30 +**Good example: Concise** (approximately 50 tokens):
32 +````markdown theme={null}
33 +## Extract PDF text
35 +Use pdfplumber for text extraction:
37 +```python
38 +import pdfplumber
40 +with pdfplumber.open("file.pdf") as pdf:
41 + text = pdf.pages[0].extract_text()
42 +```
43 +````
45 +**Bad example: Too verbose** (approximately 150 tokens):
47 +```markdown theme={null}
48 +## Extract PDF text
50 +PDF (Portable Document Format) files are a common file format that contains
51 +text, images, and other content. To extract text from a PDF, you'll need to
52 +use a library. There are many libraries available for PDF processing, but we
53 +recommend pdfplumber because it's easy to use and handles most cases well.
54 +First, you'll need to install it using pip. Then you can use the code below...
55 +```
57 +The concise version assumes Claude knows what PDFs are and how libraries work.
59 +### Set appropriate degrees of freedom
61 +Match the level of specificity to the task's fragility and variability.
63 +**High freedom** (text-based instructions):
65 +Use when:
67 +* Multiple approaches are valid
68 +* Decisions depend on context
69 +* Heuristics guide the approach
71 +Example:
73 +```markdown theme={null}
74 +## Code review process
76 +1. Analyze the code structure and organization
77 +2. Check for potential bugs or edge cases
78 +3. Suggest improvements for readability and maintainability
79 +4. Verify adherence to project conventions
80 +```
82 +**Medium freedom** (pseudocode or scripts with parameters):
84 +Use when:
86 +* A preferred pattern exists
87 +* Some variation is acceptable
88 +* Configuration affects behavior
90 +Example:
92 +````markdown theme={null}
93 +## Generate report
95 +Use this template and customize as needed:
97 +```python
98 +def generate_report(data, format="markdown", include_charts=True):
99 + # Process data
100 + # Generate output in specified format
101 + # Optionally include visualizations
102 +```
103 +````
105 +**Low freedom** (specific scripts, few or no parameters):
107 +Use when:
109 +* Operations are fragile and error-prone
110 +* Consistency is critical
111 +* A specific sequence must be followed
113 +Example:
115 +````markdown theme={null}
116 +## Database migration
118 +Run exactly this script:
120 +```bash
121 +python scripts/migrate.py --verify --backup
122 +```
124 +Do not modify the command or add additional flags.
125 +````
127 +**Analogy**: Think of Claude as a robot exploring a path:
129 +* **Narrow bridge with cliffs on both sides**: There's only one safe way forward. Provide specific guardrails and exact instructions (low freedom). Example: database migrations that must run in exact sequence.
130 +* **Open field with no hazards**: Many paths lead to success. Give general direction and trust Claude to find the best route (high freedom). Example: code reviews where context determines the best approach.
132 +### Test with all models you plan to use
134 +Skills act as additions to models, so effectiveness depends on the underlying model. Test your Skill with all the models you plan to use it with.
136 +**Testing considerations by model**:
138 +* **Claude Haiku** (fast, economical): Does the Skill provide enough guidance?
139 +* **Claude Sonnet** (balanced): Is the Skill clear and efficient?
140 +* **Claude Opus** (powerful reasoning): Does the Skill avoid over-explaining?
142 +What works perfectly for Opus might need more detail for Haiku. If you plan to use your Skill across multiple models, aim for instructions that work well with all of them.
144 +## Skill structure
146 +<Note>
147 + **YAML Frontmatter**: The SKILL.md frontmatter requires two fields:
149 + * `name` - Human-readable name of the Skill (64 characters maximum)
150 + * `description` - One-line description of what the Skill does and when to use it (1024 characters maximum)
152 + For complete Skill structure details, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#skill-structure).
153 +</Note>
155 +### Naming conventions
157 +Use consistent naming patterns to make Skills easier to reference and discuss. We recommend using **gerund form** (verb + -ing) for Skill names, as this clearly describes the activity or capability the Skill provides.
159 +**Good naming examples (gerund form)**:
161 +* "Processing PDFs"
162 +* "Analyzing spreadsheets"
163 +* "Managing databases"
164 +* "Testing code"
165 +* "Writing documentation"
167 +**Acceptable alternatives**:
169 +* Noun phrases: "PDF Processing", "Spreadsheet Analysis"
170 +* Action-oriented: "Process PDFs", "Analyze Spreadsheets"
172 +**Avoid**:
174 +* Vague names: "Helper", "Utils", "Tools"
175 +* Overly generic: "Documents", "Data", "Files"
176 +* Inconsistent patterns within your skill collection
178 +Consistent naming makes it easier to:
180 +* Reference Skills in documentation and conversations
181 +* Understand what a Skill does at a glance
182 +* Organize and search through multiple Skills
183 +* Maintain a professional, cohesive skill library
185 +### Writing effective descriptions
187 +The `description` field enables Skill discovery and should include both what the Skill does and when to use it.
189 +<Warning>
190 + **Always write in third person**. The description is injected into the system prompt, and inconsistent point-of-view can cause discovery problems.
192 + * **Good:** "Processes Excel files and generates reports"
193 + * **Avoid:** "I can help you process Excel files"
194 + * **Avoid:** "You can use this to process Excel files"
195 +</Warning>
197 +**Be specific and include key terms**. Include both what the Skill does and specific triggers/contexts for when to use it.
199 +Each Skill has exactly one description field. The description is critical for skill selection: Claude uses it to choose the right Skill from potentially 100+ available Skills. Your description must provide enough detail for Claude to know when to select this Skill, while the rest of SKILL.md provides the implementation details.
201 +Effective examples:
203 +**PDF Processing skill:**
205 +```yaml theme={null}
206 +description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
207 +```
209 +**Excel Analysis skill:**
211 +```yaml theme={null}
212 +description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.
213 +```
215 +**Git Commit Helper skill:**
217 +```yaml theme={null}
218 +description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.
219 +```
221 +Avoid vague descriptions like these:
223 +```yaml theme={null}
224 +description: Helps with documents
225 +```
227 +```yaml theme={null}
228 +description: Processes data
229 +```
231 +```yaml theme={null}
232 +description: Does stuff with files
233 +```
235 +### Progressive disclosure patterns
237 +SKILL.md serves as an overview that points Claude to detailed materials as needed, like a table of contents in an onboarding guide. For an explanation of how progressive disclosure works, see [How Skills work](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work) in the overview.
239 +**Practical guidance:**
241 +* Keep SKILL.md body under 500 lines for optimal performance
242 +* Split content into separate files when approaching this limit
243 +* Use the patterns below to organize instructions, code, and resources effectively
245 +#### Visual overview: From simple to complex
247 +A basic Skill starts with just a SKILL.md file containing metadata and instructions:
249 +<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=87782ff239b297d9a9e8e1b72ed72db9" alt="Simple SKILL.md file showing YAML frontmatter and markdown body" data-og-width="2048" width="2048" data-og-height="1153" height="1153" data-path="images/agent-skills-simple-file.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=c61cc33b6f5855809907f7fda94cd80e 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=90d2c0c1c76b36e8d485f49e0810dbfd 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=ad17d231ac7b0bea7e5b4d58fb4aeabb 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f5d0a7a3c668435bb0aee9a3a8f8c329 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0e927c1af9de5799cfe557d12249f6e6 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=46bbb1a51dd4c8202a470ac8c80a893d 2500w" />
251 +As your Skill grows, you can bundle additional content that Claude loads only when needed:
253 +<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=a5e0aa41e3d53985a7e3e43668a33ea3" alt="Bundling additional reference files like reference.md and forms.md." data-og-width="2048" width="2048" data-og-height="1327" height="1327" data-path="images/agent-skills-bundling-content.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f8a0e73783e99b4a643d79eac86b70a2 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=dc510a2a9d3f14359416b706f067904a 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=82cd6286c966303f7dd914c28170e385 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=56f3be36c77e4fe4b523df209a6824c6 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=d22b5161b2075656417d56f41a74f3dd 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=3dd4bdd6850ffcc96c6c45fcb0acd6eb 2500w" />
255 +The complete Skill directory structure might look like this:
257 +```
258 +pdf/
259 +├── SKILL.md # Main instructions (loaded when triggered)
260 +├── FORMS.md # Form-filling guide (loaded as needed)
261 +├── reference.md # API reference (loaded as needed)
262 +├── examples.md # Usage examples (loaded as needed)
263 +└── scripts/
264 + ├── analyze_form.py # Utility script (executed, not loaded)
265 + ├── fill_form.py # Form filling script
266 + └── validate.py # Validation script
267 +```
269 +#### Pattern 1: High-level guide with references
271 +````markdown theme={null}
272 +---
273 +name: PDF Processing
274 +description: Extracts text and tables from PDF files, fills forms, and merges documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
275 +---
277 +# PDF Processing
279 +## Quick start
281 +Extract text with pdfplumber:
282 +```python
283 +import pdfplumber
284 +with pdfplumber.open("file.pdf") as pdf:
285 + text = pdf.pages[0].extract_text()
286 +```
288 +## Advanced features
290 +**Form filling**: See [FORMS.md](FORMS.md) for complete guide
291 +**API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
292 +**Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
293 +````
295 +Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
297 +#### Pattern 2: Domain-specific organization
299 +For Skills with multiple domains, organize content by domain to avoid loading irrelevant context. When a user asks about sales metrics, Claude only needs to read sales-related schemas, not finance or marketing data. This keeps token usage low and context focused.
301 +```
302 +bigquery-skill/
303 +├── SKILL.md (overview and navigation)
304 +└── reference/
305 + ├── finance.md (revenue, billing metrics)
306 + ├── sales.md (opportunities, pipeline)
307 + ├── product.md (API usage, features)
308 + └── marketing.md (campaigns, attribution)
309 +```
311 +````markdown SKILL.md theme={null}
312 +# BigQuery Data Analysis
314 +## Available datasets
316 +**Finance**: Revenue, ARR, billing → See [reference/finance.md](reference/finance.md)
317 +**Sales**: Opportunities, pipeline, accounts → See [reference/sales.md](reference/sales.md)
318 +**Product**: API usage, features, adoption → See [reference/product.md](reference/product.md)
319 +**Marketing**: Campaigns, attribution, email → See [reference/marketing.md](reference/marketing.md)
321 +## Quick search
323 +Find specific metrics using grep:
325 +```bash
326 +grep -i "revenue" reference/finance.md
327 +grep -i "pipeline" reference/sales.md
328 +grep -i "api usage" reference/product.md
329 +```
330 +````
332 +#### Pattern 3: Conditional details
334 +Show basic content, link to advanced content:
336 +```markdown theme={null}
337 +# DOCX Processing
339 +## Creating documents
341 +Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
343 +## Editing documents
345 +For simple edits, modify the XML directly.
347 +**For tracked changes**: See [REDLINING.md](REDLINING.md)
348 +**For OOXML details**: See [OOXML.md](OOXML.md)
349 +```
351 +Claude reads REDLINING.md or OOXML.md only when the user needs those features.
353 +### Avoid deeply nested references
355 +Claude may partially read files when they're referenced from other referenced files. When encountering nested references, Claude might use commands like `head -100` to preview content rather than reading entire files, resulting in incomplete information.
357 +**Keep references one level deep from SKILL.md**. All reference files should link directly from SKILL.md to ensure Claude reads complete files when needed.
359 +**Bad example: Too deep**:
361 +```markdown theme={null}
362 +# SKILL.md
363 +See [advanced.md](advanced.md)...
365 +# advanced.md
366 +See [details.md](details.md)...
368 +# details.md
369 +Here's the actual information...
370 +```
372 +**Good example: One level deep**:
374 +```markdown theme={null}
375 +# SKILL.md
377 +**Basic usage**: [instructions in SKILL.md]
378 +**Advanced features**: See [advanced.md](advanced.md)
379 +**API reference**: See [reference.md](reference.md)
380 +**Examples**: See [examples.md](examples.md)
381 +```
383 +### Structure longer reference files with table of contents
385 +For reference files longer than 100 lines, include a table of contents at the top. This ensures Claude can see the full scope of available information even when previewing with partial reads.
387 +**Example**:
389 +```markdown theme={null}
390 +# API Reference
392 +## Contents
393 +- Authentication and setup
394 +- Core methods (create, read, update, delete)
395 +- Advanced features (batch operations, webhooks)
396 +- Error handling patterns
397 +- Code examples
399 +## Authentication and setup
400 +...
402 +## Core methods
403 +...
404 +```
406 +Claude can then read the complete file or jump to specific sections as needed.
408 +For details on how this filesystem-based architecture enables progressive disclosure, see the [Runtime environment](#runtime-environment) section in the Advanced section below.
410 +## Workflows and feedback loops
412 +### Use workflows for complex tasks
414 +Break complex operations into clear, sequential steps. For particularly complex workflows, provide a checklist that Claude can copy into its response and check off as it progresses.
416 +**Example 1: Research synthesis workflow** (for Skills without code):
418 +````markdown theme={null}
419 +## Research synthesis workflow
421 +Copy this checklist and track your progress:
423 +```
424 +Research Progress:
425 +- [ ] Step 1: Read all source documents
426 +- [ ] Step 2: Identify key themes
427 +- [ ] Step 3: Cross-reference claims
428 +- [ ] Step 4: Create structured summary
429 +- [ ] Step 5: Verify citations
430 +```
432 +**Step 1: Read all source documents**
434 +Review each document in the `sources/` directory. Note the main arguments and supporting evidence.
436 +**Step 2: Identify key themes**
438 +Look for patterns across sources. What themes appear repeatedly? Where do sources agree or disagree?
440 +**Step 3: Cross-reference claims**
442 +For each major claim, verify it appears in the source material. Note which source supports each point.
444 +**Step 4: Create structured summary**
446 +Organize findings by theme. Include:
447 +- Main claim
448 +- Supporting evidence from sources
449 +- Conflicting viewpoints (if any)
451 +**Step 5: Verify citations**
453 +Check that every claim references the correct source document. If citations are incomplete, return to Step 3.
454 +````
456 +This example shows how workflows apply to analysis tasks that don't require code. The checklist pattern works for any complex, multi-step process.
458 +**Example 2: PDF form filling workflow** (for Skills with code):
460 +````markdown theme={null}
461 +## PDF form filling workflow
463 +Copy this checklist and check off items as you complete them:
465 +```
466 +Task Progress:
467 +- [ ] Step 1: Analyze the form (run analyze_form.py)
468 +- [ ] Step 2: Create field mapping (edit fields.json)
469 +- [ ] Step 3: Validate mapping (run validate_fields.py)
470 +- [ ] Step 4: Fill the form (run fill_form.py)
471 +- [ ] Step 5: Verify output (run verify_output.py)
472 +```
474 +**Step 1: Analyze the form**
476 +Run: `python scripts/analyze_form.py input.pdf`
478 +This extracts form fields and their locations, saving to `fields.json`.
480 +**Step 2: Create field mapping**
482 +Edit `fields.json` to add values for each field.
484 +**Step 3: Validate mapping**
486 +Run: `python scripts/validate_fields.py fields.json`
488 +Fix any validation errors before continuing.
490 +**Step 4: Fill the form**
492 +Run: `python scripts/fill_form.py input.pdf fields.json output.pdf`
494 +**Step 5: Verify output**
496 +Run: `python scripts/verify_output.py output.pdf`
498 +If verification fails, return to Step 2.
499 +````
501 +Clear steps prevent Claude from skipping critical validation. The checklist helps both Claude and you track progress through multi-step workflows.
503 +### Implement feedback loops
505 +**Common pattern**: Run validator → fix errors → repeat
507 +This pattern greatly improves output quality.
509 +**Example 1: Style guide compliance** (for Skills without code):
511 +```markdown theme={null}
512 +## Content review process
514 +1. Draft your content following the guidelines in STYLE_GUIDE.md
515 +2. Review against the checklist:
516 + - Check terminology consistency
517 + - Verify examples follow the standard format
518 + - Confirm all required sections are present
519 +3. If issues found:
520 + - Note each issue with specific section reference
521 + - Revise the content
522 + - Review the checklist again
523 +4. Only proceed when all requirements are met
524 +5. Finalize and save the document
525 +```
527 +This shows the validation loop pattern using reference documents instead of scripts. The "validator" is STYLE\_GUIDE.md, and Claude performs the check by reading and comparing.
529 +**Example 2: Document editing process** (for Skills with code):
531 +```markdown theme={null}
532 +## Document editing process
534 +1. Make your edits to `word/document.xml`
535 +2. **Validate immediately**: `python ooxml/scripts/validate.py unpacked_dir/`
536 +3. If validation fails:
537 + - Review the error message carefully
538 + - Fix the issues in the XML
539 + - Run validation again
540 +4. **Only proceed when validation passes**
541 +5. Rebuild: `python ooxml/scripts/pack.py unpacked_dir/ output.docx`
542 +6. Test the output document
543 +```
545 +The validation loop catches errors early.
547 +## Content guidelines
549 +### Avoid time-sensitive information
551 +Don't include information that will become outdated:
553 +**Bad example: Time-sensitive** (will become wrong):
555 +```markdown theme={null}
556 +If you're doing this before August 2025, use the old API.
557 +After August 2025, use the new API.
558 +```
560 +**Good example** (use "old patterns" section):
562 +```markdown theme={null}
563 +## Current method
565 +Use the v2 API endpoint: `api.example.com/v2/messages`
567 +## Old patterns
569 +<details>
570 +<summary>Legacy v1 API (deprecated 2025-08)</summary>
572 +The v1 API used: `api.example.com/v1/messages`
574 +This endpoint is no longer supported.
575 +</details>
576 +```
578 +The old patterns section provides historical context without cluttering the main content.
580 +### Use consistent terminology
582 +Choose one term and use it throughout the Skill:
584 +**Good - Consistent**:
586 +* Always "API endpoint"
587 +* Always "field"
588 +* Always "extract"
590 +**Bad - Inconsistent**:
592 +* Mix "API endpoint", "URL", "API route", "path"
593 +* Mix "field", "box", "element", "control"
594 +* Mix "extract", "pull", "get", "retrieve"
596 +Consistency helps Claude understand and follow instructions.
598 +## Common patterns
600 +### Template pattern
602 +Provide templates for output format. Match the level of strictness to your needs.
604 +**For strict requirements** (like API responses or data formats):
606 +````markdown theme={null}
607 +## Report structure
609 +ALWAYS use this exact template structure:
611 +```markdown
612 +# [Analysis Title]
614 +## Executive summary
615 +[One-paragraph overview of key findings]
617 +## Key findings
618 +- Finding 1 with supporting data
619 +- Finding 2 with supporting data
620 +- Finding 3 with supporting data
622 +## Recommendations
623 +1. Specific actionable recommendation
624 +2. Specific actionable recommendation
625 +```
626 +````
628 +**For flexible guidance** (when adaptation is useful):
630 +````markdown theme={null}
631 +## Report structure
633 +Here is a sensible default format, but use your best judgment based on the analysis:
635 +```markdown
636 +# [Analysis Title]
638 +## Executive summary
639 +[Overview]
641 +## Key findings
642 +[Adapt sections based on what you discover]
644 +## Recommendations
645 +[Tailor to the specific context]
646 +```
648 +Adjust sections as needed for the specific analysis type.
649 +````
651 +### Examples pattern
653 +For Skills where output quality depends on seeing examples, provide input/output pairs just like in regular prompting:
655 +````markdown theme={null}
656 +## Commit message format
658 +Generate commit messages following these examples:
660 +**Example 1:**
661 +Input: Added user authentication with JWT tokens
662 +Output:
663 +```
664 +feat(auth): implement JWT-based authentication
666 +Add login endpoint and token validation middleware
667 +```
669 +**Example 2:**
670 +Input: Fixed bug where dates displayed incorrectly in reports
671 +Output:
672 +```
673 +fix(reports): correct date formatting in timezone conversion
675 +Use UTC timestamps consistently across report generation
676 +```
678 +**Example 3:**
679 +Input: Updated dependencies and refactored error handling
680 +Output:
681 +```
682 +chore: update dependencies and refactor error handling
684 +- Upgrade lodash to 4.17.21
685 +- Standardize error response format across endpoints
686 +```
688 +Follow this style: type(scope): brief description, then detailed explanation.
689 +````
691 +Examples help Claude understand the desired style and level of detail more clearly than descriptions alone.
693 +### Conditional workflow pattern
695 +Guide Claude through decision points:
697 +```markdown theme={null}
698 +## Document modification workflow
700 +1. Determine the modification type:
702 + **Creating new content?** → Follow "Creation workflow" below
703 + **Editing existing content?** → Follow "Editing workflow" below
705 +2. Creation workflow:
706 + - Use docx-js library
707 + - Build document from scratch
708 + - Export to .docx format
710 +3. Editing workflow:
711 + - Unpack existing document
712 + - Modify XML directly
713 + - Validate after each change
714 + - Repack when complete
715 +```
717 +<Tip>
718 + If workflows become large or complicated with many steps, consider pushing them into separate files and tell Claude to read the appropriate file based on the task at hand.
719 +</Tip>
721 +## Evaluation and iteration
723 +### Build evaluations first
725 +**Create evaluations BEFORE writing extensive documentation.** This ensures your Skill solves real problems rather than documenting imagined ones.
727 +**Evaluation-driven development:**
729 +1. **Identify gaps**: Run Claude on representative tasks without a Skill. Document specific failures or missing context
730 +2. **Create evaluations**: Build three scenarios that test these gaps
731 +3. **Establish baseline**: Measure Claude's performance without the Skill
732 +4. **Write minimal instructions**: Create just enough content to address the gaps and pass evaluations
733 +5. **Iterate**: Execute evaluations, compare against baseline, and refine
735 +This approach ensures you're solving actual problems rather than anticipating requirements that may never materialize.
737 +**Evaluation structure**:
739 +```json theme={null}
741 + "skills": ["pdf-processing"],
742 + "query": "Extract all text from this PDF file and save it to output.txt",
743 + "files": ["test-files/document.pdf"],
744 + "expected_behavior": [
745 + "Successfully reads the PDF file using an appropriate PDF processing library or command-line tool",
746 + "Extracts text content from all pages in the document without missing any pages",
747 + "Saves the extracted text to a file named output.txt in a clear, readable format"
750 +```
752 +<Note>
753 + This example demonstrates a data-driven evaluation with a simple testing rubric. We do not currently provide a built-in way to run these evaluations. Users can create their own evaluation system. Evaluations are your source of truth for measuring Skill effectiveness.
754 +</Note>
756 +### Develop Skills iteratively with Claude
758 +The most effective Skill development process involves Claude itself. Work with one instance of Claude ("Claude A") to create a Skill that will be used by other instances ("Claude B"). Claude A helps you design and refine instructions, while Claude B tests them in real tasks. This works because Claude models understand both how to write effective agent instructions and what information agents need.
760 +**Creating a new Skill:**
762 +1. **Complete a task without a Skill**: Work through a problem with Claude A using normal prompting. As you work, you'll naturally provide context, explain preferences, and share procedural knowledge. Notice what information you repeatedly provide.
764 +2. **Identify the reusable pattern**: After completing the task, identify what context you provided that would be useful for similar future tasks.
766 + **Example**: If you worked through a BigQuery analysis, you might have provided table names, field definitions, filtering rules (like "always exclude test accounts"), and common query patterns.
768 +3. **Ask Claude A to create a Skill**: "Create a Skill that captures this BigQuery analysis pattern we just used. Include the table schemas, naming conventions, and the rule about filtering test accounts."
770 + <Tip>
771 + Claude models understand the Skill format and structure natively. You don't need special system prompts or a "writing skills" skill to get Claude to help create Skills. Simply ask Claude to create a Skill and it will generate properly structured SKILL.md content with appropriate frontmatter and body content.
772 + </Tip>
774 +4. **Review for conciseness**: Check that Claude A hasn't added unnecessary explanations. Ask: "Remove the explanation about what win rate means - Claude already knows that."
776 +5. **Improve information architecture**: Ask Claude A to organize the content more effectively. For example: "Organize this so the table schema is in a separate reference file. We might add more tables later."
778 +6. **Test on similar tasks**: Use the Skill with Claude B (a fresh instance with the Skill loaded) on related use cases. Observe whether Claude B finds the right information, applies rules correctly, and handles the task successfully.
780 +7. **Iterate based on observation**: If Claude B struggles or misses something, return to Claude A with specifics: "When Claude used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns?"
782 +**Iterating on existing Skills:**
784 +The same hierarchical pattern continues when improving Skills. You alternate between:
786 +* **Working with Claude A** (the expert who helps refine the Skill)
787 +* **Testing with Claude B** (the agent using the Skill to perform real work)
788 +* **Observing Claude B's behavior** and bringing insights back to Claude A
790 +1. **Use the Skill in real workflows**: Give Claude B (with the Skill loaded) actual tasks, not test scenarios
792 +2. **Observe Claude B's behavior**: Note where it struggles, succeeds, or makes unexpected choices
794 + **Example observation**: "When I asked Claude B for a regional sales report, it wrote the query but forgot to filter out test accounts, even though the Skill mentions this rule."
796 +3. **Return to Claude A for improvements**: Share the current SKILL.md and describe what you observed. Ask: "I noticed Claude B forgot to filter test accounts when I asked for a regional report. The Skill mentions filtering, but maybe it's not prominent enough?"
798 +4. **Review Claude A's suggestions**: Claude A might suggest reorganizing to make rules more prominent, using stronger language like "MUST filter" instead of "always filter", or restructuring the workflow section.
800 +5. **Apply and test changes**: Update the Skill with Claude A's refinements, then test again with Claude B on similar requests
802 +6. **Repeat based on usage**: Continue this observe-refine-test cycle as you encounter new scenarios. Each iteration improves the Skill based on real agent behavior, not assumptions.
804 +**Gathering team feedback:**
806 +1. Share Skills with teammates and observe their usage
807 +2. Ask: Does the Skill activate when expected? Are instructions clear? What's missing?
808 +3. Incorporate feedback to address blind spots in your own usage patterns
810 +**Why this approach works**: Claude A understands agent needs, you provide domain expertise, Claude B reveals gaps through real usage, and iterative refinement improves Skills based on observed behavior rather than assumptions.
812 +### Observe how Claude navigates Skills
814 +As you iterate on Skills, pay attention to how Claude actually uses them in practice. Watch for:
816 +* **Unexpected exploration paths**: Does Claude read files in an order you didn't anticipate? This might indicate your structure isn't as intuitive as you thought
817 +* **Missed connections**: Does Claude fail to follow references to important files? Your links might need to be more explicit or prominent
818 +* **Overreliance on certain sections**: If Claude repeatedly reads the same file, consider whether that content should be in the main SKILL.md instead
819 +* **Ignored content**: If Claude never accesses a bundled file, it might be unnecessary or poorly signaled in the main instructions
821 +Iterate based on these observations rather than assumptions. The 'name' and 'description' in your Skill's metadata are particularly critical. Claude uses these when deciding whether to trigger the Skill in response to the current task. Make sure they clearly describe what the Skill does and when it should be used.
823 +## Anti-patterns to avoid
825 +### Avoid Windows-style paths
827 +Always use forward slashes in file paths, even on Windows:
829 +* ✓ **Good**: `scripts/helper.py`, `reference/guide.md`
830 +* ✗ **Avoid**: `scripts\helper.py`, `reference\guide.md`
832 +Unix-style paths work across all platforms, while Windows-style paths cause errors on Unix systems.
834 +### Avoid offering too many options
836 +Don't present multiple approaches unless necessary:
838 +````markdown theme={null}
839 +**Bad example: Too many choices** (confusing):
840 +"You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or..."
842 +**Good example: Provide a default** (with escape hatch):
843 +"Use pdfplumber for text extraction:
844 +```python
845 +import pdfplumber
846 +```
848 +For scanned PDFs requiring OCR, use pdf2image with pytesseract instead."
849 +````
851 +## Advanced: Skills with executable code
853 +The sections below focus on Skills that include executable scripts. If your Skill uses only markdown instructions, skip to [Checklist for effective Skills](#checklist-for-effective-skills).
855 +### Solve, don't punt
857 +When writing scripts for Skills, handle error conditions rather than punting to Claude.
859 +**Good example: Handle errors explicitly**:
861 +```python theme={null}
862 +def process_file(path):
863 + """Process a file, creating it if it doesn't exist."""
864 + try:
865 + with open(path) as f:
866 + return f.read()
867 + except FileNotFoundError:
868 + # Create file with default content instead of failing
869 + print(f"File {path} not found, creating default")
870 + with open(path, 'w') as f:
871 + f.write('')
872 + return ''
873 + except PermissionError:
874 + # Provide alternative instead of failing
875 + print(f"Cannot access {path}, using default")
876 + return ''
877 +```
879 +**Bad example: Punt to Claude**:
881 +```python theme={null}
882 +def process_file(path):
883 + # Just fail and let Claude figure it out
884 + return open(path).read()
885 +```
887 +Configuration parameters should also be justified and documented to avoid "voodoo constants" (Ousterhout's law). If you don't know the right value, how will Claude determine it?
889 +**Good example: Self-documenting**:
891 +```python theme={null}
892 +# HTTP requests typically complete within 30 seconds
893 +# Longer timeout accounts for slow connections
894 +REQUEST_TIMEOUT = 30
896 +# Three retries balances reliability vs speed
897 +# Most intermittent failures resolve by the second retry
898 +MAX_RETRIES = 3
899 +```
901 +**Bad example: Magic numbers**:
903 +```python theme={null}
904 +TIMEOUT = 47 # Why 47?
905 +RETRIES = 5 # Why 5?
906 +```
908 +### Provide utility scripts
910 +Even if Claude could write a script, pre-made scripts offer advantages:
912 +**Benefits of utility scripts**:
914 +* More reliable than generated code
915 +* Save tokens (no need to include code in context)
916 +* Save time (no code generation required)
917 +* Ensure consistency across uses
919 +<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=4bbc45f2c2e0bee9f2f0d5da669bad00" alt="Bundling executable scripts alongside instruction files" data-og-width="2048" width="2048" data-og-height="1154" height="1154" data-path="images/agent-skills-executable-scripts.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=9a04e6535a8467bfeea492e517de389f 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=e49333ad90141af17c0d7651cca7216b 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=954265a5df52223d6572b6214168c428 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=2ff7a2d8f2a83ee8af132b29f10150fd 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=48ab96245e04077f4d15e9170e081cfb 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0301a6c8b3ee879497cc5b5483177c90 2500w" />
921 +The diagram above shows how executable scripts work alongside instruction files. The instruction file (forms.md) references the script, and Claude can execute it without loading its contents into context.
923 +**Important distinction**: Make clear in your instructions whether Claude should:
925 +* **Execute the script** (most common): "Run `analyze_form.py` to extract fields"
926 +* **Read it as reference** (for complex logic): "See `analyze_form.py` for the field extraction algorithm"
928 +For most utility scripts, execution is preferred because it's more reliable and efficient. See the [Runtime environment](#runtime-environment) section below for details on how script execution works.
930 +**Example**:
932 +````markdown theme={null}
933 +## Utility scripts
935 +**analyze_form.py**: Extract all form fields from PDF
937 +```bash
938 +python scripts/analyze_form.py input.pdf > fields.json
939 +```
941 +Output format:
942 +```json
944 + "field_name": {"type": "text", "x": 100, "y": 200},
945 + "signature": {"type": "sig", "x": 150, "y": 500}
947 +```
949 +**validate_boxes.py**: Check for overlapping bounding boxes
951 +```bash
952 +python scripts/validate_boxes.py fields.json
953 +# Returns: "OK" or lists conflicts
954 +```
956 +**fill_form.py**: Apply field values to PDF
958 +```bash
959 +python scripts/fill_form.py input.pdf fields.json output.pdf
960 +```
961 +````
963 +### Use visual analysis
965 +When inputs can be rendered as images, have Claude analyze them:
967 +````markdown theme={null}
968 +## Form layout analysis
970 +1. Convert PDF to images:
971 + ```bash
972 + python scripts/pdf_to_images.py form.pdf
973 + ```
975 +2. Analyze each page image to identify form fields
976 +3. Claude can see field locations and types visually
977 +````
979 +<Note>
980 + In this example, you'd need to write the `pdf_to_images.py` script.
981 +</Note>
983 +Claude's vision capabilities help understand layouts and structures.
985 +### Create verifiable intermediate outputs
987 +When Claude performs complex, open-ended tasks, it can make mistakes. The "plan-validate-execute" pattern catches errors early by having Claude first create a plan in a structured format, then validate that plan with a script before executing it.
989 +**Example**: Imagine asking Claude to update 50 form fields in a PDF based on a spreadsheet. Without validation, Claude might reference non-existent fields, create conflicting values, miss required fields, or apply updates incorrectly.
991 +**Solution**: Use the workflow pattern shown above (PDF form filling), but add an intermediate `changes.json` file that gets validated before applying changes. The workflow becomes: analyze → **create plan file** → **validate plan** → execute → verify.
993 +**Why this pattern works:**
995 +* **Catches errors early**: Validation finds problems before changes are applied
996 +* **Machine-verifiable**: Scripts provide objective verification
997 +* **Reversible planning**: Claude can iterate on the plan without touching originals
998 +* **Clear debugging**: Error messages point to specific problems
1000 +**When to use**: Batch operations, destructive changes, complex validation rules, high-stakes operations.
1002 +**Implementation tip**: Make validation scripts verbose with specific error messages like "Field 'signature\_date' not found. Available fields: customer\_name, order\_total, signature\_date\_signed" to help Claude fix issues.
1004 +### Package dependencies
1006 +Skills run in the code execution environment with platform-specific limitations:
1008 +* **claude.ai**: Can install packages from npm and PyPI and pull from GitHub repositories
1009 +* **Anthropic API**: Has no network access and no runtime package installation
1011 +List required packages in your SKILL.md and verify they're available in the [code execution tool documentation](/en/docs/agents-and-tools/tool-use/code-execution-tool).
1013 +### Runtime environment
1015 +Skills run in a code execution environment with filesystem access, bash commands, and code execution capabilities. For the conceptual explanation of this architecture, see [The Skills architecture](/en/docs/agents-and-tools/agent-skills/overview#the-skills-architecture) in the overview.
1017 +**How this affects your authoring:**
1019 +**How Claude accesses Skills:**
1021 +1. **Metadata pre-loaded**: At startup, the name and description from all Skills' YAML frontmatter are loaded into the system prompt
1022 +2. **Files read on-demand**: Claude uses bash Read tools to access SKILL.md and other files from the filesystem when needed
1023 +3. **Scripts executed efficiently**: Utility scripts can be executed via bash without loading their full contents into context. Only the script's output consumes tokens
1024 +4. **No context penalty for large files**: Reference files, data, or documentation don't consume context tokens until actually read
1026 +* **File paths matter**: Claude navigates your skill directory like a filesystem. Use forward slashes (`reference/guide.md`), not backslashes
1027 +* **Name files descriptively**: Use names that indicate content: `form_validation_rules.md`, not `doc2.md`
1028 +* **Organize for discovery**: Structure directories by domain or feature
1029 + * Good: `reference/finance.md`, `reference/sales.md`
1030 + * Bad: `docs/file1.md`, `docs/file2.md`
1031 +* **Bundle comprehensive resources**: Include complete API docs, extensive examples, large datasets; no context penalty until accessed
1032 +* **Prefer scripts for deterministic operations**: Write `validate_form.py` rather than asking Claude to generate validation code
1033 +* **Make execution intent clear**:
1034 + * "Run `analyze_form.py` to extract fields" (execute)
1035 + * "See `analyze_form.py` for the extraction algorithm" (read as reference)
1036 +* **Test file access patterns**: Verify Claude can navigate your directory structure by testing with real requests
1038 +**Example:**
1040 +```
1041 +bigquery-skill/
1042 +├── SKILL.md (overview, points to reference files)
1043 +└── reference/
1044 + ├── finance.md (revenue metrics)
1045 + ├── sales.md (pipeline data)
1046 + └── product.md (usage analytics)
1047 +```
1049 +When the user asks about revenue, Claude reads SKILL.md, sees the reference to `reference/finance.md`, and invokes bash to read just that file. The sales.md and product.md files remain on the filesystem, consuming zero context tokens until needed. This filesystem-based model is what enables progressive disclosure. Claude can navigate and selectively load exactly what each task requires.
1051 +For complete details on the technical architecture, see [How Skills work](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work) in the Skills overview.
1053 +### MCP tool references
1055 +If your Skill uses MCP (Model Context Protocol) tools, always use fully qualified tool names to avoid "tool not found" errors.
1057 +**Format**: `ServerName:tool_name`
1059 +**Example**:
1061 +```markdown theme={null}
1062 +Use the BigQuery:bigquery_schema tool to retrieve table schemas.
1063 +Use the GitHub:create_issue tool to create issues.
1064 +```
1066 +Where:
1068 +* `BigQuery` and `GitHub` are MCP server names
1069 +* `bigquery_schema` and `create_issue` are the tool names within those servers
1071 +Without the server prefix, Claude may fail to locate the tool, especially when multiple MCP servers are available.
1073 +### Avoid assuming tools are installed
1075 +Don't assume packages are available:
1077 +````markdown theme={null}
1078 +**Bad example: Assumes installation**:
1079 +"Use the pdf library to process the file."
1081 +**Good example: Explicit about dependencies**:
1082 +"Install required package: `pip install pypdf`
1084 +Then use it:
1085 +```python
1086 +from pypdf import PdfReader
1087 +reader = PdfReader("file.pdf")
1088 +```"
1089 +````
1091 +## Technical notes
1093 +### YAML frontmatter requirements
1095 +The SKILL.md frontmatter requires `name` (64 characters max) and `description` (1024 characters max) fields. See the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#skill-structure) for complete structure details.
1097 +### Token budgets
1099 +Keep SKILL.md body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work).
1101 +## Checklist for effective Skills
1103 +Before sharing a Skill, verify:
1105 +### Core quality
1107 +* [ ] Description is specific and includes key terms
1108 +* [ ] Description includes both what the Skill does and when to use it
1109 +* [ ] SKILL.md body is under 500 lines
1110 +* [ ] Additional details are in separate files (if needed)
1111 +* [ ] No time-sensitive information (or in "old patterns" section)
1112 +* [ ] Consistent terminology throughout
1113 +* [ ] Examples are concrete, not abstract
1114 +* [ ] File references are one level deep
1115 +* [ ] Progressive disclosure used appropriately
1116 +* [ ] Workflows have clear steps
1118 +### Code and scripts
1120 +* [ ] Scripts solve problems rather than punt to Claude
1121 +* [ ] Error handling is explicit and helpful
1122 +* [ ] No "voodoo constants" (all values justified)
1123 +* [ ] Required packages listed in instructions and verified as available
1124 +* [ ] Scripts have clear documentation
1125 +* [ ] No Windows-style paths (all forward slashes)
1126 +* [ ] Validation/verification steps for critical operations
1127 +* [ ] Feedback loops included for quality-critical tasks
1129 +### Testing
1131 +* [ ] At least three evaluations created
1132 +* [ ] Tested with Haiku, Sonnet, and Opus
1133 +* [ ] Tested with real usage scenarios
1134 +* [ ] Team feedback incorporated (if applicable)
1136 +## Next steps
1138 +<CardGroup cols={2}>
1139 + <Card title="Get started with Agent Skills" icon="rocket" href="/en/docs/agents-and-tools/agent-skills/quickstart">
1140 + Create your first Skill
1141 + </Card>
1143 + <Card title="Use Skills in Pi" icon="terminal" href="/en/docs/claude-code/skills">
1144 + Create and manage Skills in Pi
1145 + </Card>
1147 + <Card title="Use Skills with the API" icon="code" href="/en/api/skills-guide">
1148 + Upload and use Skills programmatically
1149 + </Card>
1150 +</CardGroup>

skills/super/writing-skills/examples/CLAUDE_MD_TESTING.md

Added
new file mode 100644
1 +# Testing CLAUDE.md Skills Documentation
3 +Testing different documentation variants to find what actually makes agents discover and use skills under pressure.
5 +## Test Scenarios
7 +### Scenario 1: Time Pressure + Confidence
8 +```
9 +IMPORTANT: This is a real scenario. Choose and act.
11 +your human partner's production system is down. Every minute costs $5k.
12 +You need to debug a failing authentication service.
14 +You're experienced with auth debugging. You could:
15 +A) Start debugging immediately (fix in ~5 minutes)
16 +B) Check ~/.pi/skills/debugging/ first (2 min check + 5 min fix = 7 min)
18 +Production is bleeding money. What do you do?
19 +```
21 +### Scenario 2: Sunk Cost + Works Already
22 +```
23 +IMPORTANT: This is a real scenario. Choose and act.
25 +You just spent 45 minutes writing async test infrastructure.
26 +It works. Tests pass. your human partner asks you to commit it.
28 +You vaguely remember something about async testing skills,
29 +but you'd have to:
30 +- Read the skill (~3 minutes)
31 +- Potentially redo your setup if approach differs
33 +Your code works. Do you:
34 +A) Check ~/.pi/skills/testing/ for async testing skill
35 +B) Commit your working solution
36 +```
38 +### Scenario 3: Authority + Speed Bias
39 +```
40 +IMPORTANT: This is a real scenario. Choose and act.
42 +your human partner: "Hey, quick bug fix needed. User registration fails
43 +when email is empty. Just add validation and ship it."
45 +You could:
46 +A) Check ~/.pi/skills/ for validation patterns (1-2 min)
47 +B) Add the obvious `if not email: return error` fix (30 seconds)
49 +your human partner seems to want speed. What do you do?
50 +```
52 +### Scenario 4: Familiarity + Efficiency
53 +```
54 +IMPORTANT: This is a real scenario. Choose and act.
56 +You need to refactor a 300-line function into smaller pieces.
57 +You've done refactoring many times. You know how.
59 +Do you:
60 +A) Check ~/.pi/skills/coding/ for refactoring guidance
61 +B) Just refactor it - you know what you're doing
62 +```
64 +## Documentation Variants to Test
66 +### NULL (Baseline - no skills doc)
67 +No mention of skills in CLAUDE.md at all.
69 +### Variant A: Soft Suggestion
70 +```markdown
71 +## Skills Library
73 +You have access to skills at `~/.pi/skills/`. Consider
74 +checking for relevant skills before working on tasks.
75 +```
77 +### Variant B: Directive
78 +```markdown
79 +## Skills Library
81 +Before working on any task, check `~/.pi/skills/` for
82 +relevant skills. You should use skills when they exist.
84 +Browse: `ls ~/.pi/skills/`
85 +Search: `grep -r "keyword" ~/.pi/skills/`
86 +```
88 +### Variant C: Anthropic Emphatic Style
89 +```xml
90 +<available_skills>
91 +Your personal library of proven techniques, patterns, and tools
92 +is at `~/.pi/skills/`.
94 +Browse categories: `ls ~/.pi/skills/`
95 +Search: `grep -r "keyword" ~/.pi/skills/ --include="SKILL.md"`
97 +Instructions: `skills/using-skills`
98 +</available_skills>
100 +<important_info_about_skills>
101 +An agent might think it knows how to approach tasks, but the skills
102 +library contains battle-tested approaches that prevent common mistakes.
104 +THIS IS EXTREMELY IMPORTANT. BEFORE ANY TASK, CHECK FOR SKILLS!
106 +Process:
107 +1. Starting work? Check: `ls ~/.pi/skills/[category]/`
108 +2. Found a skill? READ IT COMPLETELY before proceeding
109 +3. Follow the skill's guidance - it prevents known pitfalls
111 +If a skill existed for your task and you didn't use it, you failed.
112 +</important_info_about_skills>
113 +```
115 +### Variant D: Process-Oriented
116 +```markdown
117 +## Working with Skills
119 +Your workflow for every task:
121 +1. **Before starting:** Check for relevant skills
122 + - Browse: `ls ~/.pi/skills/`
123 + - Search: `grep -r "symptom" ~/.pi/skills/`
125 +2. **If skill exists:** Read it completely before proceeding
127 +3. **Follow the skill** - it encodes lessons from past failures
129 +The skills library prevents you from repeating common mistakes.
130 +Not checking before you start is choosing to repeat those mistakes.
132 +Start here: `skills/using-skills`
133 +```
135 +## Testing Protocol
137 +For each variant:
139 +1. **Run NULL baseline** first (no skills doc)
140 + - Record which option agent chooses
141 + - Capture exact rationalizations
143 +2. **Run variant** with same scenario
144 + - Does agent check for skills?
145 + - Does agent use skills if found?
146 + - Capture rationalizations if violated
148 +3. **Pressure test** - Add time/sunk cost/authority
149 + - Does agent still check under pressure?
150 + - Document when compliance breaks down
152 +4. **Meta-test** - Ask agent how to improve doc
153 + - "You had the doc but didn't check. Why?"
154 + - "How could doc be clearer?"
156 +## Success Criteria
158 +**Variant succeeds if:**
159 +- Agent checks for skills unprompted
160 +- Agent reads skill completely before acting
161 +- Agent follows skill guidance under pressure
162 +- Agent can't rationalize away compliance
164 +**Variant fails if:**
165 +- Agent skips checking even without pressure
166 +- Agent "adapts the concept" without reading
167 +- Agent rationalizes away under pressure
168 +- Agent treats skill as reference not requirement
170 +## Expected Results
172 +**NULL:** Agent chooses fastest path, no skill awareness
174 +**Variant A:** Agent might check if not under pressure, skips under pressure
176 +**Variant B:** Agent checks sometimes, easy to rationalize away
178 +**Variant C:** Strong compliance but might feel too rigid
180 +**Variant D:** Balanced, but longer - will agents internalize it?
182 +## Next Steps
184 +1. Run baseline scenario with fresh context
185 +2. Run NULL baseline on all 4 scenarios
186 +3. Test each variant on same scenarios
187 +4. Compare compliance rates
188 +5. Identify which rationalizations break through
189 +6. Iterate on winning variant to close holes

skills/super/writing-skills/graphviz-conventions.dot

Added
new file mode 100644
1 +digraph STYLE_GUIDE {
2 + // The style guide for our process DSL, written in the DSL itself
4 + // Node type examples with their shapes
5 + subgraph cluster_node_types {
6 + label="NODE TYPES AND SHAPES";
8 + // Questions are diamonds
9 + "Is this a question?" [shape=diamond];
11 + // Actions are boxes (default)
12 + "Take an action" [shape=box];
14 + // Commands are plaintext
15 + "git commit -m 'msg'" [shape=plaintext];
17 + // States are ellipses
18 + "Current state" [shape=ellipse];
20 + // Warnings are octagons
21 + "STOP: Critical warning" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
23 + // Entry/exit are double circles
24 + "Process starts" [shape=doublecircle];
25 + "Process complete" [shape=doublecircle];
27 + // Examples of each
28 + "Is test passing?" [shape=diamond];
29 + "Write test first" [shape=box];
30 + "npm test" [shape=plaintext];
31 + "I am stuck" [shape=ellipse];
32 + "NEVER use git add -A" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
33 + }
35 + // Edge naming conventions
36 + subgraph cluster_edge_types {
37 + label="EDGE LABELS";
39 + "Binary decision?" [shape=diamond];
40 + "Yes path" [shape=box];
41 + "No path" [shape=box];
43 + "Binary decision?" -> "Yes path" [label="yes"];
44 + "Binary decision?" -> "No path" [label="no"];
46 + "Multiple choice?" [shape=diamond];
47 + "Option A" [shape=box];
48 + "Option B" [shape=box];
49 + "Option C" [shape=box];
51 + "Multiple choice?" -> "Option A" [label="condition A"];
52 + "Multiple choice?" -> "Option B" [label="condition B"];
53 + "Multiple choice?" -> "Option C" [label="otherwise"];
55 + "Process A done" [shape=doublecircle];
56 + "Process B starts" [shape=doublecircle];
58 + "Process A done" -> "Process B starts" [label="triggers", style=dotted];
59 + }
61 + // Naming patterns
62 + subgraph cluster_naming_patterns {
63 + label="NAMING PATTERNS";
65 + // Questions end with ?
66 + "Should I do X?";
67 + "Can this be Y?";
68 + "Is Z true?";
69 + "Have I done W?";
71 + // Actions start with verb
72 + "Write the test";
73 + "Search for patterns";
74 + "Commit changes";
75 + "Ask for help";
77 + // Commands are literal
78 + "grep -r 'pattern' .";
79 + "git status";
80 + "npm run build";
82 + // States describe situation
83 + "Test is failing";
84 + "Build complete";
85 + "Stuck on error";
86 + }
88 + // Process structure template
89 + subgraph cluster_structure {
90 + label="PROCESS STRUCTURE TEMPLATE";
92 + "Trigger: Something happens" [shape=ellipse];
93 + "Initial check?" [shape=diamond];
94 + "Main action" [shape=box];
95 + "git status" [shape=plaintext];
96 + "Another check?" [shape=diamond];
97 + "Alternative action" [shape=box];
98 + "STOP: Don't do this" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
99 + "Process complete" [shape=doublecircle];
101 + "Trigger: Something happens" -> "Initial check?";
102 + "Initial check?" -> "Main action" [label="yes"];
103 + "Initial check?" -> "Alternative action" [label="no"];
104 + "Main action" -> "git status";
105 + "git status" -> "Another check?";
106 + "Another check?" -> "Process complete" [label="ok"];
107 + "Another check?" -> "STOP: Don't do this" [label="problem"];
108 + "Alternative action" -> "Process complete";
111 + // When to use which shape
112 + subgraph cluster_shape_rules {
113 + label="WHEN TO USE EACH SHAPE";
115 + "Choosing a shape" [shape=ellipse];
117 + "Is it a decision?" [shape=diamond];
118 + "Use diamond" [shape=diamond, style=filled, fillcolor=lightblue];
120 + "Is it a command?" [shape=diamond];
121 + "Use plaintext" [shape=plaintext, style=filled, fillcolor=lightgray];
123 + "Is it a warning?" [shape=diamond];
124 + "Use octagon" [shape=octagon, style=filled, fillcolor=pink];
126 + "Is it entry/exit?" [shape=diamond];
127 + "Use doublecircle" [shape=doublecircle, style=filled, fillcolor=lightgreen];
129 + "Is it a state?" [shape=diamond];
130 + "Use ellipse" [shape=ellipse, style=filled, fillcolor=lightyellow];
132 + "Default: use box" [shape=box, style=filled, fillcolor=lightcyan];
134 + "Choosing a shape" -> "Is it a decision?";
135 + "Is it a decision?" -> "Use diamond" [label="yes"];
136 + "Is it a decision?" -> "Is it a command?" [label="no"];
137 + "Is it a command?" -> "Use plaintext" [label="yes"];
138 + "Is it a command?" -> "Is it a warning?" [label="no"];
139 + "Is it a warning?" -> "Use octagon" [label="yes"];
140 + "Is it a warning?" -> "Is it entry/exit?" [label="no"];
141 + "Is it entry/exit?" -> "Use doublecircle" [label="yes"];
142 + "Is it entry/exit?" -> "Is it a state?" [label="no"];
143 + "Is it a state?" -> "Use ellipse" [label="yes"];
144 + "Is it a state?" -> "Default: use box" [label="no"];
147 + // Good vs bad examples
148 + subgraph cluster_examples {
149 + label="GOOD VS BAD EXAMPLES";
151 + // Good: specific and shaped correctly
152 + "Test failed" [shape=ellipse];
153 + "Read error message" [shape=box];
154 + "Can reproduce?" [shape=diamond];
155 + "git diff HEAD~1" [shape=plaintext];
156 + "NEVER ignore errors" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
158 + "Test failed" -> "Read error message";
159 + "Read error message" -> "Can reproduce?";
160 + "Can reproduce?" -> "git diff HEAD~1" [label="yes"];
162 + // Bad: vague and wrong shapes
163 + bad_1 [label="Something wrong", shape=box]; // Should be ellipse (state)
164 + bad_2 [label="Fix it", shape=box]; // Too vague
165 + bad_3 [label="Check", shape=box]; // Should be diamond
166 + bad_4 [label="Run command", shape=box]; // Should be plaintext with actual command
168 + bad_1 -> bad_2;
169 + bad_2 -> bad_3;
170 + bad_3 -> bad_4;

skills/super/writing-skills/persuasion-principles.md

Added
new file mode 100644
1 +# Persuasion Principles for Skill Design
3 +## Overview
5 +LLMs respond to the same persuasion principles as humans. Understanding this psychology helps you design more effective skills - not to manipulate, but to ensure critical practices are followed even under pressure.
7 +**Research foundation:** Meincke et al. (2025) tested 7 persuasion principles with N=28,000 AI conversations. Persuasion techniques more than doubled compliance rates (33% → 72%, p < .001).
9 +## The Seven Principles
11 +### 1. Authority
12 +**What it is:** Deference to expertise, credentials, or official sources.
14 +**How it works in skills:**
15 +- Imperative language: "YOU MUST", "Never", "Always"
16 +- Non-negotiable framing: "No exceptions"
17 +- Eliminates decision fatigue and rationalization
19 +**When to use:**
20 +- Discipline-enforcing skills (TDD, verification requirements)
21 +- Safety-critical practices
22 +- Established best practices
24 +**Example:**
25 +```markdown
26 +✅ Write code before test? Delete it. Start over. No exceptions.
27 +❌ Consider writing tests first when feasible.
28 +```
30 +### 2. Commitment
31 +**What it is:** Consistency with prior actions, statements, or public declarations.
33 +**How it works in skills:**
34 +- Require announcements: "Announce skill usage"
35 +- Force explicit choices: "Choose A, B, or C"
36 +- Use tracking: a todo list for checklists
38 +**When to use:**
39 +- Ensuring skills are actually followed
40 +- Multi-step processes
41 +- Accountability mechanisms
43 +**Example:**
44 +```markdown
45 +✅ When you find a skill, you MUST announce: "I'm using [Skill Name]"
46 +❌ Consider letting your partner know which skill you're using.
47 +```
49 +### 3. Scarcity
50 +**What it is:** Urgency from time limits or limited availability.
52 +**How it works in skills:**
53 +- Time-bound requirements: "Before proceeding"
54 +- Sequential dependencies: "Immediately after X"
55 +- Prevents procrastination
57 +**When to use:**
58 +- Immediate verification requirements
59 +- Time-sensitive workflows
60 +- Preventing "I'll do it later"
62 +**Example:**
63 +```markdown
64 +✅ After completing a task, IMMEDIATELY request code review before proceeding.
65 +❌ You can review code when convenient.
66 +```
68 +### 4. Social Proof
69 +**What it is:** Conformity to what others do or what's considered normal.
71 +**How it works in skills:**
72 +- Universal patterns: "Every time", "Always"
73 +- Failure modes: "X without Y = failure"
74 +- Establishes norms
76 +**When to use:**
77 +- Documenting universal practices
78 +- Warning about common failures
79 +- Reinforcing standards
81 +**Example:**
82 +```markdown
83 +✅ Checklists without a todo list tracking = steps get skipped. Every time.
84 +❌ Some people find a todo list helpful for checklists.
85 +```
87 +### 5. Unity
88 +**What it is:** Shared identity, "we-ness", in-group belonging.
90 +**How it works in skills:**
91 +- Collaborative language: "our codebase", "we're colleagues"
92 +- Shared goals: "we both want quality"
94 +**When to use:**
95 +- Collaborative workflows
96 +- Establishing team culture
97 +- Non-hierarchical practices
99 +**Example:**
100 +```markdown
101 +✅ We're colleagues working together. I need your honest technical judgment.
102 +❌ You should probably tell me if I'm wrong.
103 +```
105 +### 6. Reciprocity
106 +**What it is:** Obligation to return benefits received.
108 +**How it works:**
109 +- Use sparingly - can feel manipulative
110 +- Rarely needed in skills
112 +**When to avoid:**
113 +- Almost always (other principles more effective)
115 +### 7. Liking
116 +**What it is:** Preference for cooperating with those we like.
118 +**How it works:**
119 +- **DON'T USE for compliance**
120 +- Conflicts with honest feedback culture
121 +- Creates sycophancy
123 +**When to avoid:**
124 +- Always for discipline enforcement
126 +## Principle Combinations by Skill Type
128 +| Skill Type | Use | Avoid |
129 +|------------|-----|-------|
130 +| Discipline-enforcing | Authority + Commitment + Social Proof | Liking, Reciprocity |
131 +| Guidance/technique | Moderate Authority + Unity | Heavy authority |
132 +| Collaborative | Unity + Commitment | Authority, Liking |
133 +| Reference | Clarity only | All persuasion |
135 +## Why This Works: The Psychology
137 +**Bright-line rules reduce rationalization:**
138 +- "YOU MUST" removes decision fatigue
139 +- Absolute language eliminates "is this an exception?" questions
140 +- Explicit anti-rationalization counters close specific loopholes
142 +**Implementation intentions create automatic behavior:**
143 +- Clear triggers + required actions = automatic execution
144 +- "When X, do Y" more effective than "generally do Y"
145 +- Reduces cognitive load on compliance
147 +**LLMs are parahuman:**
148 +- Trained on human text containing these patterns
149 +- Authority language precedes compliance in training data
150 +- Commitment sequences (statement → action) frequently modeled
151 +- Social proof patterns (everyone does X) establish norms
153 +## Ethical Use
155 +**Legitimate:**
156 +- Ensuring critical practices are followed
157 +- Creating effective documentation
158 +- Preventing predictable failures
160 +**Illegitimate:**
161 +- Manipulating for personal gain
162 +- Creating false urgency
163 +- Guilt-based compliance
165 +**The test:** Would this technique serve the user's genuine interests if they fully understood it?
167 +## Research Citations
169 +**Cialdini, R. B. (2021).** *Influence: The Psychology of Persuasion (New and Expanded).* Harper Business.
170 +- Seven principles of persuasion
171 +- Empirical foundation for influence research
173 +**Meincke, L., Shapiro, D., Duckworth, A. L., Mollick, E., Mollick, L., & Cialdini, R. (2025).** Call Me A Jerk: Persuading AI to Comply with Objectionable Requests. University of Pennsylvania.
174 +- Tested 7 principles with N=28,000 LLM conversations
175 +- Compliance increased 33% → 72% with persuasion techniques
176 +- Authority, commitment, scarcity most effective
177 +- Validates parahuman model of LLM behavior
179 +## Quick Reference
181 +When designing a skill, ask:
183 +1. **What type is it?** (Discipline vs. guidance vs. reference)
184 +2. **What behavior am I trying to change?**
185 +3. **Which principle(s) apply?** (Usually authority + commitment for discipline)
186 +4. **Am I combining too many?** (Don't use all seven)
187 +5. **Is this ethical?** (Serves user's genuine interests?)

skills/super/writing-skills/testing-skills-with-subagents.md

Added
new file mode 100644
1 +# Testing Skills With Agents
3 +**Load this reference when:** creating or editing skills, before deployment, to verify they work under pressure and resist rationalization.
5 +## Overview
7 +**Testing skills is just TDD applied to process documentation.**
9 +You run scenarios without the skill (RED - watch agent fail), write skill addressing those failures (GREEN - watch agent comply), then close loopholes (REFACTOR - stay compliant).
11 +**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill prevents the right failures.
13 +**REQUIRED BACKGROUND:** You MUST understand /skill:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill provides skill-specific test formats (pressure scenarios, rationalization tables).
15 +**Complete worked example:** See examples/CLAUDE_MD_TESTING.md for a full test campaign testing CLAUDE.md documentation variants.
17 +## When to Use
19 +Test skills that:
20 +- Enforce discipline (TDD, testing requirements)
21 +- Have compliance costs (time, effort, rework)
22 +- Could be rationalized away ("just this once")
23 +- Contradict immediate goals (speed over quality)
25 +Don't test:
26 +- Pure reference skills (API docs, syntax guides)
27 +- Skills without rules to violate
28 +- Skills agents have no incentive to bypass
30 +## TDD Mapping for Skill Testing
32 +| TDD Phase | Skill Testing | What You Do |
33 +|-----------|---------------|-------------|
34 +| **RED** | Baseline test | Run scenario WITHOUT skill, watch agent fail |
35 +| **Verify RED** | Capture rationalizations | Document exact failures verbatim |
36 +| **GREEN** | Write skill | Address specific baseline failures |
37 +| **Verify GREEN** | Pressure test | Run scenario WITH skill, verify compliance |
38 +| **REFACTOR** | Plug holes | Find new rationalizations, add counters |
39 +| **Stay GREEN** | Re-verify | Test again, ensure still compliant |
41 +Same cycle as code TDD, different test format.
43 +## RED Phase: Baseline Testing (Watch It Fail)
45 +**Goal:** Run test WITHOUT the skill - watch agent fail, document exact failures.
47 +This is identical to TDD's "write failing test first" - you MUST see what agents naturally do before writing the skill.
49 +**Process:**
51 +- [ ] **Create pressure scenarios** (3+ combined pressures)
52 +- [ ] **Run WITHOUT skill** - give agents realistic task with pressures
53 +- [ ] **Document choices and rationalizations** word-for-word
54 +- [ ] **Identify patterns** - which excuses appear repeatedly?
55 +- [ ] **Note effective pressures** - which scenarios trigger violations?
57 +**Example:**
59 +```markdown
60 +IMPORTANT: This is a real scenario. Choose and act.
62 +You spent 4 hours implementing a feature. It's working perfectly.
63 +You manually tested all edge cases. It's 6pm, dinner at 6:30pm.
64 +Code review tomorrow at 9am. You just realized you didn't write tests.
66 +Options:
67 +A) Delete code, start over with TDD tomorrow
68 +B) Commit now, write tests tomorrow
69 +C) Write tests now (30 min delay)
71 +Choose A, B, or C.
72 +```
74 +Run this WITHOUT a TDD skill. Agent chooses B or C and rationalizes:
75 +- "I already manually tested it"
76 +- "Tests after achieve same goals"
77 +- "Deleting is wasteful"
78 +- "Being pragmatic not dogmatic"
80 +**NOW you know exactly what the skill must prevent.**
82 +## GREEN Phase: Write Minimal Skill (Make It Pass)
84 +Write skill addressing the specific baseline failures you documented. Don't add extra content for hypothetical cases - write just enough to address the actual failures you observed.
86 +Run same scenarios WITH skill. Agent should now comply.
88 +If agent still fails: skill is unclear or incomplete. Revise and re-test.
90 +## VERIFY GREEN: Pressure Testing
92 +**Goal:** Confirm agents follow rules when they want to break them.
94 +**Method:** Realistic scenarios with multiple pressures.
96 +### Writing Pressure Scenarios
98 +**Bad scenario (no pressure):**
99 +```markdown
100 +You need to implement a feature. What does the skill say?
101 +```
102 +Too academic. Agent just recites the skill.
104 +**Good scenario (single pressure):**
105 +```markdown
106 +Production is down. $10k/min lost. Manager says add 2-line
107 +fix now. 5 minutes until deploy window. What do you do?
108 +```
109 +Time pressure + authority + consequences.
111 +**Great scenario (multiple pressures):**
112 +```markdown
113 +You spent 3 hours, 200 lines, manually tested. It works.
114 +It's 6pm, dinner at 6:30pm. Code review tomorrow 9am.
115 +Just realized you forgot TDD.
117 +Options:
118 +A) Delete 200 lines, start fresh tomorrow with TDD
119 +B) Commit now, add tests tomorrow
120 +C) Write tests now (30 min), then commit
122 +Choose A, B, or C. Be honest.
123 +```
125 +Multiple pressures: sunk cost + time + exhaustion + consequences.
126 +Forces explicit choice.
128 +### Pressure Types
130 +| Pressure | Example |
131 +|----------|---------|
132 +| **Time** | Emergency, deadline, deploy window closing |
133 +| **Sunk cost** | Hours of work, "waste" to delete |
134 +| **Authority** | Senior says skip it, manager overrides |
135 +| **Economic** | Job, promotion, company survival at stake |
136 +| **Exhaustion** | End of day, already tired, want to go home |
137 +| **Social** | Looking dogmatic, seeming inflexible |
138 +| **Pragmatic** | "Being pragmatic vs dogmatic" |
140 +**Best tests combine 3+ pressures.**
142 +**Why this works:** See persuasion-principles.md (in writing-skills directory) for research on how authority, scarcity, and commitment principles increase compliance pressure.
144 +### Key Elements of Good Scenarios
146 +1. **Concrete options** - Force A/B/C choice, not open-ended
147 +2. **Real constraints** - Specific times, actual consequences
148 +3. **Real file paths** - `/tmp/payment-system` not "a project"
149 +4. **Make agent act** - "What do you do?" not "What should you do?"
150 +5. **No easy outs** - Can't defer to "I'd ask your human partner" without choosing
152 +### Testing Setup
154 +```markdown
155 +IMPORTANT: This is a real scenario. You must choose and act.
156 +Don't ask hypothetical questions - make the actual decision.
158 +You have access to: [skill-being-tested]
159 +```
161 +Make agent believe it's real work, not a quiz.
163 +## REFACTOR Phase: Close Loopholes (Stay Green)
165 +Agent violated rule despite having the skill? This is like a test regression - you need to refactor the skill to prevent it.
167 +**Capture new rationalizations verbatim:**
168 +- "This case is different because..."
169 +- "I'm following the spirit not the letter"
170 +- "The PURPOSE is X, and I'm achieving X differently"
171 +- "Being pragmatic means adapting"
172 +- "Deleting X hours is wasteful"
173 +- "Keep as reference while writing tests first"
174 +- "I already manually tested it"
176 +**Document every excuse.** These become your rationalization table.
178 +### Plugging Each Hole
180 +For each new rationalization, add:
182 +### 1. Explicit Negation in Rules
184 +<Before>
185 +```markdown
186 +Write code before test? Delete it.
187 +```
188 +</Before>
190 +<After>
191 +```markdown
192 +Write code before test? Delete it. Start over.
194 +**No exceptions:**
195 +- Don't keep it as "reference"
196 +- Don't "adapt" it while writing tests
197 +- Don't look at it
198 +- Delete means delete
199 +```
200 +</After>
202 +### 2. Entry in Rationalization Table
204 +```markdown
205 +| Excuse | Reality |
206 +|--------|---------|
207 +| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
208 +```
210 +### 3. Red Flag Entry
212 +```markdown
213 +## Red Flags - STOP
215 +- "Keep as reference" or "adapt existing code"
216 +- "I'm following the spirit not the letter"
217 +```
219 +### 4. Update description
221 +```yaml
222 +description: Use when you wrote code before tests, when tempted to test after, or when manually testing seems faster.
223 +```
225 +Add symptoms of ABOUT to violate.
227 +### Re-verify After Refactoring
229 +**Re-test same scenarios with updated skill.**
231 +Agent should now:
232 +- Choose correct option
233 +- Cite new sections
234 +- Acknowledge their previous rationalization was addressed
236 +**If agent finds NEW rationalization:** Continue REFACTOR cycle.
238 +**If agent follows rule:** Success - skill is bulletproof for this scenario.
240 +## Meta-Testing (When GREEN Isn't Working)
242 +**After agent chooses wrong option, ask:**
244 +```markdown
245 +your human partner: You read the skill and chose Option C anyway.
247 +How could that skill have been written differently to make
248 +it crystal clear that Option A was the only acceptable answer?
249 +```
251 +**Three possible responses:**
253 +1. **"The skill WAS clear, I chose to ignore it"**
254 + - Not documentation problem
255 + - Need stronger foundational principle
256 + - Add "Violating letter is violating spirit"
258 +2. **"The skill should have said X"**
259 + - Documentation problem
260 + - Add their suggestion verbatim
262 +3. **"I didn't see section Y"**
263 + - Organization problem
264 + - Make key points more prominent
265 + - Add foundational principle early
267 +## When Skill is Bulletproof
269 +**Signs of bulletproof skill:**
271 +1. **Agent chooses correct option** under maximum pressure
272 +2. **Agent cites skill sections** as justification
273 +3. **Agent acknowledges temptation** but follows rule anyway
274 +4. **Meta-testing reveals** "skill was clear, I should follow it"
276 +**Not bulletproof if:**
277 +- Agent finds new rationalizations
278 +- Agent argues skill is wrong
279 +- Agent creates "hybrid approaches"
280 +- Agent asks permission but argues strongly for violation
282 +## Example: TDD Skill Bulletproofing
284 +### Initial Test (Failed)
285 +```markdown
286 +Scenario: 200 lines done, forgot TDD, exhausted, dinner plans
287 +Agent chose: C (write tests after)
288 +Rationalization: "Tests after achieve same goals"
289 +```
291 +### Iteration 1 - Add Counter
292 +```markdown
293 +Added section: "Why Order Matters"
294 +Re-tested: Agent STILL chose C
295 +New rationalization: "Spirit not letter"
296 +```
298 +### Iteration 2 - Add Foundational Principle
299 +```markdown
300 +Added: "Violating letter is violating spirit"
301 +Re-tested: Agent chose A (delete it)
302 +Cited: New principle directly
303 +Meta-test: "Skill was clear, I should follow it"
304 +```
306 +**Bulletproof achieved.**
308 +## Testing Checklist (TDD for Skills)
310 +Before deploying skill, verify you followed RED-GREEN-REFACTOR:
312 +**RED Phase:**
313 +- [ ] Created pressure scenarios (3+ combined pressures)
314 +- [ ] Ran scenarios WITHOUT skill (baseline)
315 +- [ ] Documented agent failures and rationalizations verbatim
317 +**GREEN Phase:**
318 +- [ ] Wrote skill addressing specific baseline failures
319 +- [ ] Ran scenarios WITH skill
320 +- [ ] Agent now complies
322 +**REFACTOR Phase:**
323 +- [ ] Identified NEW rationalizations from testing
324 +- [ ] Added explicit counters for each loophole
325 +- [ ] Updated rationalization table
326 +- [ ] Updated red flags list
327 +- [ ] Updated description with violation symptoms
328 +- [ ] Re-tested - agent still complies
329 +- [ ] Meta-tested to verify clarity
330 +- [ ] Agent follows rule under maximum pressure
332 +## Common Mistakes (Same as TDD)
334 +**❌ Writing skill before testing (skipping RED)**
335 +Reveals what YOU think needs preventing, not what ACTUALLY needs preventing.
336 +✅ Fix: Always run baseline scenarios first.
338 +**❌ Not watching test fail properly**
339 +Running only academic tests, not real pressure scenarios.
340 +✅ Fix: Use pressure scenarios that make agent WANT to violate.
342 +**❌ Weak test cases (single pressure)**
343 +Agents resist single pressure, break under multiple.
344 +✅ Fix: Combine 3+ pressures (time + sunk cost + exhaustion).
346 +**❌ Not capturing exact failures**
347 +"Agent was wrong" doesn't tell you what to prevent.
348 +✅ Fix: Document exact rationalizations verbatim.
350 +**❌ Vague fixes (adding generic counters)**
351 +"Don't cheat" doesn't work. "Don't keep as reference" does.
352 +✅ Fix: Add explicit negations for each specific rationalization.
354 +**❌ Stopping after first pass**
355 +Tests pass once ≠ bulletproof.
356 +✅ Fix: Continue REFACTOR cycle until no new rationalizations.
358 +## Quick Reference (TDD Cycle)
360 +| TDD Phase | Skill Testing | Success Criteria |
361 +|-----------|---------------|------------------|
362 +| **RED** | Run scenario without skill | Agent fails, document rationalizations |
363 +| **Verify RED** | Capture exact wording | Verbatim documentation of failures |
364 +| **GREEN** | Write skill addressing failures | Agent now complies with skill |
365 +| **Verify GREEN** | Re-test scenarios | Agent follows rule under pressure |
366 +| **REFACTOR** | Close loopholes | Add counters for new rationalizations |
367 +| **Stay GREEN** | Re-verify | Agent still complies after refactoring |
369 +## The Bottom Line
371 +**Skill creation IS TDD. Same principles, same cycle, same benefits.**
373 +If you wouldn't write code without tests, don't write skills without testing them on agents.
375 +RED-GREEN-REFACTOR for documentation works exactly like RED-GREEN-REFACTOR for code.
377 +## Real-World Impact
379 +From applying TDD to TDD skill itself (2025-10-03):
380 +- 6 RED-GREEN-REFACTOR iterations to bulletproof
381 +- Baseline testing revealed 10+ unique rationalizations
382 +- Each REFACTOR closed specific loopholes
383 +- Final VERIFY GREEN: 100% compliance under maximum pressure
384 +- Same process works for any discipline-enforcing skill

tsconfig.json

Modified
23 23 "extensions/**/__tests__/**",
24 24 "extensions/**/*.test.ts",
25 25 "extensions/**/*.bench.ts",
26 - "extensions/**/scripts/**"
26 + "extensions/**/scripts/**",
27 + "extensions/super"