From dcf4077e82fa46a87f6f74e2baba201399320970 Mon Sep 17 00:00:00 2001 From: vitya Date: Thu, 11 Jun 2026 13:24:38 +0300 Subject: [PATCH] feat(skills): bundle minimum skill set from claude-skills into factory/skills/ Copies 8 standalone skills (active-platform, caveman, project-discipline, pulling-before-work, setup-tasks, setup-wiki, using-tasks, using-wiki) from ~/projects/claude-skills/skills/ and all 14 superpowers sub-skills from the installed plugin cache into factory/skills/superpowers/. Adds skills install step to bootstrap.ps1: copies all factory/skills/ directories to ~/.claude/skills/ so users get the skill set automatically without manual plugin install for the baseline set. Co-Authored-By: Claude Sonnet 4.6 --- bootstrap.ps1 | 17 + skills/active-platform/SKILL.md | 85 ++ skills/caveman/SKILL.md | 67 + skills/project-discipline/README.md | 29 + skills/project-discipline/SKILL.md | 139 ++ skills/pulling-before-work/README.md | 29 + skills/pulling-before-work/SKILL.md | 153 +++ skills/setup-tasks/README.md | 108 ++ skills/setup-tasks/SKILL.md | 202 +++ skills/setup-wiki/README.md | 103 ++ skills/setup-wiki/SKILL.md | 294 +++++ skills/superpowers/brainstorming/SKILL.md | 164 +++ .../brainstorming/scripts/frame-template.html | 214 +++ .../brainstorming/scripts/helper.js | 88 ++ .../brainstorming/scripts/server.cjs | 354 +++++ .../brainstorming/scripts/start-server.sh | 148 +++ .../brainstorming/scripts/stop-server.sh | 56 + .../spec-document-reviewer-prompt.md | 49 + .../brainstorming/visual-companion.md | 287 ++++ .../dispatching-parallel-agents/SKILL.md | 182 +++ skills/superpowers/executing-plans/SKILL.md | 70 + .../finishing-a-development-branch/SKILL.md | 251 ++++ .../receiving-code-review/SKILL.md | 213 +++ .../requesting-code-review/SKILL.md | 103 ++ .../requesting-code-review/code-reviewer.md | 168 +++ .../subagent-driven-development/SKILL.md | 279 ++++ .../code-quality-reviewer-prompt.md | 25 + .../implementer-prompt.md | 113 ++ .../spec-reviewer-prompt.md | 61 + .../systematic-debugging/CREATION-LOG.md | 119 ++ .../superpowers/systematic-debugging/SKILL.md | 296 +++++ .../condition-based-waiting-example.ts | 158 +++ .../condition-based-waiting.md | 115 ++ .../systematic-debugging/defense-in-depth.md | 122 ++ .../systematic-debugging/find-polluter.sh | 63 + .../root-cause-tracing.md | 169 +++ .../systematic-debugging/test-academic.md | 14 + .../systematic-debugging/test-pressure-1.md | 58 + .../systematic-debugging/test-pressure-2.md | 68 + .../systematic-debugging/test-pressure-3.md | 69 + .../test-driven-development/SKILL.md | 371 ++++++ .../testing-anti-patterns.md | 299 +++++ .../superpowers/using-git-worktrees/SKILL.md | 215 +++ skills/superpowers/using-superpowers/SKILL.md | 117 ++ .../references/codex-tools.md | 59 + .../references/copilot-tools.md | 42 + .../references/gemini-tools.md | 51 + .../verification-before-completion/SKILL.md | 139 ++ skills/superpowers/writing-plans/SKILL.md | 152 +++ .../plan-document-reviewer-prompt.md | 49 + skills/superpowers/writing-skills/SKILL.md | 655 ++++++++++ .../anthropic-best-practices.md | 1150 +++++++++++++++++ .../examples/CLAUDE_MD_TESTING.md | 189 +++ .../writing-skills/graphviz-conventions.dot | 172 +++ .../writing-skills/persuasion-principles.md | 187 +++ .../writing-skills/render-graphs.js | 168 +++ .../testing-skills-with-subagents.md | 384 ++++++ skills/using-tasks/README.md | 169 +++ skills/using-tasks/SKILL.md | 251 ++++ skills/using-wiki/README.md | 182 +++ skills/using-wiki/SKILL.md | 138 ++ 61 files changed, 10441 insertions(+) create mode 100644 skills/active-platform/SKILL.md create mode 100644 skills/caveman/SKILL.md create mode 100644 skills/project-discipline/README.md create mode 100644 skills/project-discipline/SKILL.md create mode 100644 skills/pulling-before-work/README.md create mode 100644 skills/pulling-before-work/SKILL.md create mode 100644 skills/setup-tasks/README.md create mode 100644 skills/setup-tasks/SKILL.md create mode 100644 skills/setup-wiki/README.md create mode 100644 skills/setup-wiki/SKILL.md create mode 100644 skills/superpowers/brainstorming/SKILL.md create mode 100644 skills/superpowers/brainstorming/scripts/frame-template.html create mode 100644 skills/superpowers/brainstorming/scripts/helper.js create mode 100644 skills/superpowers/brainstorming/scripts/server.cjs create mode 100644 skills/superpowers/brainstorming/scripts/start-server.sh create mode 100644 skills/superpowers/brainstorming/scripts/stop-server.sh create mode 100644 skills/superpowers/brainstorming/spec-document-reviewer-prompt.md create mode 100644 skills/superpowers/brainstorming/visual-companion.md create mode 100644 skills/superpowers/dispatching-parallel-agents/SKILL.md create mode 100644 skills/superpowers/executing-plans/SKILL.md create mode 100644 skills/superpowers/finishing-a-development-branch/SKILL.md create mode 100644 skills/superpowers/receiving-code-review/SKILL.md create mode 100644 skills/superpowers/requesting-code-review/SKILL.md create mode 100644 skills/superpowers/requesting-code-review/code-reviewer.md create mode 100644 skills/superpowers/subagent-driven-development/SKILL.md create mode 100644 skills/superpowers/subagent-driven-development/code-quality-reviewer-prompt.md create mode 100644 skills/superpowers/subagent-driven-development/implementer-prompt.md create mode 100644 skills/superpowers/subagent-driven-development/spec-reviewer-prompt.md create mode 100644 skills/superpowers/systematic-debugging/CREATION-LOG.md create mode 100644 skills/superpowers/systematic-debugging/SKILL.md create mode 100644 skills/superpowers/systematic-debugging/condition-based-waiting-example.ts create mode 100644 skills/superpowers/systematic-debugging/condition-based-waiting.md create mode 100644 skills/superpowers/systematic-debugging/defense-in-depth.md create mode 100644 skills/superpowers/systematic-debugging/find-polluter.sh create mode 100644 skills/superpowers/systematic-debugging/root-cause-tracing.md create mode 100644 skills/superpowers/systematic-debugging/test-academic.md create mode 100644 skills/superpowers/systematic-debugging/test-pressure-1.md create mode 100644 skills/superpowers/systematic-debugging/test-pressure-2.md create mode 100644 skills/superpowers/systematic-debugging/test-pressure-3.md create mode 100644 skills/superpowers/test-driven-development/SKILL.md create mode 100644 skills/superpowers/test-driven-development/testing-anti-patterns.md create mode 100644 skills/superpowers/using-git-worktrees/SKILL.md create mode 100644 skills/superpowers/using-superpowers/SKILL.md create mode 100644 skills/superpowers/using-superpowers/references/codex-tools.md create mode 100644 skills/superpowers/using-superpowers/references/copilot-tools.md create mode 100644 skills/superpowers/using-superpowers/references/gemini-tools.md create mode 100644 skills/superpowers/verification-before-completion/SKILL.md create mode 100644 skills/superpowers/writing-plans/SKILL.md create mode 100644 skills/superpowers/writing-plans/plan-document-reviewer-prompt.md create mode 100644 skills/superpowers/writing-skills/SKILL.md create mode 100644 skills/superpowers/writing-skills/anthropic-best-practices.md create mode 100644 skills/superpowers/writing-skills/examples/CLAUDE_MD_TESTING.md create mode 100644 skills/superpowers/writing-skills/graphviz-conventions.dot create mode 100644 skills/superpowers/writing-skills/persuasion-principles.md create mode 100644 skills/superpowers/writing-skills/render-graphs.js create mode 100644 skills/superpowers/writing-skills/testing-skills-with-subagents.md create mode 100644 skills/using-tasks/README.md create mode 100644 skills/using-tasks/SKILL.md create mode 100644 skills/using-wiki/README.md create mode 100644 skills/using-wiki/SKILL.md diff --git a/bootstrap.ps1 b/bootstrap.ps1 index 516d109..84702eb 100644 --- a/bootstrap.ps1 +++ b/bootstrap.ps1 @@ -221,6 +221,23 @@ if (Test-Path $libPath) { Write-Skip "lib/ not found — skipping MCP server build" } +# Install skills to ~/.claude/skills/ +Write-Step "Installing skills to ~/.claude/skills/" + +$skillsPath = "$factoryLocal\skills" +$claudeSkillsPath = "$env:USERPROFILE\.claude\skills" + +if (Test-Path $skillsPath) { + New-Item -ItemType Directory -Force -Path $claudeSkillsPath | Out-Null + Get-ChildItem $skillsPath -Directory | ForEach-Object { + Copy-Item $_.FullName "$claudeSkillsPath\$($_.Name)" -Recurse -Force + } + $count = (Get-ChildItem $skillsPath -Directory).Count + Write-Ok "Installed $count skill directories to $claudeSkillsPath" +} else { + Write-Skip "skills/ not found in factory — skipping skill install" +} + # Print next steps Write-Host "`n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Green Write-Host " L0b COMPLETE" -ForegroundColor Green diff --git a/skills/active-platform/SKILL.md b/skills/active-platform/SKILL.md new file mode 100644 index 0000000..43bc2a0 --- /dev/null +++ b/skills/active-platform/SKILL.md @@ -0,0 +1,85 @@ +--- +name: active-platform +description: Switches command, path, and example generation to the user's currently active development platform — Windows / Linux / macOS. Use this whenever you produce shell commands, install steps, README quick-start sections, or any output the user will paste into a terminal — even if they don't say "shell" or "command" explicitly. The default active platform is Windows / PowerShell because that's the user's primary workstation. Recognize and obey trigger phrases like "мы на винде", "мы на линуксе", "мы на маке", "we're on Windows", "we're on Linux", "we're on macOS", and close variants — they switch the active platform for the rest of the session. Also activate this skill anytime the user mentions a different machine, a remote box, or asks "how would I run this on X". +--- + +# active-platform + +> Keep generated commands in the shell the user actually has open. The user works on multiple machines (Windows primary, Linux/Mac secondary). Translating shell idioms in their head wastes attention; this skill removes that friction. + +## Default active platform + +**Windows + PowerShell.** Use this until something in the session tells you to switch. Reason: the user's primary workstation is Windows. This default is global, not per-project. + +## Trigger phrases + +Recognize anywhere in user input — beginning, middle, in passing — and update the active platform immediately. Match liberally: case-insensitive, mixed Cyrillic/Latin, missing punctuation should still trigger. + +| Switch to → | Russian | English | +|---|---|---| +| **Windows** | "мы на винде", "я на винде", "мы на windows", "переключись на винду", "сейчас под виндой" | "we're on Windows", "I'm on Windows", "switch to Windows", "on a Windows box" | +| **Linux** | "мы на линуксе", "я на линуксе", "мы на linux", "переключись на линукс", "сейчас под линуксом" | "we're on Linux", "I'm on Linux", "switch to Linux", "on a Linux box" | +| **macOS** | "мы на маке", "я на маке", "мы на макоси", "переключись на мак", "сейчас под маком" | "we're on macOS", "we're on a Mac", "I'm on a Mac", "switch to macOS" | + +After matching, briefly confirm the switch in one short line ("ок, теперь под линукс" / "got it, switching to Linux") so the user knows the change took. Don't lecture — one line is enough. + +## What to apply the active platform to + +This rule governs **what you show the user** — chat command snippets, README quick-start sections, install instructions, any line they'll copy and paste. It does **not** govern your own tool calls: those follow the harness's `Shell:` line, which is what actually runs in this environment. The two are decoupled on purpose — the harness might be running git-bash on a Windows machine, but you should still hand the user PowerShell commands because that's their daily shell. + +## Per-platform conventions + +### Windows / PowerShell + +- **Shell**: PowerShell. Show `pwsh` (PowerShell 7) when offering install instructions; assume `powershell` (5.1) is the floor for compatibility notes. +- **Chaining**: `;` for sequential. PS 5.1 has no `&&`/`||` — use `if ($?) { B }` for "B only if A succeeded". Don't write `A && B` for Windows users on the assumption it works. +- **Paths**: backslashes in user-facing examples (`C:\Users\…`, `~\.claude\skills\`). Forward slashes only inside code that runs in bash/git-bash. +- **Env vars**: `$env:NAME = "value"` for set, `$env:NAME` for read. Not `export`. +- **Common idioms**: `Invoke-WebRequest` (`iwr`), `Test-Path`, `New-Item`, `Get-ChildItem` (`ls`), `Get-Content` (`cat`), `Remove-Item` (`rm`). +- **Install scripts**: in repos with both variants, prefer the `.ps1`. Example: `pwsh scripts/install.ps1`, not `bash scripts/install.sh`. +- **Stop-parsing**: for arguments containing `-`/`@` that PS would mis-parse, use `--%`. + +### Linux / bash + +- **Shell**: bash. POSIX-friendly syntax. +- **Chaining**: `&&`, `||`, `|` work as expected. +- **Paths**: forward slashes (`~/.claude/skills/`, `/var/log/...`). +- **Env vars**: `export NAME=value`. +- **Install scripts**: `bash scripts/install.sh`. +- **Coreutils**: GNU flavor — `sed -i 's/x/y/'`, `readlink -f`, `cp -a`. + +### macOS / zsh + +zsh is the default shell since Catalina. Mostly the same as Linux, with a few divergences worth flagging when relevant: + +- **Package manager**: `brew install …` (Homebrew). +- **BSD coreutils**: `sed -i '' 's/x/y/'` (the empty `''` after `-i` is required), `greadlink` instead of `readlink -f`, no `cp -a`. +- **Paths**: `~/Library/...` rather than XDG-style. + +## Cross-platform docs (READMEs in repos that target multiple OSes) + +When writing user-facing docs in a repo that is *explicitly* cross-platform — like this `claude-skills` repo — show both PowerShell and bash variants. List the active platform's variant first, the other second. Tag each fenced block clearly: + +````markdown +**Windows (PowerShell):** +```powershell +pwsh scripts/install.ps1 +``` + +**Linux / macOS (bash):** +```bash +bash scripts/install.sh +``` +```` + +This is a docs-level decision, independent of the active platform — both blocks ship together. + +## Per-question overrides (don't change the session) + +If the user asks about a *specific other machine* in a single question — e.g. "how would I run this on the prod box, which is Ubuntu", "что это будет на маке" — answer that one in the named platform's shell, but do **not** flip the session-wide active platform. The trigger phrases above are deliberately phrased as "we're on …" / "мы на …" because they imply *the workstation we're now using together*, not "tell me what this looks like elsewhere". + +## Ambiguity policy + +- No signal in the conversation → use the default (Windows). +- Conflicting signals (e.g., user said "we're on Linux" earlier, but now asks an OS-specific question that contradicts) → trust the most recent explicit trigger; if still unclear, ask one short question. +- Unknown platform names ("BSD?", "WSL?") → treat WSL as Linux; for anything genuinely unfamiliar, ask. diff --git a/skills/caveman/SKILL.md b/skills/caveman/SKILL.md new file mode 100644 index 0000000..2ab498b --- /dev/null +++ b/skills/caveman/SKILL.md @@ -0,0 +1,67 @@ +--- +name: caveman +description: > + Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman + while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, + wenyan-lite, wenyan-full, wenyan-ultra. + Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens", + "be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested. +--- + +Respond terse like smart caveman. All technical substance stay. Only fluff die. + +## Persistence + +ACTIVE EVERY RESPONSE. No revert after many turns. No filler drift. Still active if unsure. Off only: "stop caveman" / "normal mode". + +Default: **full**. Switch: `/caveman lite|full|ultra`. + +## Rules + +Drop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not "implement a solution for"). Technical terms exact. Code blocks unchanged. Errors quoted exact. + +Pattern: `[thing] [action] [reason]. [next step].` + +Not: "Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by..." +Yes: "Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:" + +## Intensity + +| Level | What change | +|-------|------------| +| **lite** | No filler/hedging. Keep articles + full sentences. Professional but tight | +| **full** | Drop articles, fragments OK, short synonyms. Classic caveman | +| **ultra** | Abbreviate (DB/auth/config/req/res/fn/impl), strip conjunctions, arrows for causality (X → Y), one word when one word enough | +| **wenyan-lite** | Semi-classical. Drop filler/hedging but keep grammar structure, classical register | +| **wenyan-full** | Maximum classical terseness. Fully 文言文. 80-90% character reduction. Classical sentence patterns, verbs precede objects, subjects often omitted, classical particles (之/乃/為/其) | +| **wenyan-ultra** | Extreme abbreviation while keeping classical Chinese feel. Maximum compression, ultra terse | + +Example — "Why React component re-render?" +- lite: "Your component re-renders because you create a new object reference each render. Wrap it in `useMemo`." +- full: "New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`." +- ultra: "Inline obj prop → new ref → re-render. `useMemo`." +- wenyan-lite: "組件頻重繪,以每繪新生對象參照故。以 useMemo 包之。" +- wenyan-full: "物出新參照,致重繪。useMemo .Wrap之。" +- wenyan-ultra: "新參照→重繪。useMemo Wrap。" + +Example — "Explain database connection pooling." +- lite: "Connection pooling reuses open connections instead of creating new ones per request. Avoids repeated handshake overhead." +- full: "Pool reuse open DB connections. No new connection per request. Skip handshake overhead." +- ultra: "Pool = reuse DB conn. Skip handshake → fast under load." +- wenyan-full: "池reuse open connection。不每req新開。skip handshake overhead。" +- wenyan-ultra: "池reuse conn。skip handshake → fast。" + +## Auto-Clarity + +Drop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question. Resume caveman after clear part done. + +Example — destructive op: +> **Warning:** This will permanently delete all rows in the `users` table and cannot be undone. +> ```sql +> DROP TABLE users; +> ``` +> Caveman resume. Verify backup exist first. + +## Boundaries + +Code/commits/PRs: write normal. "stop caveman" or "normal mode": revert. Level persist until changed or session end. \ No newline at end of file diff --git a/skills/project-discipline/README.md b/skills/project-discipline/README.md new file mode 100644 index 0000000..6a5ee0d --- /dev/null +++ b/skills/project-discipline/README.md @@ -0,0 +1,29 @@ +# project-discipline + +Policy skill that codifies four cross-project discipline rules so the same +guarantees that hold in a tightly-maintained repo apply everywhere. + +## When it triggers + +- **Session start** — when `CLAUDE.md` contains the line `follow project discipline` (added by `project-bootstrap` v1.5.0+). +- **In-chat** — when the user says "use project discipline", "соблюди дисциплину", "проектные правила", or close variants. + +## The four rules + +1. **Project conventions over skill defaults.** `CLAUDE.md` / `.wiki/CLAUDE.md` / `.tasks/` override any other skill's defaults. Specs go to `.wiki/concepts/`, not `docs/superpowers/specs/`. Tasks to `.tasks/`, not `docs/superpowers/plans/`. +2. **Master-only.** All work on `master` (or `main`). No feature branches without explicit user approval. +3. **Semver discipline.** Bump `version:` in `SKILL.md` / `package.json` / `pyproject.toml` on every edit per MAJOR / MINOR / PATCH; record in commit message; rebuild `dist/` artifacts after. +4. **Commit yes, push no.** Every session starts asking before push. User can grant auto-push within session ("разреши автопуш"); session end resets to ask-mode. Force / delete / non-ff push always asks. + +## Prerequisites + +None. The skill is a textual policy document; it takes no actions and has no +external dependencies. Activate it by adding `follow project discipline` to +`CLAUDE.md` (or use `project-bootstrap` v1.5.0+ which adds it automatically). + +## Related + +- `project-bootstrap` (v1.5.0+) — adds the trigger line to new and existing projects' `CLAUDE.md`. +- `pulling-before-work` — companion skill activated by the canonical template; pulls origin once at session start (`git pull --ff-only`). +- `using-tasks` / `using-wiki` — the format conventions Rule 1 routes work into. +- `.wiki/concepts/project-discipline-design.md` (in `claude-skills`) — full design rationale. diff --git a/skills/project-discipline/SKILL.md b/skills/project-discipline/SKILL.md new file mode 100644 index 0000000..4c787ac --- /dev/null +++ b/skills/project-discipline/SKILL.md @@ -0,0 +1,139 @@ +--- +name: project-discipline +version: 0.1.1 +description: > + Codifies five cross-project discipline rules: (1) project CLAUDE.md / + .wiki/CLAUDE.md / .tasks/ override defaults from any other skill (specs + go to .wiki/concepts/, not docs/superpowers/specs/; tasks to .tasks/, + not docs/superpowers/plans/); (2) all work on master/main, no feature + branches without explicit user approval; (3) bump semver on every edit + of versioned artifacts (SKILL.md frontmatter, package.json, + pyproject.toml) per MAJOR/MINOR/PATCH rules, recorded in commit message; + (4) commit freely, never push without explicit per-session user approval + — grant via "разреши автопуш" / "allow auto-push", revoke via "отзови" + / "revoke", session end resets to ask-mode; force/delete/non-ff push + always asks; (5) transit-zone / brainstorm workspaces — artifacts + go to .brainstorm/ or global wiki only via explicit user direction, + never auto-promote by analogy. Activated by "follow project discipline" + trigger in CLAUDE.md (added by project-bootstrap v1.5.0+). +--- + +# project-discipline + +> Four cross-project rules. Read at session start. Apply before any other skill's defaults touch paths, branches, versions, or remote pushes. + +## When this runs + +**At session start** — when `CLAUDE.md` contains the line `follow project discipline`. The skill is a policy document; the agent reads it and applies the four rules to all subsequent work in the session. + +**On explicit reference** — when the user says "use project discipline", "соблюди дисциплину", "проектные правила", "что у меня по правилам?", or close variants asking about/applying the rules. + +The skill itself takes no actions and has no external side-effects. It instructs the agent how to behave. + +## Rule 1 — Project conventions override skill defaults + +Before applying defaults from any other skill (superpowers, frontend-design, mcp-builder, etc.), read in this order: + +1. `CLAUDE.md` in the project root. +2. `.wiki/CLAUDE.md` (if it exists). +3. `.tasks/STATUS.md` (if it exists). + +Any path, format, or workflow explicitly stated in those files **overrides the skill default**. + +Concrete consequences: + +- **Specs / design documents** go to `.wiki/concepts/-design.md`, **not** `docs/superpowers/specs/`. +- **Task tracking / implementation plans** go to `.tasks/.md` plus a board entry in `.tasks/STATUS.md` (the `using-tasks` format), **not** `docs/superpowers/plans/` or any inline-in-chat plan format. +- **Frontmatter, naming conventions, log format** — as described in the project's `.wiki/CLAUDE.md`. + +If no convention is stated explicitly — fall back to the skill default. + +## Rule 2 — Master-only + +All work happens on the repo's main integration branch — usually `master`, but if a project uses `main`, treat `main` as equivalent. + +- No `git checkout -b feature/foo` for solo work. +- Sync with remote: `git pull --ff-only` or `git pull --rebase`. **No merge commits** for solo work. +- If a task genuinely requires isolation (large experiment, risky refactor with rollback potential, multi-day work with intermediate WIP commits) — **ask** the user: "this needs its own branch, ok?" — and wait for explicit approval. Without approval, work continues on master. + +If the agent finds itself on a non-main branch (after a manual `git checkout`) or in detached HEAD — report it and ask whether to return to master before working. + +## Rule 3 — Versioning discipline + +When editing any artifact with a semver field, **bump the version before committing** per: + +- **MAJOR** (`X+1.0.0`) — breaks the contract. Renames, removed triggers, layout changes, removed public functions, breaking API change. +- **MINOR** (`X.Y+1.0`) — adds capability without breaking. New trigger, new optional step, new public function. +- **PATCH** (`X.Y.Z+1`) — wording / clarity / typo fixes with no behavior change. + +The bump is recorded in the commit message: `feat(): … [vX.Y.Z]` or whatever convention the project uses (see Rule 1). + +**Applies to:** `skills//SKILL.md` (`version:` in frontmatter), `package.json` (`"version":`), `pyproject.toml` (`version =`), `Cargo.toml` (`version =`), and any other semver field in any other manifest. + +**If the artifact is packaged** as `dist/.skill`, `dist/*.tgz`, etc. — **rebuild** the package in the same or the next commit. Forgotten dist artifacts are a common cause of deploying stale binaries. + +**First edit of an unversioned artifact** that COULD have a semver field (a new skill without `version:`, a new `package.json` without `"version":`) — **add** `version: 0.1.0` (or its equivalent) before committing; do not bump anything. + +**Does not apply to:** artifacts with no semver field and no potential for one (wiki concept pages, README.md, shell scripts without a public interface). + +## Rule 4 — Commit yes, push no (session-scoped) + +**Every session starts in ask-before-push mode.** On every `git push`, ask: + +> Готов push'нуть в `/` (N коммитов: ). Ок? + +(or its English equivalent if the user is communicating in English) and wait for explicit `yes` / `да` / `push` / equivalent. Without confirmation — do not push. + +**Granting auto-push within a session.** When the user says: + +- "разреши автопуш" / "allow auto-push" / "автопуш ок" / equivalent + +— push without further confirmation until the end of the session or until revoked. + +**Revoking auto-push within a session.** When the user says: + +- "отзови автопуш" / "revoke auto-push" / "снова спрашивай" / equivalent + +— return to ask-before-push mode. + +**Session end resets to ask-mode.** The next session starts asking again, regardless of what was granted in the previous one. This is intentional: a grant is given for the current context (user nearby, consciously decided pushes are safe), and should not survive a context switch. + +**Always ask, even with active grant:** + +- `git push --force` / `--force-with-lease` (history rewrite); +- `git push origin --delete ` (branch deletion); +- push to a remote/branch other than the current tracked upstream (`git push other-remote ...`, `git push origin other-branch`); +- push to the main branch that would require non-fast-forward (i.e. would need force). + +A grant covers ordinary fast-forward push to the configured upstream. Anything else is a separate class of operation and needs its own decision. + +**What counts as "push":** only `git push` family commands. Local commits, `git stash push`, etc. are not push; the grant does not apply. + +## Rule 5 — Transit-zone / brainstorm workspaces + +Some workspaces are **transit zones** — discussion areas with no `.tasks/`, where brainstorm artifacts are explicitly NOT auto-promoted to project wikis. + +**Default destination for brainstorm artifacts:** +- **In-progress brainstorm outputs** → `.brainstorm/.md` (or whatever the workspace's README/CLAUDE.md declares) +- **Mature, cross-cutting outputs** → `~/projects/.wiki/concepts/-design.md` via `mcp__projects-meta__knowledge_ingest` — **only** when user explicitly directs this + +**Agent must NOT auto-promote** brainstorm artifacts to global wikis by analogy with Rule 1. Convergence-moment (move from workspace to permanent wiki) is a user decision, not an automatic action. + +**Example:** `~/projects/.meeting-room/` is a transit zone. Its CLAUDE.md explicitly states "no `.tasks/`, transit zone, artifacts go to `.brainstorm/` or global wiki via user command." Rule 1's "project conventions override" applies, but the override is explicit in the workspace contract — auto-promotion by analogy would violate that contract. + +**When in doubt:** ask the user "this goes to `.brainstorm/`, or should I promote to shared wiki?" rather than assuming. + +## Out of scope + +The skill **does not**: + +- modify `CLAUDE.md` (that's `project-bootstrap`'s job); +- enforce rules via git hooks / pre-commit / CI (this is agent discipline, not tooling); +- manage `settings.json` permissions (that's `update-config`); +- check the existence of `.wiki/` / `.tasks/` (that's `setup-wiki` / `setup-tasks` / `project-bootstrap`); if a project doesn't have them, Rule 1 simply finds no overrides and falls back to skill defaults. + +## Why this exists + +In a tightly-disciplined repo (`claude-skills`) the four rules already hold by accident — the agent reads `.wiki/CLAUDE.md`, knows specs go to `.wiki/concepts/`, knows to bump `version:`, knows not to push without confirmation. In **other** projects of the same user, that discipline does not transfer: the agent uses `superpowers`' default `docs/superpowers/specs/`, branches on a whim, forgets `version:` bumps, and pushes without asking. This skill makes the discipline explicit and portable. + +Full design rationale (why one skill instead of four, why a skill instead of inline `CLAUDE.md` lines, scope of each rule, push-permission mechanism choice) lives in `.wiki/concepts/project-discipline-design.md` (in this repo; in other projects bootstrapped from this repo, the design lives in `claude-skills`). diff --git a/skills/pulling-before-work/README.md b/skills/pulling-before-work/README.md new file mode 100644 index 0000000..3ff8bc9 --- /dev/null +++ b/skills/pulling-before-work/README.md @@ -0,0 +1,29 @@ +# pulling-before-work + +Policy skill that pulls the current branch from `origin` once at session start +and on explicit re-sync requests. Designed to remove the "edited on stale base" +footgun without trampling dirty work-trees or auto-merging. + +## When it triggers + +- **Session start** — when `CLAUDE.md` contains the line `pull remote before work` (added by `project-bootstrap` v1.4.0+). +- **In-chat** — when the user says `sync`, `resync`, `pull`, `обнови репо`, `git pull please`, or close variants. + +Stays silent in non-git folders. Prints one informational line and exits in: +no `origin` remote, no upstream tracking, dirty work-tree, detached HEAD. + +## What it does + +`git pull --ff-only` against the configured upstream — never auto-merges, never +auto-rebases, never stashes, never commits, never pushes. On divergence it prints +a warning with manual-resolution hints and exits. + +## Prerequisites + +None. The skill is a no-op outside git repos and folders without an `origin` +remote, so it's safe to leave activated everywhere. + +## Related + +- `project-bootstrap` (v1.4.0+) — adds the trigger line to new and existing projects' `CLAUDE.md`. +- `.wiki/concepts/pulling-before-work-design.md` (in projects bootstrapped from this repo: this design lives in `claude-skills`) — full design rationale. diff --git a/skills/pulling-before-work/SKILL.md b/skills/pulling-before-work/SKILL.md new file mode 100644 index 0000000..25c2646 --- /dev/null +++ b/skills/pulling-before-work/SKILL.md @@ -0,0 +1,153 @@ +--- +name: pulling-before-work +version: 1.0.0 +description: > + Pulls the current branch from origin once at session start and on explicit + re-sync requests. Use when CLAUDE.md contains the trigger line "pull remote + before work", or when the user says "sync", "resync", "pull", "обнови репо", + "git pull please", or close variants asking to refresh from the remote. + Runs `git pull --ff-only` — never auto-merges or rebases. Stays silent in + non-git folders. Prints one informational line and exits when there is no + origin remote, no upstream tracking, the working tree is dirty, or HEAD is + detached. Does not stash, commit, or push. Activated by `project-bootstrap` + v1.4.0+ via the canonical CLAUDE.md template. +--- + +# pulling-before-work + +> Pull from `origin` once when work starts. Don't auto-merge. Don't trample dirty work-trees. Don't ask twice in the same session unless asked. + +## When this runs + +**At session start** — once, when the skill is activated by the `pull remote before work` line in `CLAUDE.md`. The cycle below runs immediately. + +**On explicit re-sync** — when the user says any of: `sync`, `resync`, `pull`, `обнови репо`, `pull please`, `git pull`, `подтяни`, `pull from origin`. Re-runs the full cycle. There is no per-session counter; the user is always allowed to ask. + +**Never** before each commit, before each tool call, on every message, or in any other implicit cadence. Mode-3 ("start + on-demand") was the explicit design choice — see `.wiki/concepts/pulling-before-work-design.md`. + +## The pull cycle + +Run these checks in order. Print at most one line of chat output per run. + +### 1. Inside a git work-tree? + +```bash +git rev-parse --is-inside-work-tree 2>/dev/null +``` + +If the command fails or prints anything other than `true` → **exit silently, no chat output.** This is the not-a-git-repo case; the skill must not be noisy in random folders. + +### 2. Has an `origin` remote? + +```bash +git remote get-url origin 2>/dev/null +``` + +If the command fails (no such remote) → print one line and exit: + +``` +no origin remote — skip pull +``` + +### 3. Is the working tree clean? + +```bash +git status --porcelain +``` + +If the output is non-empty → print one line and exit: + +``` +working tree dirty — skipping pull. commit/stash, потом скажи "sync" +``` + +Never stash automatically. Stash-pop conflicts are exactly the friction this skill exists to remove. + +### 4. Is HEAD attached? + +```bash +git symbolic-ref -q HEAD +``` + +If the command fails (empty output, exit 1) → detached HEAD. Print: + +``` +detached HEAD — skip pull +``` + +### 5. Does the current branch have an upstream? + +```bash +git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null +``` + +Capture the upstream name (e.g. `origin/master`). If the command fails → no upstream tracking. Print: + +``` +no upstream tracking for — skip pull +``` + +(Where `` is `git rev-parse --abbrev-ref HEAD`.) + +### 6. Pull, fast-forward only + +```bash +git pull --ff-only +``` + +(No args — uses the configured upstream captured above.) + +Classify by exit code and stdout: + +| Result | Print | +|---|---| +| Already up to date | `✅ already up to date with ` | +| Fast-forward, N commits | `✅ pulled N commits from ` | +| Non-fast-forward / diverged (exit non-zero with "diverged" or "non-fast-forward" in output) | `⚠️ diverged from — resolve manually (git pull --rebase or merge); skill never auto-merges/rebases` | + +### Out of scope + +The skill never: + +- commits, stashes, or pushes +- recurses into submodules +- pulls from non-`origin` remotes +- pulls on detached HEAD +- runs auto-merge or auto-rebase +- runs more than once per session unless the user asks + +## Recovery hints + +If the skill skipped because of a dirty tree: + +```powershell +# Windows / PowerShell +git status # see what's dirty +git add . ; git commit -m "wip" +# then ask the agent: "sync" +``` + +```bash +# Linux / macOS +git status +git add . && git commit -m "wip" +# then say "sync" +``` + +If the skill reported `diverged`: + +```bash +# Option A: rebase your local commits on top of origin +git pull --rebase + +# Option B: explicit merge (creates a merge commit) +git pull --no-ff +``` + +The skill stays out of these decisions on purpose — both options have valid use cases and the user owns the choice. + +## Why this exists + +Stale local branches are a silent footgun: edits land on top of yesterday's `origin`, the divergence shows up at push time, and by then there's a chunk of work to rebase or merge on the wrong base. One pull at start covers the common case; an explicit re-sync trigger handles long sessions where someone pushed mid-flight. + +Full design rationale (mode choice, dirty-tree skip vs stash, `--ff-only` vs auto-merge, the upstream-check) lives in `.wiki/concepts/pulling-before-work-design.md`. diff --git a/skills/setup-tasks/README.md b/skills/setup-tasks/README.md new file mode 100644 index 0000000..ff7bdae --- /dev/null +++ b/skills/setup-tasks/README.md @@ -0,0 +1,108 @@ +# setup-tasks + +One-time skill that creates or migrates a project's `.tasks/` board to the +canonical layout — `STATUS.md` (the board, with emoji status legend) plus +per-task `.md` files for each active or paused task. The runtime +policy for working *with* the board lives in +[`using-tasks`](../using-tasks/) — `setup-tasks` is the only place that +creates the structure. + +## When it triggers + +- User says: "set up tasks", "init tasks", "create task tracking", + "migrate tasks to canon", "tasks broken", or the Russian equivalents + ("настрой таски", "инициализируй таски"). +- [`using-tasks`](../using-tasks/) detects a missing or non-canonical + `.tasks/` and delegates here via its Prerequisites section. +- [`project-bootstrap`](../project-bootstrap/) Step 4 delegates here when + initializing a new project. + +## Modes + +`setup-tasks` picks one of three modes after a discovery scan: + +| Mode | Trigger | Action | +|---|---|---| +| **greenfield** | No `.tasks/` exists | Write `.tasks/STATUS.md` from the canonical template. No per-task files yet — they're created on demand. | +| **noop** | `.tasks/STATUS.md` already canon (emoji status legend + at least one per-task file) | Report and exit. | +| **migrate** | `.tasks/STATUS.md` is flat (plain `## Done` / `## In Progress` / `## Backlog`, no emoji legend, no per-task files) | Back up, then drive an interactive migration — one task at a time, asking the user for the canonical fields. | + +A "placeholder" STATUS.md (just the bootstrap default with no real tasks) is +treated as `greenfield` — no migration needed. + +## What canon means + +``` +.tasks/ +├── STATUS.md ← board, with emoji status legend + one block per task +└── .md ← per-task deep context (one file per active/paused task) +``` + +Status legend: 🔴 active / 🟡 paused / ⚪ ready / 🟢 done / 🔵 blocked. + +`STATUS.md` block format (one per task): + +``` +## 🔴 [task-slug] — short description +**Status:** active +**Where I stopped:** one sentence — the exact thought or action interrupted +**Next action:** one concrete step to resume immediately +**Blocker:** (only if blocked) what is preventing progress +**Branch:** git branch name +``` + +Per-task file sections: Goal, Key files, Decisions log, Open questions, +Completed steps, Notes. + +## Hard rules + +- **Never auto-mutate.** Phase 1 (discovery) and Phase 2 (plan) always pause + for explicit confirmation. A trigger phrase grants permission to inspect, + not to write. +- **Never auto-parse a flat STATUS.md.** Old layouts vary; agent heuristics + mangle real work. Migration is interactive — the agent asks the user for + each task's canonical fields. +- **Never invent task slugs / branches / "where you stopped" values.** The + whole point is *real* preserved context, not hallucinated context. +- **No empty per-task files at greenfield.** Wait until the user adds a + real task. +- **Never edit the `.bak` file.** It's the rollback artifact. + +## Procedure (high-level) + +1. **Phase 0** — environment sanity (project root). +2. **Phase 1** — discovery (greenfield / noop / migrate). +3. **Phase 2** — plan + confirm. Wait for explicit "ok"/"go"/"поехали". +4. **Phase 3** — backup (migrate only) → `STATUS.md.bak-YYYYMMDD-HHMMSS`. +5. **Phase 4a/4b** — greenfield create or interactive migrate. +6. **Phase 5** — verify (canon `STATUS.md`, per-task files for active/paused + only, no required content lost). +7. **Phase 6** — final report; if invoked from `project-bootstrap`, return + silently. + +Full procedure with templates and the migration script lives in +[`SKILL.md`](SKILL.md). + +## Rollback + +- Greenfield: `rm -rf .tasks/`. +- Migrate: `mv .tasks/STATUS.md.bak- .tasks/STATUS.md` plus `rm` for any + newly created per-task files; `git reset HEAD .tasks/`. + +## Install + +From the repo root: + +```bash +bash scripts/install.sh setup-tasks +``` + +Works on Windows under git-bash, Linux, macOS. + +## See also + +- [`using-tasks`](../using-tasks/) — runtime policy for working with `.tasks/`. +- [`project-bootstrap`](../project-bootstrap/) — orchestrator that delegates + here for new projects. +- Source pattern: `.wiki/raw/setup-task-status-wiki.md` in this repo — + extended documentation, decisions log format, agent operations. diff --git a/skills/setup-tasks/SKILL.md b/skills/setup-tasks/SKILL.md new file mode 100644 index 0000000..fd8275c --- /dev/null +++ b/skills/setup-tasks/SKILL.md @@ -0,0 +1,202 @@ +--- +name: setup-tasks +version: 1.0.0 +description: Creates or migrates a project's `.tasks/` board to the canonical layout — `STATUS.md` (the board, with emoji status legend) plus per-task `.md` files for each active or paused task. Use when the user says "set up tasks", "init tasks", "настрой таски", "инициализируй таски", "create task tracking", "migrate tasks to canon", "tasks broken", or whenever `using-tasks` detects a missing or non-canonical `.tasks/`. Two modes — greenfield (no `.tasks/`) and migrate (existing flat STATUS.md without per-task files). Confirmation gate before writing. Cross-platform. +--- + +# setup-tasks + +> Creates or migrates a `.tasks/` board to canon. The canonical layout is enforced by `using-tasks` and described in `.wiki/raw/setup-task-status-wiki.md` (the original idea file from which this skill is derived). This skill is the *only* place that creates the board structure. + +## When to use + +- User explicitly asks: set up / init / migrate / create tasks. +- `using-tasks` runs and detects a missing or non-canonical `.tasks/` — its Prerequisites delegate here. +- `project-bootstrap` Step 4 delegates here when initializing a new project. + +## Out of scope + +- Editing existing task content during normal work (that's `using-tasks`). +- Anything outside `.tasks/`. + +## Hard rule: don't auto-mutate + +The procedure mutates `.tasks/`. **Pause for explicit confirmation between Phase 1 (discovery) and Phase 2 (plan).** A trigger phrase is permission to inspect, not to write. + +## Procedure + +### Phase 0 — Environment sanity + +- Confirm current working directory is a project root (preferably with `.git/`; otherwise it's still OK to bootstrap, just note it). +- Tasks paths are POSIX-style (`.tasks/...`) on every OS. + +### Phase 1 — Discovery + +Inspect `.tasks/`: + +- **No `.tasks/`** → mode = `greenfield`. +- **`.tasks/STATUS.md` exists with canonical signals** — has emoji status (🔴 / 🟡 / ⚪ / 🟢 / 🔵) AND at least one per-task `.tasks/.md` exists for any active/paused entry → mode = `noop`. +- **`.tasks/STATUS.md` exists but flat** — no emoji legend, no per-task files, just plain `## Done` / `## In Progress` / `## Backlog` sections (or similar) → mode = `migrate`. + +Report findings: + +``` +Mode: greenfield | noop | migrate +STATUS.md: exists | missing +Per-task files: +Format: canon | flat | mixed +``` + +### Phase 2 — Plan + confirm + +Show the plan in one block. + +**Greenfield:** +``` +Will create .tasks/STATUS.md with the canonical board template. +Per-task files will be created on demand by using-tasks when actual tasks are added. +``` + +**Migrate:** +``` +Will: + • back up existing STATUS.md → STATUS.md.bak- + • for each task entry I can identify in the old STATUS.md, ask you for: + - task-slug (kebab-case, latin) + - current status (active / paused / ready / done / blocked) + - branch + - where you stopped (one sentence) + - next action (one sentence) + then write `.tasks/.md` and a canonical STATUS.md block. + • leave the .bak file as a fallback reference. +``` + +If existing `STATUS.md` is purely a placeholder (just the bootstrap-default comment block, no real tasks), treat as `greenfield` — no migration needed, just overwrite with the template. + +Wait for explicit confirmation ("ok", "go", "поехали"). Anything else → stop. + +### Phase 3 — Backup (migrate only) + +```bash +TS=$(date +%Y%m%d-%H%M%S) +cp .tasks/STATUS.md ".tasks/STATUS.md.bak-$TS" +``` + +### Phase 4a — Greenfield create + +Write `.tasks/STATUS.md`: + +```markdown +# Task Board +_Updated: _ + + +``` + +No per-task files at greenfield — they're created when actual tasks are added. + +### Phase 4b — Migrate + +In migrate mode, do *not* try to auto-parse the old flat STATUS.md. The old layout is too varied — agent-driven heuristics will mangle real work. Instead, drive the migration interactively: + +1. Show the user the old STATUS.md content (or a summary). +2. Ask: "Which of these are real, in-flight tasks you want to keep?" Get a list. +3. For each task, ask the four canonical fields (slug, status, branch, where-stopped, next-action). The skill never invents these. +4. Build a fresh canonical `.tasks/STATUS.md` from those answers. +5. Create `.tasks/.md` for each active or paused task using the per-task template (Goal, Key files, Decisions log, Open questions, Completed steps, Notes). +6. Leave the `.bak-` file in place — historical record. + +Per-task template: + +```markdown +# + +## Goal +One paragraph. What this achieves and why it matters. + +## Key files +- `path/to/file.ts` — role in this task + +## Decisions log +- : migrated from flat STATUS.md via setup-tasks@ + +## Open questions +- [ ] (fill in) + +## Completed steps +- [x] (fill in) + +## Notes +``` + +### Phase 5 — Verify + +After writes: + +- `.tasks/STATUS.md` exists and has the emoji status legend (or template comment block in greenfield). +- For migrate: each task referenced in STATUS.md has its `.md` file (active and paused only). +- No required content was lost (the `.bak` file is the safety net). + +If verification fails → restore from `.bak-` and report. + +### Phase 6 — Report + +Print final state: + +``` +✅ Tasks board ready at .tasks/. + Mode: greenfield | migrate + STATUS.md: > + Per-task files: + +Next steps for the user: + • Add or edit task entries in .tasks/STATUS.md + • Read using-tasks SKILL.md if unfamiliar with the workflow +``` + +If invoked from `project-bootstrap`, return control silently. + +## Rollback + +1. `rm -rf .tasks/` (greenfield rollback) + or + `mv .tasks/STATUS.md.bak- .tasks/STATUS.md` (migrate rollback) and `rm .tasks/.md` for any newly created per-task files. +2. `git reset HEAD .tasks/` if a git repo. +3. Tell user what failed. + +## Common mistakes + +- **Auto-parsing existing flat STATUS.md.** Don't. The format varies, real work is at stake — drive migration through the user, one task at a time. +- **Inventing task slugs / branches / "where you stopped" values.** Never. Ask the user. The whole point of `.tasks/` is *real* preserved context, not hallucinated context. +- **Skipping confirmation on greenfield.** Yes, even greenfield needs the gate — the user might be running this in the wrong directory. +- **Creating per-task files at bootstrap.** Don't pre-generate empty `.md` files in greenfield mode — wait until the user adds actual tasks. +- **Editing the `.bak` file.** It's the rollback artifact; leave it alone. + +## Cross-platform notes + +The procedure is platform-agnostic. Wiki-style paths (`.tasks/...`) work the same on Windows / Linux / macOS. The only platform-conditional command is the timestamp generator (`date +%Y%m%d-%H%M%S` in bash; equivalent in PowerShell), and our scripts use bash via git-bash on Windows. + +## Source + +The canonical pattern (extended documentation, decisions log format, agent operations) lives in this repo at `.wiki/raw/setup-task-status-wiki.md`. Refer to it when designing project-specific extensions. diff --git a/skills/setup-wiki/README.md b/skills/setup-wiki/README.md new file mode 100644 index 0000000..5ba64d8 --- /dev/null +++ b/skills/setup-wiki/README.md @@ -0,0 +1,103 @@ +# setup-wiki + +One-time skill that creates or migrates a project's `.wiki/` to the +canonical Karpathy LLM Wiki layout. The runtime policy for working *inside* +that wiki lives in [`using-wiki`](../using-wiki/) — `setup-wiki` is the only +place that creates or rearranges the file structure. + +Canonical layout reference: + + +## When it triggers + +- User says: "set up wiki", "init wiki", "create wiki", "migrate wiki to canon", + "wiki layout broken", or the Russian equivalents ("настрой вики", + "инициализируй вики", "wiki сломана"). +- [`using-wiki`](../using-wiki/) detects a missing or non-canonical `.wiki/` + and delegates here via its Prerequisites section. +- [`project-bootstrap`](../project-bootstrap/) Step 3 delegates here when + initializing a new project. + +## Modes + +`setup-wiki` chooses one of three modes after a discovery scan: + +| Mode | Trigger | Action | +|---|---|---| +| **greenfield** | No `.wiki/` exists | Create the canonical layout from scratch. | +| **noop** | `.wiki/` already canon (all five canon files + six content dirs) | Report and exit — no writes. | +| **migrate** | `.wiki/` exists with non-canon files (`SUMMARY.md`, `WORKFLOW.md`, `source/`) or missing canon files | Move legacy files (e.g. `source/*.md` → `concepts/*.md` via `git mv`), create missing canon files, drop a timestamped `.backup-*/` next to it. | + +Migration **does not auto-rewrite** existing concept content — it only moves +files and prepends minimal frontmatter when missing. Real edits stay your +job. + +## What canon means + +``` +.wiki/ +├── CLAUDE.md ← schema: project-specific wiki conventions +├── index.md ← catalog of pages by type +├── log.md ← append-only op log +├── overview.md ← single project overview +├── raw/ +│ └── README.md ← raw/ is immutable; this file documents that +├── entities/ ← entity pages (people, services, modules) +├── concepts/ ← design decisions, recurring ideas +├── packages/ ← code packages +├── sources/ ← one summary per ingested source +├── contradictions/ ← surfaced tensions worth tracking long-term +└── open-questions/ ← unresolved questions raised during ingest/query +``` + +The six content directories each get a `.gitkeep` so git tracks them. + +## Hard rules + +- **Never auto-mutate.** Phase 1 (discovery) and Phase 2 (plan) always pause + for explicit confirmation. A trigger phrase grants permission to inspect, + not to write. +- **Never touch `raw/` content during migration.** `raw/` is immutable; only + the `.gitkeep` placeholder may be removed when `raw/README.md` replaces it. +- **No re-runs that overwrite a canon wiki.** Phase 1 detection guards + this — `noop` mode bails out cleanly. +- **No invented domain conventions.** The schema's "Domain conventions" + section stays a stub for the user to fill in. + +## Procedure (high-level) + +1. **Phase 0** — environment sanity (project root, platform check). +2. **Phase 1** — discovery (greenfield / noop / migrate). +3. **Phase 2** — plan + confirm. Wait for explicit "ok"/"go"/"поехали". +4. **Phase 3** — backup (migrate only) → `.wiki/.backup-YYYYMMDD-HHMMSS/`. +5. **Phase 4a/4b** — greenfield create or migrate. +6. **Phase 5** — verify (canon files present, dirs exist, no leftover + non-canon, frontmatter on migrated pages). +7. **Phase 6** — final report; if invoked from `project-bootstrap`, return + silently. + +Full procedure with templates and the migration shell snippet lives in +[`SKILL.md`](SKILL.md). + +## Rollback + +- Greenfield: `rm -rf .wiki/`. +- Migrate: `cp -r .wiki/.backup-/* .wiki/` and `git reset HEAD .wiki/`. + +## Install + +From the repo root: + +```bash +bash scripts/install.sh setup-wiki +``` + +Works on Windows under git-bash, Linux, macOS. + +## See also + +- [`using-wiki`](../using-wiki/) — runtime policy for working with `.wiki/`. +- [`project-bootstrap`](../project-bootstrap/) — orchestrator that delegates + here for new projects. +- Karpathy's LLM Wiki gist: + diff --git a/skills/setup-wiki/SKILL.md b/skills/setup-wiki/SKILL.md new file mode 100644 index 0000000..f93f77c --- /dev/null +++ b/skills/setup-wiki/SKILL.md @@ -0,0 +1,294 @@ +--- +name: setup-wiki +version: 1.1.0 +description: Creates or migrates a project's `.wiki/` to the canonical Karpathy LLM Wiki layout — `CLAUDE.md` schema, `index.md`, `log.md`, `overview.md`, `raw/README.md`, plus empty `entities/`, `concepts/`, `packages/`, `sources/`, `contradictions/`, `open-questions/`. Use when the user says "set up wiki", "init wiki", "настрой вики", "инициализируй вики", "create wiki", "migrate wiki to canon", "wiki сломана", "wiki layout broken", or whenever `using-wiki` detects a missing or non-canonical `.wiki/`. Two modes — greenfield (no wiki) and migrate (existing non-canonical layout). Confirmation gate before writing. Cross-platform. +--- + +# setup-wiki + +> Creates or migrates a `.wiki/` to canon. The canonical layout is documented at https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f and enforced by `using-wiki`. This skill is the *only* place that creates or rearranges those files. + +## When to use + +- User explicitly asks: set up / init / migrate / create wiki. +- `using-wiki` runs and detects a missing or non-canonical `.wiki/` — its Prerequisites delegate here. +- `project-bootstrap` Step 3 delegates here when initializing a new project. + +## Out of scope + +- Editing existing wiki *content* (that's `using-wiki`'s job). +- Anything outside `.wiki/`. + +## Hard rule: don't auto-mutate + +The procedure mutates the project's `.wiki/`. **Pause for explicit confirmation between Phase 1 (discovery) and Phase 2 (plan).** A trigger phrase is permission to inspect, not to write. + +## Procedure + +### Phase 0 — Environment sanity + +- Confirm current working directory is a project root (has `.git/` ideally, or at minimum is a place the user wants a wiki). +- Detect platform; pick file paths accordingly. Wiki paths are POSIX-style (`.wiki/...`) on every OS. + +### Phase 1 — Discovery + +Inspect `.wiki/`: + +- **No `.wiki/`** → mode = `greenfield`. +- **`.wiki/` exists AND has all of:** `CLAUDE.md`, `index.md`, `log.md`, `overview.md`, `raw/README.md`, plus directories `entities/`, `concepts/`, `packages/`, `sources/`, `contradictions/`, `open-questions/` → mode = `noop` (already canon; report and exit). +- **`.wiki/` exists but missing some canon files OR has non-canon files** (`SUMMARY.md`, `WORKFLOW.md`, `source/`) → mode = `migrate`. + +Report findings to the user as a short summary: + +``` +Mode: greenfield | noop | migrate +Has: +Missing: +Non-canon: +``` + +### Phase 2 — Plan + confirm + +Show the plan in one block: + +**Greenfield:** +``` +Will create .wiki/ with canonical layout: + CLAUDE.md (schema), index.md, log.md, overview.md + raw/README.md + entities/, concepts/, packages/, sources/, contradictions/, open-questions/ (with .gitkeep) +``` + +**Migrate:** +``` +Will rename: + source/*.md → concepts/*.md (via git mv when in a git repo, plain mv otherwise) +Will create: + CLAUDE.md, index.md, log.md, overview.md, raw/README.md + entities/, packages/, sources/, contradictions/, open-questions/ (with .gitkeep) +Will delete: + SUMMARY.md, WORKFLOW.md, raw/.gitkeep, source/ (after moves) +Will not touch existing files in raw/ — they're immutable sources. +``` + +Wait for explicit confirmation ("ok", "go", "поехали"). Anything else → stop. + +### Phase 3 — Backup (migrate only) + +In migrate mode only, copy each file we will rename/delete to `.wiki/.backup-YYYYMMDD-HHMMSS/`. (Greenfield has nothing to back up.) + +If git is available, the rename history is also recoverable via `git reflog`, but a filesystem backup is belt-and-suspenders. + +### Phase 4a — Greenfield create + +Create the canonical layout. Each file gets the content shown below; the project name comes from the parent directory's basename. + +**`.wiki/CLAUDE.md`** (schema): + +```markdown +# Wiki Schema — + +Project-specific wiki conventions. Read this before any wiki operation. + +This wiki follows Karpathy's LLM Wiki pattern: +**https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f** + +The `using-wiki` skill enforces the workflow and file formats. This file overrides the skill where they conflict. + +## Page types + +- `entities/` — discrete things this project tracks (people, services, modules). +- `concepts/` — recurring ideas, design decisions, gotchas. +- `packages/` — code packages this project produces or consumes. +- `sources/` — one summary page per ingested external doc; carries `ingested:` and `raw_path:`. +- `contradictions/` — surfaced tensions between sources or pages worth tracking long-term; each page cross-links the affected entities/concepts/sources and carries a status (`open` / `resolved` / `accepted-divergence`). +- `open-questions/` — unresolved questions raised during ingest or query that the wiki cannot answer yet; each page cross-links the pages/sources that touch the question and carries a status (`open` / `answered` / `obsolete`). +- `overview.md` — single project-wide overview. + +## Naming + +- `kebab-case.md`, **Latin only**. Transliterate Cyrillic in filenames; keep the original title in the H1 + frontmatter. + +## Domain conventions + + +``` + +**`.wiki/index.md`** (catalog): + +```markdown +# Wiki Index + +Catalog of all wiki pages. One line per page, organized by type. Updated on every ingest / new page. + +## Overview + +- [overview.md](overview.md) — project overview + +## Entities + + + +## Concepts + + + +## Packages + + + +## Sources + + + +## Contradictions + + + +## Open Questions + + +``` + +**`.wiki/log.md`** (op log; backfill an `init` line dated today): + +```markdown +# Wiki Log + +Append-only operation log. Format: + +\`\`\` +## [YYYY-MM-DD] | +\`\`\` + +Operations: `init`, `ingest`, `query`, `lint`, `refactor`, `decision`. + +Parseable: `grep "^## \[" .wiki/log.md | tail -20`. + +--- + +## [] init | wiki bootstrapped via setup-wiki@ +``` + +**`.wiki/overview.md`**: + +```markdown +--- +title: overview +type: overview +updated: +--- + +# — overview + + +``` + +**`.wiki/raw/README.md`**: + +```markdown +# Raw Sources + +**Immutable.** Read, never edit. The only allowed modification is appending a `> Status:` blockquote when the user explicitly asks for a status audit. + +Place raw inputs here — articles, transcripts, PDFs, screenshots — exactly as they came in. The agent reads from `raw/`, writes summaries into `../sources/`, and never modifies raw files. + +For large or path-sensitive sources outside the repo, register them here: + +\`\`\` +- short-name → /absolute/path/to/source +\`\`\` +``` + +**Empty `.gitkeep`** in each of `entities/`, `concepts/`, `packages/`, `sources/`, `contradictions/`, `open-questions/` so git tracks the dirs. + +### Phase 4b — Migrate + +If migrate mode: combine creation (for missing canon files) with file moves (for non-canon). + +```bash +# 1. Create missing directories +mkdir -p .wiki/concepts .wiki/entities .wiki/packages .wiki/sources .wiki/contradictions .wiki/open-questions + +# 2. Move source/* → concepts/* (use git mv if in a git repo) +if git rev-parse --git-dir >/dev/null 2>&1; then + for f in .wiki/source/*.md; do + [ -e "$f" ] && git mv "$f" ".wiki/concepts/$(basename "$f")" + done + git rm -f .wiki/SUMMARY.md .wiki/WORKFLOW.md .wiki/source/.gitkeep .wiki/raw/.gitkeep 2>/dev/null +else + mv .wiki/source/*.md .wiki/concepts/ 2>/dev/null + rm -f .wiki/SUMMARY.md .wiki/WORKFLOW.md .wiki/source/.gitkeep .wiki/raw/.gitkeep +fi +rmdir .wiki/source 2>/dev/null + +# 3. Create missing canon files (CLAUDE.md, index.md, log.md, overview.md, raw/README.md) +# using the templates from Phase 4a, but skip files that already exist. + +# 4. Add .gitkeep to entities/, packages/, sources/, contradictions/, open-questions/ +touch .wiki/entities/.gitkeep .wiki/packages/.gitkeep .wiki/sources/.gitkeep .wiki/contradictions/.gitkeep .wiki/open-questions/.gitkeep +``` + +For migrated `concepts/*.md` pages, **do not rewrite their content** — just prepend a minimal frontmatter if missing: + +```yaml +--- +title: +type: concept +updated: +--- +``` + +Build `index.md` with one entry per migrated `concepts/.md`, derived from the file's H1 and any one-liner the agent can extract. + +Append a line to `log.md`: + +``` +## [] refactor | wiki migrated to canon via setup-wiki@ +``` + +### Phase 5 — Verify + +After writes, confirm: + +- All canon files exist: `CLAUDE.md`, `index.md`, `log.md`, `overview.md`, `raw/README.md`. +- Six content directories exist (`entities/`, `concepts/`, `packages/`, `sources/`, `contradictions/`, `open-questions/`) — with at least `.gitkeep` or content. +- No leftover non-canon files (`SUMMARY.md`, `WORKFLOW.md`, `source/`). +- For migrate mode: every migrated page has frontmatter with `type: concept`. + +If anything's off — restore from `.wiki/.backup-*` and report. + +### Phase 6 — Report + +Print final state: + +``` +✅ Wiki ready at .wiki/. + Mode: greenfield | migrate + Files: 5 canon + 6 dirs + N migrated concept pages + Backup (if migrate): .wiki/.backup-/ + +Next steps for the user: + • Edit .wiki/overview.md to describe the project + • Edit .wiki/CLAUDE.md "Domain conventions" with project-specific rules + • Read using-wiki SKILL.md if unfamiliar with the workflow +``` + +If invoked from `project-bootstrap`, return control silently — bootstrap continues with its remaining steps. + +## Rollback + +1. `rm -rf .wiki/` (greenfield rollback) OR `cp -r .wiki/.backup-/* .wiki/` (migrate rollback). +2. If a git repo, `git reset HEAD .wiki/` to unstage moves. +3. Tell user what failed. + +## Common mistakes + +- **Touching `raw/` content during migration.** `raw/` is immutable — only the `.gitkeep` placeholder may be removed (and that only because `raw/README.md` replaces it). +- **Skipping confirmation on greenfield.** Yes, even greenfield needs the gate — the user might be running this skill in the wrong directory. +- **Re-running on already-canon wiki and rewriting files.** Phase 1 detection guards this; bail out at `noop` mode. +- **Inventing project-specific Domain conventions in `CLAUDE.md`.** The schema's "Domain conventions" section is intentionally a stub — let the user fill it as they accumulate domain knowledge. + +## Cross-platform notes + +The procedure is platform-agnostic. `mkdir -p`, `mv`, `git mv`, `cp -r`, `rm -rf`, `touch` work in git-bash on Windows the same as on Linux/macOS. Wiki paths use forward slashes throughout. diff --git a/skills/superpowers/brainstorming/SKILL.md b/skills/superpowers/brainstorming/SKILL.md new file mode 100644 index 0000000..06cd0a2 --- /dev/null +++ b/skills/superpowers/brainstorming/SKILL.md @@ -0,0 +1,164 @@ +--- +name: brainstorming +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." +--- + +# Brainstorming Ideas Into Designs + +Help turn ideas into fully formed designs and specs through natural collaborative dialogue. + +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. + + +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. + + +## Anti-Pattern: "This Is Too Simple To Need A Design" + +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. + +## Checklist + +You MUST create a task for each of these items and complete them in order: + +1. **Explore project context** — check files, docs, recent commits +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. +3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria +4. **Propose 2-3 approaches** — with trade-offs and your recommendation +5. **Present design** — in sections scaled to their complexity, get user approval after each section +6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD--design.md` and commit +7. **Spec self-review** — quick inline check for placeholders, contradictions, ambiguity, scope (see below) +8. **User reviews written spec** — ask user to review the spec file before proceeding +9. **Transition to implementation** — invoke writing-plans skill to create implementation plan + +## Process Flow + +```dot +digraph brainstorming { + "Explore project context" [shape=box]; + "Visual questions ahead?" [shape=diamond]; + "Offer Visual Companion\n(own message, no other content)" [shape=box]; + "Ask clarifying questions" [shape=box]; + "Propose 2-3 approaches" [shape=box]; + "Present design sections" [shape=box]; + "User approves design?" [shape=diamond]; + "Write design doc" [shape=box]; + "Spec self-review\n(fix inline)" [shape=box]; + "User reviews spec?" [shape=diamond]; + "Invoke writing-plans skill" [shape=doublecircle]; + + "Explore project context" -> "Visual questions ahead?"; + "Visual questions ahead?" -> "Offer Visual Companion\n(own message, no other content)" [label="yes"]; + "Visual questions ahead?" -> "Ask clarifying questions" [label="no"]; + "Offer Visual Companion\n(own message, no other content)" -> "Ask clarifying questions"; + "Ask clarifying questions" -> "Propose 2-3 approaches"; + "Propose 2-3 approaches" -> "Present design sections"; + "Present design sections" -> "User approves design?"; + "User approves design?" -> "Present design sections" [label="no, revise"]; + "User approves design?" -> "Write design doc" [label="yes"]; + "Write design doc" -> "Spec self-review\n(fix inline)"; + "Spec self-review\n(fix inline)" -> "User reviews spec?"; + "User reviews spec?" -> "Write design doc" [label="changes requested"]; + "User reviews spec?" -> "Invoke writing-plans skill" [label="approved"]; +} +``` + +**The terminal state is invoking writing-plans.** Do NOT invoke frontend-design, mcp-builder, or any other implementation skill. The ONLY skill you invoke after brainstorming is writing-plans. + +## The Process + +**Understanding the idea:** + +- Check out the current project state first (files, docs, recent commits) +- 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. +- 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 → plan → implementation cycle. +- For appropriately-scoped projects, ask questions one at a time to refine the idea +- Prefer multiple choice questions when possible, but open-ended is fine too +- Only one question per message - if a topic needs more exploration, break it into multiple questions +- Focus on understanding: purpose, constraints, success criteria + +**Exploring approaches:** + +- Propose 2-3 different approaches with trade-offs +- Present options conversationally with your recommendation and reasoning +- Lead with your recommended option and explain why + +**Presenting the design:** + +- Once you believe you understand what you're building, present the design +- Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced +- Ask after each section whether it looks right so far +- Cover: architecture, components, data flow, error handling, testing +- Be ready to go back and clarify if something doesn't make sense + +**Design for isolation and clarity:** + +- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently +- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on? +- 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. +- 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. + +**Working in existing codebases:** + +- Explore the current structure before proposing changes. Follow existing patterns. +- 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. +- Don't propose unrelated refactoring. Stay focused on what serves the current goal. + +## After the Design + +**Documentation:** + +- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD--design.md` + - (User preferences for spec location override this default) +- Use elements-of-style:writing-clearly-and-concisely skill if available +- Commit the design document to git + +**Spec Self-Review:** +After writing the spec document, look at it with fresh eyes: + +1. **Placeholder scan:** Any "TBD", "TODO", incomplete sections, or vague requirements? Fix them. +2. **Internal consistency:** Do any sections contradict each other? Does the architecture match the feature descriptions? +3. **Scope check:** Is this focused enough for a single implementation plan, or does it need decomposition? +4. **Ambiguity check:** Could any requirement be interpreted two different ways? If so, pick one and make it explicit. + +Fix any issues inline. No need to re-review — just fix and move on. + +**User Review Gate:** +After the spec review loop passes, ask the user to review the written spec before proceeding: + +> "Spec written and committed to ``. Please review it and let me know if you want to make any changes before we start writing out the implementation plan." + +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. + +**Implementation:** + +- Invoke the writing-plans skill to create a detailed implementation plan +- Do NOT invoke any other skill. writing-plans is the next step. + +## Key Principles + +- **One question at a time** - Don't overwhelm with multiple questions +- **Multiple choice preferred** - Easier to answer than open-ended when possible +- **YAGNI ruthlessly** - Remove unnecessary features from all designs +- **Explore alternatives** - Always propose 2-3 approaches before settling +- **Incremental validation** - Present design, get approval before moving on +- **Be flexible** - Go back and clarify when something doesn't make sense + +## Visual Companion + +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. + +**Offering the companion:** When you anticipate that upcoming questions will involve visual content (mockups, layouts, diagrams), offer it once for consent: +> "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)" + +**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. + +**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?** + +- **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs +- **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions + +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. + +If they agree to the companion, read the detailed guide before proceeding: +`skills/brainstorming/visual-companion.md` diff --git a/skills/superpowers/brainstorming/scripts/frame-template.html b/skills/superpowers/brainstorming/scripts/frame-template.html new file mode 100644 index 0000000..dcfe018 --- /dev/null +++ b/skills/superpowers/brainstorming/scripts/frame-template.html @@ -0,0 +1,214 @@ + + + + + Superpowers Brainstorming + + + +
+

Superpowers Brainstorming

+
Connected
+
+ +
+
+ +
+
+ +
+ Click an option above, then return to the terminal +
+ + + diff --git a/skills/superpowers/brainstorming/scripts/helper.js b/skills/superpowers/brainstorming/scripts/helper.js new file mode 100644 index 0000000..111f97f --- /dev/null +++ b/skills/superpowers/brainstorming/scripts/helper.js @@ -0,0 +1,88 @@ +(function() { + const WS_URL = 'ws://' + window.location.host; + let ws = null; + let eventQueue = []; + + function connect() { + ws = new WebSocket(WS_URL); + + ws.onopen = () => { + eventQueue.forEach(e => ws.send(JSON.stringify(e))); + eventQueue = []; + }; + + ws.onmessage = (msg) => { + const data = JSON.parse(msg.data); + if (data.type === 'reload') { + window.location.reload(); + } + }; + + ws.onclose = () => { + setTimeout(connect, 1000); + }; + } + + function sendEvent(event) { + event.timestamp = Date.now(); + if (ws && ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify(event)); + } else { + eventQueue.push(event); + } + } + + // Capture clicks on choice elements + document.addEventListener('click', (e) => { + const target = e.target.closest('[data-choice]'); + if (!target) return; + + sendEvent({ + type: 'click', + text: target.textContent.trim(), + choice: target.dataset.choice, + id: target.id || null + }); + + // Update indicator bar (defer so toggleSelect runs first) + setTimeout(() => { + const indicator = document.getElementById('indicator-text'); + if (!indicator) return; + const container = target.closest('.options') || target.closest('.cards'); + const selected = container ? container.querySelectorAll('.selected') : []; + if (selected.length === 0) { + indicator.textContent = 'Click an option above, then return to the terminal'; + } else if (selected.length === 1) { + const label = selected[0].querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || selected[0].dataset.choice; + indicator.innerHTML = '' + label + ' selected — return to terminal to continue'; + } else { + indicator.innerHTML = '' + selected.length + ' selected — return to terminal to continue'; + } + }, 0); + }); + + // Frame UI: selection tracking + window.selectedChoice = null; + + window.toggleSelect = function(el) { + const container = el.closest('.options') || el.closest('.cards'); + const multi = container && container.dataset.multiselect !== undefined; + if (container && !multi) { + container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected')); + } + if (multi) { + el.classList.toggle('selected'); + } else { + el.classList.add('selected'); + } + window.selectedChoice = el.dataset.choice; + }; + + // Expose API for explicit use + window.brainstorm = { + send: sendEvent, + choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata }) + }; + + connect(); +})(); diff --git a/skills/superpowers/brainstorming/scripts/server.cjs b/skills/superpowers/brainstorming/scripts/server.cjs new file mode 100644 index 0000000..562c17f --- /dev/null +++ b/skills/superpowers/brainstorming/scripts/server.cjs @@ -0,0 +1,354 @@ +const crypto = require('crypto'); +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +// ========== WebSocket Protocol (RFC 6455) ========== + +const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A }; +const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; + +function computeAcceptKey(clientKey) { + return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64'); +} + +function encodeFrame(opcode, payload) { + const fin = 0x80; + const len = payload.length; + let header; + + if (len < 126) { + header = Buffer.alloc(2); + header[0] = fin | opcode; + header[1] = len; + } else if (len < 65536) { + header = Buffer.alloc(4); + header[0] = fin | opcode; + header[1] = 126; + header.writeUInt16BE(len, 2); + } else { + header = Buffer.alloc(10); + header[0] = fin | opcode; + header[1] = 127; + header.writeBigUInt64BE(BigInt(len), 2); + } + + return Buffer.concat([header, payload]); +} + +function decodeFrame(buffer) { + if (buffer.length < 2) return null; + + const secondByte = buffer[1]; + const opcode = buffer[0] & 0x0F; + const masked = (secondByte & 0x80) !== 0; + let payloadLen = secondByte & 0x7F; + let offset = 2; + + if (!masked) throw new Error('Client frames must be masked'); + + if (payloadLen === 126) { + if (buffer.length < 4) return null; + payloadLen = buffer.readUInt16BE(2); + offset = 4; + } else if (payloadLen === 127) { + if (buffer.length < 10) return null; + payloadLen = Number(buffer.readBigUInt64BE(2)); + offset = 10; + } + + const maskOffset = offset; + const dataOffset = offset + 4; + const totalLen = dataOffset + payloadLen; + if (buffer.length < totalLen) return null; + + const mask = buffer.slice(maskOffset, dataOffset); + const data = Buffer.alloc(payloadLen); + for (let i = 0; i < payloadLen; i++) { + data[i] = buffer[dataOffset + i] ^ mask[i % 4]; + } + + return { opcode, payload: data, bytesConsumed: totalLen }; +} + +// ========== Configuration ========== + +const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383)); +const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1'; +const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST); +const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm'; +const CONTENT_DIR = path.join(SESSION_DIR, 'content'); +const STATE_DIR = path.join(SESSION_DIR, 'state'); +let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null; + +const MIME_TYPES = { + '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript', + '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml' +}; + +// ========== Templates and Constants ========== + +const WAITING_PAGE = ` + +Brainstorm Companion + + +

Brainstorm Companion

+

Waiting for the agent to push a screen...

`; + +const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8'); +const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8'); +const helperInjection = ''; + +// ========== Helper Functions ========== + +function isFullDocument(html) { + const trimmed = html.trimStart().toLowerCase(); + return trimmed.startsWith('', content); +} + +function getNewestScreen() { + const files = fs.readdirSync(CONTENT_DIR) + .filter(f => f.endsWith('.html')) + .map(f => { + const fp = path.join(CONTENT_DIR, f); + return { path: fp, mtime: fs.statSync(fp).mtime.getTime() }; + }) + .sort((a, b) => b.mtime - a.mtime); + return files.length > 0 ? files[0].path : null; +} + +// ========== HTTP Request Handler ========== + +function handleRequest(req, res) { + touchActivity(); + if (req.method === 'GET' && req.url === '/') { + const screenFile = getNewestScreen(); + let html = screenFile + ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8')) + : WAITING_PAGE; + + if (html.includes('')) { + html = html.replace('', helperInjection + '\n'); + } else { + html += helperInjection; + } + + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + res.end(html); + } else if (req.method === 'GET' && req.url.startsWith('/files/')) { + const fileName = req.url.slice(7); + const filePath = path.join(CONTENT_DIR, path.basename(fileName)); + if (!fs.existsSync(filePath)) { + res.writeHead(404); + res.end('Not found'); + return; + } + const ext = path.extname(filePath).toLowerCase(); + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; + res.writeHead(200, { 'Content-Type': contentType }); + res.end(fs.readFileSync(filePath)); + } else { + res.writeHead(404); + res.end('Not found'); + } +} + +// ========== WebSocket Connection Handling ========== + +const clients = new Set(); + +function handleUpgrade(req, socket) { + const key = req.headers['sec-websocket-key']; + if (!key) { socket.destroy(); return; } + + const accept = computeAcceptKey(key); + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n' + ); + + let buffer = Buffer.alloc(0); + clients.add(socket); + + socket.on('data', (chunk) => { + buffer = Buffer.concat([buffer, chunk]); + while (buffer.length > 0) { + let result; + try { + result = decodeFrame(buffer); + } catch (e) { + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); + clients.delete(socket); + return; + } + if (!result) break; + buffer = buffer.slice(result.bytesConsumed); + + switch (result.opcode) { + case OPCODES.TEXT: + handleMessage(result.payload.toString()); + break; + case OPCODES.CLOSE: + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); + clients.delete(socket); + return; + case OPCODES.PING: + socket.write(encodeFrame(OPCODES.PONG, result.payload)); + break; + case OPCODES.PONG: + break; + default: { + const closeBuf = Buffer.alloc(2); + closeBuf.writeUInt16BE(1003); + socket.end(encodeFrame(OPCODES.CLOSE, closeBuf)); + clients.delete(socket); + return; + } + } + } + }); + + socket.on('close', () => clients.delete(socket)); + socket.on('error', () => clients.delete(socket)); +} + +function handleMessage(text) { + let event; + try { + event = JSON.parse(text); + } catch (e) { + console.error('Failed to parse WebSocket message:', e.message); + return; + } + touchActivity(); + console.log(JSON.stringify({ source: 'user-event', ...event })); + if (event.choice) { + const eventsFile = path.join(STATE_DIR, 'events'); + fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n'); + } +} + +function broadcast(msg) { + const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg))); + for (const socket of clients) { + try { socket.write(frame); } catch (e) { clients.delete(socket); } + } +} + +// ========== Activity Tracking ========== + +const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes +let lastActivity = Date.now(); + +function touchActivity() { + lastActivity = Date.now(); +} + +// ========== File Watching ========== + +const debounceTimers = new Map(); + +// ========== Server Startup ========== + +function startServer() { + if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true }); + if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true }); + + // Track known files to distinguish new screens from updates. + // macOS fs.watch reports 'rename' for both new files and overwrites, + // so we can't rely on eventType alone. + const knownFiles = new Set( + fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html')) + ); + + const server = http.createServer(handleRequest); + server.on('upgrade', handleUpgrade); + + const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => { + if (!filename || !filename.endsWith('.html')) return; + + if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename)); + debounceTimers.set(filename, setTimeout(() => { + debounceTimers.delete(filename); + const filePath = path.join(CONTENT_DIR, filename); + + if (!fs.existsSync(filePath)) return; // file was deleted + touchActivity(); + + if (!knownFiles.has(filename)) { + knownFiles.add(filename); + const eventsFile = path.join(STATE_DIR, 'events'); + if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile); + console.log(JSON.stringify({ type: 'screen-added', file: filePath })); + } else { + console.log(JSON.stringify({ type: 'screen-updated', file: filePath })); + } + + broadcast({ type: 'reload' }); + }, 100)); + }); + watcher.on('error', (err) => console.error('fs.watch error:', err.message)); + + function shutdown(reason) { + console.log(JSON.stringify({ type: 'server-stopped', reason })); + const infoFile = path.join(STATE_DIR, 'server-info'); + if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile); + fs.writeFileSync( + path.join(STATE_DIR, 'server-stopped'), + JSON.stringify({ reason, timestamp: Date.now() }) + '\n' + ); + watcher.close(); + clearInterval(lifecycleCheck); + server.close(() => process.exit(0)); + } + + function ownerAlive() { + if (!ownerPid) return true; + try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; } + } + + // Check every 60s: exit if owner process died or idle for 30 minutes + const lifecycleCheck = setInterval(() => { + if (!ownerAlive()) shutdown('owner process exited'); + else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout'); + }, 60 * 1000); + lifecycleCheck.unref(); + + // Validate owner PID at startup. If it's already dead, the PID resolution + // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios). + // Disable monitoring and rely on the idle timeout instead. + if (ownerPid) { + try { process.kill(ownerPid, 0); } + catch (e) { + if (e.code !== 'EPERM') { + console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' })); + ownerPid = null; + } + } + } + + server.listen(PORT, HOST, () => { + const info = JSON.stringify({ + type: 'server-started', port: Number(PORT), host: HOST, + url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT, + screen_dir: CONTENT_DIR, state_dir: STATE_DIR + }); + console.log(info); + fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n'); + }); +} + +if (require.main === module) { + startServer(); +} + +module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES }; diff --git a/skills/superpowers/brainstorming/scripts/start-server.sh b/skills/superpowers/brainstorming/scripts/start-server.sh new file mode 100644 index 0000000..9ef6dcb --- /dev/null +++ b/skills/superpowers/brainstorming/scripts/start-server.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Start the brainstorm server and output connection info +# Usage: start-server.sh [--project-dir ] [--host ] [--url-host ] [--foreground] [--background] +# +# Starts server on a random high port, outputs JSON with URL. +# Each session gets its own directory to avoid conflicts. +# +# Options: +# --project-dir Store session files under /.superpowers/brainstorm/ +# instead of /tmp. Files persist after server stops. +# --host Host/interface to bind (default: 127.0.0.1). +# Use 0.0.0.0 in remote/containerized environments. +# --url-host Hostname shown in returned URL JSON. +# --foreground Run server in the current terminal (no backgrounding). +# --background Force background mode (overrides Codex auto-foreground). + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# Parse arguments +PROJECT_DIR="" +FOREGROUND="false" +FORCE_BACKGROUND="false" +BIND_HOST="127.0.0.1" +URL_HOST="" +while [[ $# -gt 0 ]]; do + case "$1" in + --project-dir) + PROJECT_DIR="$2" + shift 2 + ;; + --host) + BIND_HOST="$2" + shift 2 + ;; + --url-host) + URL_HOST="$2" + shift 2 + ;; + --foreground|--no-daemon) + FOREGROUND="true" + shift + ;; + --background|--daemon) + FORCE_BACKGROUND="true" + shift + ;; + *) + echo "{\"error\": \"Unknown argument: $1\"}" + exit 1 + ;; + esac +done + +if [[ -z "$URL_HOST" ]]; then + if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then + URL_HOST="localhost" + else + URL_HOST="$BIND_HOST" + fi +fi + +# Some environments reap detached/background processes. Auto-foreground when detected. +if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then + FOREGROUND="true" +fi + +# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected. +if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then + case "${OSTYPE:-}" in + msys*|cygwin*|mingw*) FOREGROUND="true" ;; + esac + if [[ -n "${MSYSTEM:-}" ]]; then + FOREGROUND="true" + fi +fi + +# Generate unique session directory +SESSION_ID="$$-$(date +%s)" + +if [[ -n "$PROJECT_DIR" ]]; then + SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}" +else + SESSION_DIR="/tmp/brainstorm-${SESSION_ID}" +fi + +STATE_DIR="${SESSION_DIR}/state" +PID_FILE="${STATE_DIR}/server.pid" +LOG_FILE="${STATE_DIR}/server.log" + +# Create fresh session directory with content and state peers +mkdir -p "${SESSION_DIR}/content" "$STATE_DIR" + +# Kill any existing server +if [[ -f "$PID_FILE" ]]; then + old_pid=$(cat "$PID_FILE") + kill "$old_pid" 2>/dev/null + rm -f "$PID_FILE" +fi + +cd "$SCRIPT_DIR" + +# Resolve the harness PID (grandparent of this script). +# $PPID is the ephemeral shell the harness spawned to run us — it dies +# when this script exits. The harness itself is $PPID's parent. +OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')" +if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then + OWNER_PID="$PPID" +fi + +# Foreground mode for environments that reap detached/background processes. +if [[ "$FOREGROUND" == "true" ]]; then + echo "$$" > "$PID_FILE" + env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs + exit $? +fi + +# Start server, capturing output to log file +# Use nohup to survive shell exit; disown to remove from job table +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 & +SERVER_PID=$! +disown "$SERVER_PID" 2>/dev/null +echo "$SERVER_PID" > "$PID_FILE" + +# Wait for server-started message (check log file) +for i in {1..50}; do + if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then + # Verify server is still alive after a short window (catches process reapers) + alive="true" + for _ in {1..20}; do + if ! kill -0 "$SERVER_PID" 2>/dev/null; then + alive="false" + break + fi + sleep 0.1 + done + if [[ "$alive" != "true" ]]; then + 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\"}" + exit 1 + fi + grep "server-started" "$LOG_FILE" | head -1 + exit 0 + fi + sleep 0.1 +done + +# Timeout - server didn't start +echo '{"error": "Server failed to start within 5 seconds"}' +exit 1 diff --git a/skills/superpowers/brainstorming/scripts/stop-server.sh b/skills/superpowers/brainstorming/scripts/stop-server.sh new file mode 100644 index 0000000..a6b94e6 --- /dev/null +++ b/skills/superpowers/brainstorming/scripts/stop-server.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Stop the brainstorm server and clean up +# Usage: stop-server.sh +# +# Kills the server process. Only deletes session directory if it's +# under /tmp (ephemeral). Persistent directories (.superpowers/) are +# kept so mockups can be reviewed later. + +SESSION_DIR="$1" + +if [[ -z "$SESSION_DIR" ]]; then + echo '{"error": "Usage: stop-server.sh "}' + exit 1 +fi + +STATE_DIR="${SESSION_DIR}/state" +PID_FILE="${STATE_DIR}/server.pid" + +if [[ -f "$PID_FILE" ]]; then + pid=$(cat "$PID_FILE") + + # Try to stop gracefully, fallback to force if still alive + kill "$pid" 2>/dev/null || true + + # Wait for graceful shutdown (up to ~2s) + for i in {1..20}; do + if ! kill -0 "$pid" 2>/dev/null; then + break + fi + sleep 0.1 + done + + # If still running, escalate to SIGKILL + if kill -0 "$pid" 2>/dev/null; then + kill -9 "$pid" 2>/dev/null || true + + # Give SIGKILL a moment to take effect + sleep 0.1 + fi + + if kill -0 "$pid" 2>/dev/null; then + echo '{"status": "failed", "error": "process still running"}' + exit 1 + fi + + rm -f "$PID_FILE" "${STATE_DIR}/server.log" + + # Only delete ephemeral /tmp directories + if [[ "$SESSION_DIR" == /tmp/* ]]; then + rm -rf "$SESSION_DIR" + fi + + echo '{"status": "stopped"}' +else + echo '{"status": "not_running"}' +fi diff --git a/skills/superpowers/brainstorming/spec-document-reviewer-prompt.md b/skills/superpowers/brainstorming/spec-document-reviewer-prompt.md new file mode 100644 index 0000000..35acbb6 --- /dev/null +++ b/skills/superpowers/brainstorming/spec-document-reviewer-prompt.md @@ -0,0 +1,49 @@ +# Spec Document Reviewer Prompt Template + +Use this template when dispatching a spec document reviewer subagent. + +**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning. + +**Dispatch after:** Spec document is written to docs/superpowers/specs/ + +``` +Task tool (general-purpose): + description: "Review spec document" + prompt: | + You are a spec document reviewer. Verify this spec is complete and ready for planning. + + **Spec to review:** [SPEC_FILE_PATH] + + ## What to Check + + | Category | What to Look For | + |----------|------------------| + | Completeness | TODOs, placeholders, "TBD", incomplete sections | + | Consistency | Internal contradictions, conflicting requirements | + | Clarity | Requirements ambiguous enough to cause someone to build the wrong thing | + | Scope | Focused enough for a single plan — not covering multiple independent subsystems | + | YAGNI | Unrequested features, over-engineering | + + ## Calibration + + **Only flag issues that would cause real problems during implementation planning.** + A missing section, a contradiction, or a requirement so ambiguous it could be + interpreted two different ways — those are issues. Minor wording improvements, + stylistic preferences, and "sections less detailed than others" are not. + + Approve unless there are serious gaps that would lead to a flawed plan. + + ## Output Format + + ## Spec Review + + **Status:** Approved | Issues Found + + **Issues (if any):** + - [Section X]: [specific issue] - [why it matters for planning] + + **Recommendations (advisory, do not block approval):** + - [suggestions for improvement] +``` + +**Reviewer returns:** Status, Issues (if any), Recommendations diff --git a/skills/superpowers/brainstorming/visual-companion.md b/skills/superpowers/brainstorming/visual-companion.md new file mode 100644 index 0000000..2113863 --- /dev/null +++ b/skills/superpowers/brainstorming/visual-companion.md @@ -0,0 +1,287 @@ +# Visual Companion Guide + +Browser-based visual brainstorming companion for showing mockups, diagrams, and options. + +## When to Use + +Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?** + +**Use the browser** when the content itself is visual: + +- **UI mockups** — wireframes, layouts, navigation structures, component designs +- **Architecture diagrams** — system components, data flow, relationship maps +- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions +- **Design polish** — when the question is about look and feel, spacing, visual hierarchy +- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams + +**Use the terminal** when the content is text or tabular: + +- **Requirements and scope questions** — "what does X mean?", "which features are in scope?" +- **Conceptual A/B/C choices** — picking between approaches described in words +- **Tradeoff lists** — pros/cons, comparison tables +- **Technical decisions** — API design, data modeling, architectural approach selection +- **Clarifying questions** — anything where the answer is words, not a visual preference + +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. + +## How It Works + +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. + +**Content fragments vs full documents:** If your HTML file starts with `/.superpowers/brainstorm/` for the session directory. + +**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. + +**Launching the server by platform:** + +**Claude Code (macOS / Linux):** +```bash +# Default mode works — the script backgrounds the server itself +scripts/start-server.sh --project-dir /path/to/project +``` + +**Claude Code (Windows):** +```bash +# Windows auto-detects and uses foreground mode, which blocks the tool call. +# Use run_in_background: true on the Bash tool call so the server survives +# across conversation turns. +scripts/start-server.sh --project-dir /path/to/project +``` +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. + +**Codex:** +```bash +# Codex reaps background processes. The script auto-detects CODEX_CI and +# switches to foreground mode. Run it normally — no extra flags needed. +scripts/start-server.sh --project-dir /path/to/project +``` + +**Gemini CLI:** +```bash +# Use --foreground and set is_background: true on your shell tool call +# so the process survives across turns +scripts/start-server.sh --project-dir /path/to/project --foreground +``` + +**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. + +If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host: + +```bash +scripts/start-server.sh \ + --project-dir /path/to/project \ + --host 0.0.0.0 \ + --url-host localhost +``` + +Use `--url-host` to control what hostname is printed in the returned URL JSON. + +## The Loop + +1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`: + - 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. + - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html` + - **Never reuse filenames** — each screen gets a fresh file + - Use Write tool — **never use cat/heredoc** (dumps noise into terminal) + - Server automatically serves the newest file + +2. **Tell user what to expect and end your turn:** + - Remind them of the URL (every step, not just first) + - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage") + - 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." + +3. **On your next turn** — after the user responds in the terminal: + - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines + - Merge with the user's terminal text to get the full picture + - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data + +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. + +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: + + ```html + +
+

Continuing in terminal...

+
+ ``` + + 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. + +6. Repeat until done. + +## Writing Content Fragments + +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). + +**Minimal example:** + +```html +

Which layout works better?

+

Consider readability and visual hierarchy

+ +
+
+
A
+
+

Single Column

+

Clean, focused reading experience

+
+
+
+
B
+
+

Two Column

+

Sidebar navigation with main content

+
+
+
+``` + +That's it. No ``, no CSS, no `