Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9fd5a054b3 | ||
|
|
da76a6b3d2 | ||
|
|
fc6d5628a7 | ||
|
|
1f7f53e6c0 | ||
|
|
bedb6d278d | ||
|
|
e9ad692418 | ||
|
|
86529d2ac5 | ||
|
|
d6e892ac4c | ||
|
|
4d6ebb626f | ||
|
|
88a4fa407b | ||
|
|
808af7b020 | ||
|
|
40405cd95a | ||
|
|
39ac61c411 | ||
|
|
2cb6b54a5e | ||
|
|
1448963823 | ||
|
|
58687c68a6 | ||
|
|
0c7fac3686 | ||
|
|
cba0fe4337 | ||
|
|
06592805b6 | ||
|
|
1d140ec525 | ||
|
|
2fcc15e9e4 | ||
|
|
b2af4e1129 | ||
|
|
3c8d2f5613 | ||
|
|
1d368d4b5d | ||
|
|
a565b04e91 | ||
|
|
b616c51a2c | ||
|
|
b8bacfa7b3 | ||
|
|
c377c23e21 | ||
|
|
8f9d5dd8bd | ||
|
|
7ba01abdbe | ||
|
|
9a81a707af | ||
|
|
5070a738e8 | ||
|
|
8da7c9c45f | ||
|
|
6e5024d498 | ||
|
|
62cfe46927 | ||
|
|
de84800892 | ||
|
|
51a2d396fd | ||
|
|
bb912e5594 | ||
|
|
08c935ba8a | ||
|
|
84a012cd0f | ||
|
|
e12ac99465 | ||
|
|
dc97fd4a36 | ||
|
|
d7775aac57 | ||
|
|
c6787e04d7 | ||
|
|
90a58f0b9e | ||
|
|
15737321ac | ||
|
|
025f01aa80 | ||
|
|
eee62e4fc0 | ||
|
|
a2afb35d1d | ||
|
|
ad17a7c6c0 | ||
|
|
21dbb35526 | ||
|
|
8ad2079f86 | ||
|
|
b188965161 | ||
|
|
ae66840a03 | ||
|
|
e7e514390b | ||
|
|
087685f2e3 | ||
|
|
83b069afba | ||
|
|
a699ad8cbd | ||
|
|
a42ec18f40 | ||
|
|
46ff1acdfe | ||
|
|
3112b4ce92 | ||
|
|
51a8c25b4d | ||
|
|
d40169f2b7 | ||
|
|
d4f0416dc5 | ||
|
|
abd81f939a | ||
|
|
e42d2ba9cb | ||
|
|
68cebc0bbb | ||
|
|
f50dd6be6a | ||
|
|
1906a774b3 | ||
|
|
38f905e705 | ||
|
|
7db7e0779b | ||
|
|
0be3506799 | ||
|
|
6151b973bc | ||
|
|
6c1b6ce9db | ||
|
|
5c8341c797 | ||
|
|
5ca44c9c6b | ||
|
|
e2a312d05e | ||
|
|
78b9b59eca | ||
|
|
88c54399fe | ||
|
|
747c6c7f4c | ||
|
|
56a947b2a0 | ||
|
|
21be3ea245 | ||
|
|
85e125703e | ||
|
|
1256653319 | ||
|
|
7292e50d12 | ||
|
|
cf19fc52ce | ||
|
|
ef72982489 | ||
|
|
1e29c6d1af | ||
|
|
5ffa397029 | ||
|
|
8f14c572b9 | ||
|
|
b7d8cfc3cc | ||
|
|
e553dae354 | ||
|
|
5a2bef35c1 |
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "mathias",
|
||||
"description": "Mathias's private plugin marketplace, hosted on gitea.d-ma.be. Self-hosted by design — nothing here transits GitHub.",
|
||||
"owner": {
|
||||
"name": "Mathias",
|
||||
"url": "https://git.d-ma.be/mathias"
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "skills",
|
||||
"source": ".",
|
||||
"description": "Engineering skills, the pre-task-ritual and secret-guard hooks, and the brain/gitea/infra MCP servers as one versioned unit."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "skills",
|
||||
"description": "Mathias's engineering skills library, plus the hooks and MCP servers that make it enforceable: TDD, clean code, debugging, specs, discovery, CI, and secret hygiene.",
|
||||
"version": "0.19.1",
|
||||
"author": {
|
||||
"name": "Mathias",
|
||||
"url": "https://git.d-ma.be/mathias"
|
||||
},
|
||||
"homepage": "https://git.d-ma.be/mathias/skills",
|
||||
"repository": "https://git.d-ma.be/mathias/skills.git"
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
name: CI
|
||||
|
||||
# Two jobs, in order:
|
||||
#
|
||||
# gate — `task check` (structure, frontmatter, manifest/tag parity) plus
|
||||
# `task test` (hooks, doctor, release-skip). Runs on every push and
|
||||
# every PR. Before this existed the suite ran nowhere: CI reported
|
||||
# green having tested nothing (#22).
|
||||
#
|
||||
# tag — auto-tags a push to main with a semver bump derived from the latest
|
||||
# commit footer:
|
||||
# Bump-Type: major → vX.0.0
|
||||
# Bump-Type: minor → v0.Y.0
|
||||
# (default) → v0.0.Z (patch)
|
||||
# Skips when the commit carries the `Skip-Release: true` trailer (the
|
||||
# tagger's own manifest bump) to prevent recursion. Gated on `gate`,
|
||||
# so a red check cannot ship a tag.
|
||||
|
||||
"on":
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
name: Check / Test
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# `task check` compares plugin.json's version to `git describe`;
|
||||
# a shallow checkout has no tags and would skip that assertion.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Verify toolchain
|
||||
run: task --version
|
||||
|
||||
- name: Structure gate
|
||||
run: task check
|
||||
|
||||
- name: Shell test suite
|
||||
run: task test
|
||||
|
||||
tag:
|
||||
name: Tag release
|
||||
needs: gate
|
||||
runs-on: self-hosted
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
- name: derive next version
|
||||
id: bump
|
||||
run: |
|
||||
set -euo pipefail
|
||||
last_commit=$(git log -1 --pretty=%B)
|
||||
# Delegated to bin/should-skip-release so the rule is covered by
|
||||
# tests/release_skip_test.sh rather than living untested in YAML.
|
||||
if printf '%s\n' "$last_commit" | sh bin/should-skip-release; then
|
||||
echo "skipping — commit carries the Skip-Release trailer"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
latest=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0")
|
||||
major=$(echo "$latest" | sed -E 's/^v([0-9]+)\.([0-9]+)\.([0-9]+)$/\1/')
|
||||
minor=$(echo "$latest" | sed -E 's/^v([0-9]+)\.([0-9]+)\.([0-9]+)$/\2/')
|
||||
patch=$(echo "$latest" | sed -E 's/^v([0-9]+)\.([0-9]+)\.([0-9]+)$/\3/')
|
||||
bump=$(printf '%s' "$last_commit" | grep -iE '^Bump-Type:' | head -1 | awk '{print tolower($2)}' || true)
|
||||
case "$bump" in
|
||||
major) major=$((major + 1)); minor=0; patch=0 ;;
|
||||
minor) minor=$((minor + 1)); patch=0 ;;
|
||||
*) patch=$((patch + 1)) ;;
|
||||
esac
|
||||
next="v${major}.${minor}.${patch}"
|
||||
echo "previous=$latest"
|
||||
echo "bump=${bump:-patch}"
|
||||
echo "next=$next"
|
||||
echo "tag=$next" >> "$GITHUB_OUTPUT"
|
||||
echo "skip=false" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: tag + push
|
||||
if: steps.bump.outputs.skip != 'true'
|
||||
env:
|
||||
TAG: ${{ steps.bump.outputs.tag }}
|
||||
GITEA_ACTOR: ${{ gitea.actor }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config user.name "${GITEA_ACTOR}"
|
||||
git config user.email "${GITEA_ACTOR}@noreply.gitea.d-ma.be"
|
||||
|
||||
# The tag goes up FIRST and on its own. It names the commit this run
|
||||
# checked out and can never be rejected, however far main has moved.
|
||||
git tag -a "$TAG" -m "release $TAG"
|
||||
git push origin "$TAG"
|
||||
echo "pushed $TAG"
|
||||
|
||||
# The manifest bump is a separate concern and must land on whatever
|
||||
# main is NOW. The runner is maxParallel=1 and shared with other
|
||||
# repos, so a job routinely starts several commits after its own —
|
||||
# pushing this run's stale HEAD to main is then rejected
|
||||
# non-fast-forward, which is how v0.10.0 ended up tagged with the
|
||||
# manifest still reading 0.9.0.
|
||||
#
|
||||
# Claude Code gates plugin updates on this field: if it does not
|
||||
# move, installed hosts never see the release. `task check` asserts
|
||||
# the manifest is not behind the latest tag, so a failure here is a
|
||||
# red main, not a cosmetic miss.
|
||||
manifest=.claude-plugin/plugin.json
|
||||
version="${TAG#v}"
|
||||
|
||||
for attempt in 1 2 3; do
|
||||
git fetch --quiet origin main
|
||||
git checkout --quiet -B release-bump origin/main
|
||||
|
||||
current=$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$manifest" | head -1)
|
||||
if [ "$current" = "$version" ]; then
|
||||
echo "manifest already at $version"
|
||||
exit 0
|
||||
fi
|
||||
# A later run may have bumped past us while this one waited.
|
||||
if [ "$(sh bin/newer-version "$current" "$version")" = "$current" ]; then
|
||||
echo "manifest is $current, already newer than $version — leaving it"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sed -i "s/\"version\"[[:space:]]*:[[:space:]]*\"$current\"/\"version\": \"$version\"/" "$manifest"
|
||||
git add "$manifest"
|
||||
# The trailer below stops this push from re-triggering the tagger.
|
||||
git commit -m "chore(release): plugin.json version $version" -m "Skip-Release: true"
|
||||
if git push origin HEAD:main; then
|
||||
echo "bumped $manifest to $version"
|
||||
exit 0
|
||||
fi
|
||||
echo "main moved while bumping — retry $attempt"
|
||||
done
|
||||
|
||||
echo "could not land the manifest bump after 3 attempts" >&2
|
||||
exit 1
|
||||
@@ -1,68 +0,0 @@
|
||||
name: release
|
||||
|
||||
# Auto-tag every push to main with a semver bump derived from the latest
|
||||
# commit footer:
|
||||
# Bump-Type: major → vX.0.0
|
||||
# Bump-Type: minor → v0.Y.0
|
||||
# (default) → v0.0.Z (patch)
|
||||
#
|
||||
# Skips when the latest commit is itself the auto-tagger (commit message
|
||||
# contains "[skip-release]") to prevent recursion. Tag is pushed back
|
||||
# to the repo using the GITEA_TOKEN provided by act_runner.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
tag:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
- name: derive next version
|
||||
id: bump
|
||||
run: |
|
||||
set -euo pipefail
|
||||
last_commit=$(git log -1 --pretty=%B)
|
||||
if printf '%s' "$last_commit" | grep -qi '\[skip-release\]'; then
|
||||
echo "skipping — commit marked [skip-release]"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
latest=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0")
|
||||
major=$(echo "$latest" | sed -E 's/^v([0-9]+)\.([0-9]+)\.([0-9]+)$/\1/')
|
||||
minor=$(echo "$latest" | sed -E 's/^v([0-9]+)\.([0-9]+)\.([0-9]+)$/\2/')
|
||||
patch=$(echo "$latest" | sed -E 's/^v([0-9]+)\.([0-9]+)\.([0-9]+)$/\3/')
|
||||
bump=$(printf '%s' "$last_commit" | grep -iE '^Bump-Type:' | head -1 | awk '{print tolower($2)}')
|
||||
case "$bump" in
|
||||
major) major=$((major + 1)); minor=0; patch=0 ;;
|
||||
minor) minor=$((minor + 1)); patch=0 ;;
|
||||
*) patch=$((patch + 1)) ;;
|
||||
esac
|
||||
next="v${major}.${minor}.${patch}"
|
||||
echo "previous=$latest"
|
||||
echo "bump=${bump:-patch}"
|
||||
echo "next=$next"
|
||||
echo "tag=$next" >> "$GITHUB_OUTPUT"
|
||||
echo "skip=false" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: tag + push
|
||||
if: steps.bump.outputs.skip != 'true'
|
||||
env:
|
||||
TAG: ${{ steps.bump.outputs.tag }}
|
||||
GITEA_ACTOR: ${{ gitea.actor }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config user.name "${GITEA_ACTOR}"
|
||||
git config user.email "${GITEA_ACTOR}@noreply.gitea.d-ma.be"
|
||||
git tag -a "$TAG" -m "release $TAG"
|
||||
# gitea-actions checkout uses an x-access-token URL; reuse it.
|
||||
git push origin "$TAG"
|
||||
echo "pushed $TAG"
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"_comment": "Tailscale Serve on koala, not the public d-ma.be hostnames. The public path exits to Cloudflare and NPM to reach a k3s service on the same machine most sessions run on, which imposes rate limits and message-size caps on tool results. Serve terminates TLS with a real Tailscale cert and proxies to the NodePort over loopback, so traffic reaches the service from koala itself and satisfies the default-deny-ingress NetworkPolicy with no cluster change. Clients need 'tailscale set --accept-dns=true' for the MagicDNS name to resolve; see mathias/skills#24. Every ${VAR} below must be one ~/.op-env defines -- bin/check-mcp-env enforces that, because an undefined one sends an empty Authorization header and reports as 'requires authentication', which is indistinguishable from a revoked credential.",
|
||||
"mcpServers": {
|
||||
"brain": {
|
||||
"type": "http",
|
||||
"url": "https://koala.tail30472e.ts.net:8443/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${BRAIN_MCP_TOKEN}"
|
||||
}
|
||||
},
|
||||
"infra": {
|
||||
"type": "http",
|
||||
"url": "https://koala.tail30472e.ts.net:8444/mcp"
|
||||
},
|
||||
"gitea": {
|
||||
"_comment": "gitea-mcp authenticates by PASS-THROUGH: the bearer is a Gitea PAT, which the server validates against Gitea and then acts as. So no dedicated MCP token is needed, and the AgentSecrets blocker that parked this entry (skills#32, #33) never applied to it -- DMABE_GITEA_API_TOKEN is op://HomeLab and already in the session environment. Verified 2026-09-07: initialize 200 (serverInfo gitea-mcp) and tools/list returns 41 tools. Two DIFFERENT PATs both authenticate while GITEA_MCP_TOKEN 401s, which is what proves this is pass-through validation and not a static-token comparison.",
|
||||
"type": "http",
|
||||
"url": "https://koala.tail30472e.ts.net:8446/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${DMABE_GITEA_API_TOKEN}"
|
||||
}
|
||||
}
|
||||
},
|
||||
"_parked": {
|
||||
"_reason": "cad is proxied, reachable and AUTHENTICATING: tailscale serve 8445 -> 127.0.0.1:31877, and an MCP initialize with the correct bearer returns 200 (serverInfo cad aed2aaf). It stays parked only because nothing puts CAD_MCP_TOKEN into the session environment. It lives in the 1Password AgentSecrets vault, and by deliberate design (infra#224, closed) no single identity on koala reads both vaults: koala-homelab is HomeLab-only and resolves ~/.op-env, koala-agentsecrets-write is AgentSecrets-only and lives in ~/.op-agent-write.env. Adding an AgentSecrets reference to ~/.op-env does NOT degrade gracefully -- `op run` fails wholesale and every other token, BRAIN_MCP_TOKEN included, goes unresolved with it. Enabling needs a read-scoped AgentSecrets identity in the session-env path; see mathias/skills#32, #33. gitea was parked here for the same stated reason and has been unparked: it needs no AgentSecrets token at all, because gitea-mcp is pass-through-authenticated.",
|
||||
"cad": {
|
||||
"type": "http",
|
||||
"url": "https://koala.tail30472e.ts.net:8445/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${CAD_MCP_TOKEN}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
# skills
|
||||
|
||||
Engineering skills library — markdown `SKILL.md` files that plug into any
|
||||
project or AI-coding harness. Installed via `task skills:install` in
|
||||
consumer projects, or directly by `install.sh` on hosts without Task.
|
||||
AI-coding harness.
|
||||
|
||||
For **Claude Code** this repo is a plugin, installed from the marketplace it
|
||||
also hosts; that path carries the hooks and MCP servers too. For **Crush, Pi
|
||||
and OpenCode** it is a plain library wired by `install.sh` as one directory
|
||||
symlink per harness. See [`SKILLS_INDEX.md`](./SKILLS_INDEX.md#wiring-into-tools).
|
||||
|
||||
## What is a skill?
|
||||
|
||||
@@ -16,65 +20,117 @@ references.
|
||||
See [`SKILLS_INDEX.md`](./SKILLS_INDEX.md) for the full catalogue with
|
||||
descriptions and "use when" triggers.
|
||||
|
||||
## Install (consumer project)
|
||||
## Install
|
||||
|
||||
The expected pattern: each consumer project's `Taskfile.yml` has a
|
||||
`skills:install` target that delegates here. From a project root:
|
||||
### Claude Code — the plugin
|
||||
|
||||
```bash
|
||||
task skills:install
|
||||
```
|
||||
/plugin marketplace add https://git.d-ma.be/mathias/skills.git
|
||||
/plugin install skills@mathias
|
||||
```
|
||||
|
||||
Bare-shell fallback for hosts without Task installed:
|
||||
The plugin ships skills, the `secret-guard` + `pre-task-ritual` hooks, and the
|
||||
brain/gitea/infra MCP servers as one versioned unit. Skills are namespaced
|
||||
(`skills:tdd`). Updates land when `.claude-plugin/plugin.json`'s `version`
|
||||
moves — CI bumps it on every release.
|
||||
|
||||
### Crush, Pi, OpenCode — `install.sh`
|
||||
|
||||
```bash
|
||||
curl -fsSL https://gitea.d-ma.be/mathias/skills/raw/branch/main/install.sh | bash
|
||||
curl -fsSL https://git.d-ma.be/mathias/skills/raw/branch/main/install.sh | bash
|
||||
```
|
||||
|
||||
Both forms are idempotent and re-runnable. On every run they:
|
||||
Idempotent. It clones or fast-forwards the checkout, then populates one
|
||||
**managed directory** and gives each harness a single link to it:
|
||||
|
||||
1. `git clone` (or `git pull`) this repo into `~/.local/share/skills/` —
|
||||
the **canonical local checkout** on every host.
|
||||
2. Wire per-skill symlinks into the harnesses found on the host (see
|
||||
[Wired harnesses](#wired-harnesses)).
|
||||
| Path | Target |
|
||||
|---|---|
|
||||
| `~/.agents/skills/` | a real directory, one symlink per skill (Pi reads this path directly) |
|
||||
| `~/.agents/skills/<skill>` | `$SKILLS_CHECKOUT_DIR/skills/<skill>`, or another configured source |
|
||||
| `~/.config/crush/skills` | `~/.agents/skills` |
|
||||
| `~/.config/opencode/skills` | `~/.agents/skills` |
|
||||
|
||||
Re-run after `git pull` upstream to pick up new skills or version
|
||||
changes. CI tags every change as a `vX.Y.Z` release (see
|
||||
[Versioning](#versioning)).
|
||||
Total links are N + one per harness — not N x harnesses, which is what #23 was
|
||||
actually about.
|
||||
|
||||
## Wired harnesses
|
||||
### More than one source of skills
|
||||
|
||||
| Harness | Target path | Notes |
|
||||
|---|---|---|
|
||||
| **Claude Code (global)** | `~/.claude/skills/<name>` | Visible in every Claude Code session on the host. |
|
||||
| **Claude Code (per-repo)** | `<repo>/.claude/skills/<name>` | Created when `install` is invoked inside a git repo (not the skills repo itself). Gitignored globally via `**/.claude/skills/`. |
|
||||
| **Crush** | `~/.config/crush/skills/<name>` | Charmbracelet Crush — successor to `opencode-ai/opencode` (archived). |
|
||||
| **Antigravity** | `~/.gemini/antigravity/skills/<name>` | Google Antigravity (VS Code extension). Our `SKILL.md` frontmatter (`name` + `description`) is already in the format Antigravity expects, so symlinks suffice — no manifest translation. |
|
||||
`~/.agents/skills` used to be a single link straight at this checkout. That
|
||||
encoded an assumption nobody had stated — that this checkout is the only source
|
||||
of skills on the host — and on flamingo the only way to install this library
|
||||
was to displace Anthropic's official set, which lived in Crush's directory.
|
||||
Real capability loss dressed up as a tidy-up (#27).
|
||||
|
||||
### Not wired (and why)
|
||||
Point `SKILLS_EXTRA_SOURCES` at any number of extra directories, colon
|
||||
separated, each holding `<skill>/SKILL.md`:
|
||||
|
||||
- **opencode** (`opencode-ai/opencode`): archive notice; succeeded by Crush.
|
||||
Its only "skill"-like surface — Custom Commands at `~/.config/opencode/commands/` —
|
||||
is for user-facing prompt templates, not system-level instructions.
|
||||
Misaligned with how we use skills. Skipped.
|
||||
- **gitea-resident agents** (cobalt-dingo, agentsquad): they consume
|
||||
skills via their containing project's `.claude/skills` directory
|
||||
(populated by the per-repo wirer when run from the host), or via the
|
||||
brain MCP. No special target needed.
|
||||
```
|
||||
SKILLS_EXTRA_SOURCES=~/.config/crush/skills.anthropic bash install.sh
|
||||
```
|
||||
|
||||
- The checkout is always first and always wins a name collision — but the
|
||||
collision is **logged**, never resolved in silence. Quietly picking one is
|
||||
how stale content wins.
|
||||
- Removing a skill from a source removes its link on the next run.
|
||||
- Anything in the managed directory that is not a symlink is reported and left
|
||||
alone. install.sh does not delete content it did not create.
|
||||
- The source list is recorded at `~/.agents/skills-sources` so `bin/doctor`
|
||||
can tell a link into a known source from a link into a forgotten one.
|
||||
|
||||
### Where the checkout must live
|
||||
|
||||
`SKILLS_CHECKOUT_DIR` defaults to `~/.local/share/skills`, and that default is
|
||||
load-bearing: it is **host-local, outside any synced or shared directory**.
|
||||
|
||||
On this fleet `~/dev` is an iCloud folder shared by flamingo and iguana, and it
|
||||
spans two path roots — `/Users/mathias` on the Macs, `/home/mathias` on koala.
|
||||
A checkout there is a git working tree with two concurrent writers, and any
|
||||
absolute symlink stored there is broken on one side by construction. That is
|
||||
what produced 243 dangling links across 12 repos (#23). Do not "fix" the
|
||||
default to point into `~/dev`.
|
||||
|
||||
### Per-host env-var overrides
|
||||
|
||||
Each target path can be overridden by setting the matching env var before
|
||||
running `install.sh`:
|
||||
|
||||
| Env var | Default |
|
||||
|---|---|
|
||||
| `SKILLS_REPO_URL` | `https://gitea.d-ma.be/mathias/skills.git` |
|
||||
| `SKILLS_REF` | `main` (set to e.g. `v0.1.0` to pin a release) |
|
||||
| `SKILLS_REPO_URL` | `https://git.d-ma.be/mathias/skills.git` |
|
||||
| `SKILLS_REF` | `main` (set to e.g. `v0.4.0` to pin a release) |
|
||||
| `SKILLS_CHECKOUT_DIR` | `$HOME/.local/share/skills` |
|
||||
| `CLAUDE_SKILLS_DIR` | `$HOME/.claude/skills` |
|
||||
| `SKILLS_SKIP_FETCH` | unset (`1` wires an existing checkout without touching HEAD) |
|
||||
| `AGENTS_SKILLS_DIR` | `$HOME/.agents/skills` |
|
||||
| `CRUSH_SKILLS_DIR` | `$HOME/.config/crush/skills` |
|
||||
| `ANTIGRAVITY_SKILLS_DIR` | `$HOME/.gemini/antigravity/skills` |
|
||||
| `OPENCODE_SKILLS_DIR` | `$HOME/.config/opencode/skills` |
|
||||
| `ANTIGRAVITY_SKILLS_JSON` | `$HOME/.gemini/config/skills.json` (registers `AGENTS_SKILLS_DIR` as a path entry; needs `jq`) |
|
||||
| `SKILLS_EXTRA_SOURCES` | unset (colon-separated extra source directories) |
|
||||
|
||||
The Mistral Vibe target was removed — unused. Antigravity's was removed for
|
||||
the same reason and re-added once it came back into use.
|
||||
|
||||
## Checking a host
|
||||
|
||||
```bash
|
||||
task doctor # or bin/doctor
|
||||
```
|
||||
|
||||
Reports dangling links, links into a source nobody configured, skills in the
|
||||
checkout with no link, stray entries, leftover per-skill Claude symlinks, and a
|
||||
Claude Code plugin sitting on an older generation than the host already has.
|
||||
Non-zero exit on drift. It also runs at session start via the plugin, so a
|
||||
drifting host says so rather than waiting to be discovered.
|
||||
|
||||
All of that compares copies already on the machine — deliberately, since it
|
||||
runs in a session hook where latency shows. That leaves one case invisible: a
|
||||
host where the checkout, the marketplace clone and the installed plugin all
|
||||
agree, and all three are a release behind origin.
|
||||
|
||||
```bash
|
||||
task doctor -- --online # or bin/doctor --online
|
||||
```
|
||||
|
||||
One `git ls-remote` against origin, opt-in. Belongs in a scheduled per-host job,
|
||||
not the session hook. An unreachable remote is reported as its own fault rather
|
||||
than as staleness — "I could not check" and "you are behind" are different
|
||||
answers and only one of them is about the host.
|
||||
|
||||
## Versioning
|
||||
|
||||
@@ -91,13 +147,48 @@ before `task skills:install`; default is `main` for always-current.
|
||||
|
||||
## Contributing a skill
|
||||
|
||||
1. Add a directory `<short-kebab-name>/`.
|
||||
2. Create `<short-kebab-name>/SKILL.md` — start with one-paragraph
|
||||
purpose, then triggers ("use when …"), then mechanics.
|
||||
3. Add a row to `SKILLS_INDEX.md` (description + use-when).
|
||||
4. Commit directly to `main`. Conventional-commit prefix
|
||||
1. Add a directory `skills/<short-kebab-name>/`.
|
||||
2. Create `skills/<short-kebab-name>/SKILL.md` with this frontmatter — all four
|
||||
keys are gated by `task check`, and the index table is generated from the
|
||||
last three:
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: <short-kebab-name>
|
||||
surfaces: [claude-code, library] # any of claude-code | library | chat
|
||||
summary: "<one line for the index table>"
|
||||
use_when: "<the trigger, for the index table>"
|
||||
description: <the paragraph the model selects on>
|
||||
---
|
||||
```
|
||||
|
||||
Then: one-paragraph purpose, triggers ("use when …"), mechanics.
|
||||
3. Run `task index` and commit the regenerated `SKILLS_INDEX.md`. Do **not**
|
||||
hand-edit the table — `task check` regenerates it and fails on a diff.
|
||||
4. Pressure-test it before shipping: run the scenario against a subagent that
|
||||
does *not* have the skill, write the skill against what that run actually
|
||||
did, then re-run with it. See `superpowers-writing-skills` and #19.
|
||||
5. Commit directly to `main`. Conventional-commit prefix
|
||||
(`feat:` / `fix:` / `docs:`). Add `Bump-Type: minor` footer when
|
||||
adding a new skill or expanding scope; default patch covers edits.
|
||||
|
||||
This repo is markdown-only and public — never include secrets, client
|
||||
names, or anything under NDA in a skill.
|
||||
|
||||
## Mode 2 routing candidates
|
||||
|
||||
These notes used to sit in each SKILL.md as a `## Mode 2 Routing Note` section.
|
||||
They changed nothing about how the skill is invoked — several said so outright —
|
||||
and cost context on every load, so they live here instead. Nothing in the repo
|
||||
depends on this table; it is a record of which skills looked mechanical enough
|
||||
to route to a local model, should a routing layer ever exist.
|
||||
|
||||
| Skill | Note |
|
||||
|---|---|
|
||||
| `cad-babysit` | Phases 2-4 (reading comments/logs, classifying fault vs outcome) are judgment-heavy and should stay Mode 1. Phase 1 (running `cad stuck` and grouping its output) is mechanical and a Mode 2 routing candidate once Plan 6 ships the routing pod. |
|
||||
| `code-review` | This skill is invoked identically in Mode 1 (cloud Claude) and Mode 2 (client-local with supervisor routing). The routing layer (Plan 6) does not exist yet; treat this skill as Mode 1 only for now. Findings format and severity classification are unchanged across modes. |
|
||||
| `debug` | This skill produces high-volume mechanical output (hypothesis enumeration) and is a candidate for Mode 2 routing to a local model in the future. Until Plan 6 ships the routing pod, treat as Mode 1 only. The hypothesis format and discipline are identical regardless of which model generates them. |
|
||||
| `feature-spec` | Spec writing requires interpretation of intent and tradeoff reasoning — work where Claude generally outperforms a 9-13B local model. This skill is intentionally **not** a Mode 2 routing candidate. In Mode 2, the routing layer should leave `feature-spec` calls on Claude. |
|
||||
| `session-retrospective` | Reading long session logs and pulling themes is high-volume, mechanical pattern-recognition work — a strong Mode 2 routing candidate. Until Plan 6 ships the routing pod, treat as Mode 1 only. |
|
||||
| `tdd` | This skill is invoked identically whether the agent is running in Mode 1 (cloud Claude, no routing) or Mode 2 (client-local, supervisor routing layer). The routing pod (Plan 6) does not exist yet; until it does, treat this skill as Mode 1 only. The discipline does not change between modes — only the model behind the call. |
|
||||
| `trainer` | Trainer is the same shape as `session-retrospective` — long-context reading, mechanical filtering — and is a Mode 2 routing candidate. Until Plan 6, treat as Mode 1 only. |
|
||||
|
||||
+118
-39
@@ -2,42 +2,115 @@
|
||||
|
||||
This index lists all available engineering skills. Load the full SKILL.md on demand.
|
||||
|
||||
| Skill | Description | Use when |
|
||||
|-------|-------------|----------|
|
||||
| `tdd` | Test-Driven Development enforcement | Starting any new feature or fixing a bug |
|
||||
| `clean-code` | Clean code principles with Go adaptation | Code review, refactoring, new code |
|
||||
| `solid` | SOLID principles with Go examples | Design review, architecture decisions |
|
||||
| `code-review` | Code smell detection + Go-specific checklist | Pre-merge review |
|
||||
| `refactoring` | Systematic refactoring methodology (Fowler) | When improving existing code |
|
||||
| `test-design` | Dave Farley test design scoring (Farley Index) | Reviewing or writing tests |
|
||||
| `cognitive-load` | Cognitive complexity analysis (CLI score) | Identifying hotspots, before refactoring |
|
||||
| `problem-analysis` | Deep problem understanding before coding | Starting any non-trivial task |
|
||||
| `user-stories` | Elephant Carpaccio story slicing | Breaking down features |
|
||||
| `atdd` | Acceptance Test-Driven Development workflow | Feature development with acceptance criteria |
|
||||
| `spec-driven-dev` | Spec-driven development for PMs | Writing specs and requirements |
|
||||
| `planning` | Planning and task breakdown | Sprint planning, task decomposition |
|
||||
| `gitea-ci` | Gitea CI/CD pipeline with act_runner, buildah, k3s, GitHub mirror | Setting up or debugging CI on this infra |
|
||||
| `debug` | Hypothesis-first debugging discipline | Any test failure or bug whose cause is not immediately obvious |
|
||||
| `feature-spec` | Implementation-level feature spec (tighter than spec-driven-dev) | Scoping one feature inside an already-specced project |
|
||||
| `playwright` | Playwright E2E testing — setup, HTMX patterns, SSE streams, CI wiring | Adding browser tests to any project with a web UI |
|
||||
| `session-retrospective` | Surface non-obvious learnings from a session log | After a coding session ends, before context is lost |
|
||||
| `trainer` | Two-phase brain curation (score candidates, write past quality gate) | Periodic brain pruning and curation |
|
||||
| `grill-me` | Structured plan interrogation — Quick Poke, Full Grill, Pre-mortem | Stress-testing a plan before committing; end of Diamond 1; before promoting to pre-prod |
|
||||
The table is **generated** from each skill's frontmatter (`summary`, `use_when`,
|
||||
`surfaces`) by `task index`, and `task check` fails if it is out of date. Edit
|
||||
the SKILL.md, not the table.
|
||||
|
||||
<!-- BEGIN skills-table -->
|
||||
| Skill | Description | Use when | Surfaces |
|
||||
|-------|-------------|----------|----------|
|
||||
| `adr` | Architecture Decision Records — house format, and how to record a decision you cannot make yet | Recording an architectural decision; revisiting one; or deciding between options where the right answer genuinely is not knowable yet | claude-code, library |
|
||||
| `atdd` | Acceptance Test-Driven Development workflow | Feature development with acceptance criteria | claude-code, library |
|
||||
| `cad-babysit` | Focused human-in-the-loop session working CAD's stuck queue (read-only) | Picking up whatever `cad stuck` flags, with a human present | claude-code, library |
|
||||
| `clean-code` | Clean code principles with Go adaptation | Code review, refactoring, new code | claude-code, library |
|
||||
| `code-review` | Code smell detection + Go-specific checklist | Pre-merge review | claude-code, library |
|
||||
| `cognitive-load` | Cognitive complexity analysis (CLI score) | Identifying hotspots, before refactoring | claude-code, library |
|
||||
| `debug` | Hypothesis-first debugging discipline | Any test failure or bug whose cause is not immediately obvious — or a bug report with no failure text, which this skill refuses rather than guesses at | claude-code, library |
|
||||
| `discovery-framing` | Problem-before-solution discovery/framing method | Framing/validating a problem before any solution; opportunity sizing | claude-code, library |
|
||||
| `dream` | Reflective consolidation pass over an agent's memory directory | Pruning/merging memory files, rebuilding a memory index | claude-code, library, chat |
|
||||
| `experiment-spec` | Rigorous experiment spec — falsifiable hypothesis, quantitative acceptance, null-result protocol | Scoping a research/ML phase instead of a feature | claude-code, library |
|
||||
| `feature-spec` | Implementation-level feature spec (tighter than spec-driven-dev) | Scoping one feature inside an already-specced project | claude-code, library |
|
||||
| `gitea-ci` | Gitea CI/CD pipeline with act_runner, buildah, k3s, GitHub mirror | Setting up or debugging CI on this infra | claude-code, library |
|
||||
| `grill-me` | Structured plan interrogation — Quick Poke, Full Grill, Pre-mortem | Stress-testing a plan before committing; end of Diamond 1; before promoting to pre-prod | claude-code, library, chat |
|
||||
| `lineage` | Backward decision archaeology — was this tried before, and does the reason it failed still hold | Before proposing something that feels new; when an idea keeps resurfacing; when you inherit code whose reason is gone | claude-code, library |
|
||||
| `own-the-task` | Delegation ownership — Intake → Brief → Plan → Execute | A task is handed over open-ended; \"take this off my plate\"; before a plan exists | claude-code, library, chat |
|
||||
| `planning` | Planning and task breakdown | Sprint planning, task decomposition | claude-code, library |
|
||||
| `playwright` | Playwright E2E testing — setup, HTMX patterns, SSE streams, CI wiring | Adding browser tests to any project with a web UI | claude-code, library |
|
||||
| `problem-analysis` | Deep problem understanding before coding | Starting any non-trivial task | claude-code, library |
|
||||
| `refactoring` | Systematic refactoring methodology (Fowler) | When improving existing code | claude-code, library |
|
||||
| `regulatory-risk-assessment` | Structured risk register for regulated-industry features | Filing a CAD issue (needs Risk: level); features touching payments, auth, external APIs, user data | claude-code, library |
|
||||
| `secret-hygiene` | Stop credentials rendering into the session transcript; safe rotation chain when one leaks | Before any kubectl/SOPS/token command; after a confirmed leak | claude-code, library |
|
||||
| `session-retrospective` | Surface non-obvious learnings from a session log | After a coding session ends, before context is lost | claude-code, library |
|
||||
| `solid` | SOLID principles with Go examples | Design review, architecture decisions | claude-code, library |
|
||||
| `spec-driven-dev` | Spec-driven development for PMs | Writing specs and requirements | claude-code, library |
|
||||
| `stage-gate-review` | Stage-gate product governance (go/no-go council) | Preparing a Product Council ask; building a go/no-go checklist; gate review | claude-code, library |
|
||||
| `superpowers-brainstorming` | Structured divergent brainstorming | Generating or expanding a set of ideas | claude-code, library |
|
||||
| `superpowers-dispatching-parallel-agents` | Fan work out across parallel subagents | Decomposing work for concurrent agents | claude-code, library |
|
||||
| `superpowers-executing-plans` | Executing a written plan step by step | Running an approved plan to completion | claude-code, library |
|
||||
| `superpowers-finishing-a-development-branch` | Cleanly finishing/landing a dev branch | Wrapping a branch → merge/PR | claude-code, library |
|
||||
| `superpowers-receiving-code-review` | Acting on received review feedback | Responding to review comments | claude-code, library |
|
||||
| `superpowers-requesting-code-review` | Requesting a code review well | Asking another agent/human to review | claude-code, library |
|
||||
| `superpowers-subagent-driven-development` | Subagent-driven development workflow | Building via orchestrated subagents | claude-code, library |
|
||||
| `superpowers-using-git-worktrees` | Isolating work with git worktrees | Parallel/isolated work in a worktree | claude-code, library |
|
||||
| `superpowers-using-superpowers` | Meta: orienting in the superpowers set | Learning how to use the superpowers skills | claude-code, library |
|
||||
| `superpowers-verification-before-completion` | Verify behavior before claiming done | Before marking any task complete | claude-code, library |
|
||||
| `superpowers-writing-plans` | Writing implementation plans | Planning substantial work before coding | claude-code, library |
|
||||
| `superpowers-writing-skills` | Authoring new SKILL.md skills | Creating a new reusable skill | claude-code, library |
|
||||
| `tdd` | Test-Driven Development enforcement | Starting any new feature or fixing a bug | claude-code, library |
|
||||
| `telos-load` | Load TELOS intention substrate at session start | Starting any koala session; before architectural decisions; CAD pipeline entry | claude-code, library |
|
||||
| `test-design` | Dave Farley test design scoring (Farley Index) | Reviewing or writing tests | claude-code, library |
|
||||
| `traceability` | Forward trace — requirement to decision to commit to verification to release, and what cannot be checked | Proving why a change exists; auditing a claim; before an attestation or a compliance ask | claude-code, library |
|
||||
| `trainer` | Two-phase brain curation (score candidates, write past quality gate) | Periodic brain pruning and curation | claude-code, library |
|
||||
| `user-stories` | Elephant Carpaccio story slicing | Breaking down features | claude-code, library |
|
||||
| `web-shot` | Screenshot a running web UI via a koala k3s Playwright job | Visual verification of a running UI when no local browser exists | claude-code, library |
|
||||
<!-- END skills-table -->
|
||||
|
||||
## Wiring into tools
|
||||
|
||||
The canonical home is `~/dev/.skills/`. Per-tool surfacing is handled by
|
||||
`~/dev/.context/wire-skills.sh`:
|
||||
This repo is the canonical home, and it is delivered two different ways.
|
||||
|
||||
- **Claude Code** — each git repo under `~/dev/` gets a `<repo>/.claude/skills`
|
||||
symlink pointing at `~/dev/.skills/`. The symlink is excluded by
|
||||
`**/.claude/skills` in `~/.config/git/ignore`, so it never lands in commits.
|
||||
- **Crush** — per-skill symlinks under `~/.config/crush/skills/<name>`, added
|
||||
alongside existing entries (e.g., `mstack/*`). Skills already present as
|
||||
real directories or non-canonical symlinks are preserved.
|
||||
### Claude Code — install the plugin
|
||||
|
||||
Run `bash ~/dev/.context/wire-skills.sh --dry-run` to preview, then drop the
|
||||
flag to apply. The script is idempotent.
|
||||
This repo hosts a marketplace containing exactly one plugin: itself. The plugin
|
||||
carries the skills **plus** the `secret-guard` and `pre-task-ritual` hooks and
|
||||
the brain/gitea/infra MCP servers — none of which a symlink can deliver.
|
||||
|
||||
```
|
||||
/plugin marketplace add https://git.d-ma.be/mathias/skills.git
|
||||
/plugin install skills@mathias
|
||||
```
|
||||
|
||||
Skills are namespaced: `tdd` becomes `skills:tdd`. Updates arrive when
|
||||
`.claude-plugin/plugin.json`'s `version` moves, which CI does on every release.
|
||||
Remove any leftover `~/.claude/skills/<name>` symlinks from the pre-plugin era —
|
||||
plugin skills do **not** override same-named user skills, so leftovers make
|
||||
everything load twice.
|
||||
|
||||
### Crush, Pi, OpenCode — run `install.sh`
|
||||
|
||||
These have no plugin system, so they get symlinks — but through one managed
|
||||
directory, never one link per skill per harness:
|
||||
|
||||
```
|
||||
~/.agents/skills/ (real directory; Pi reads it directly)
|
||||
~/.agents/skills/tdd -> $SKILLS_CHECKOUT_DIR/skills/tdd
|
||||
~/.agents/skills/xlsx -> $SKILLS_EXTRA_SOURCES entry
|
||||
~/.config/crush/skills -> ~/.agents/skills
|
||||
~/.config/opencode/skills -> ~/.agents/skills
|
||||
```
|
||||
|
||||
Total links are N + one per harness. `SKILLS_EXTRA_SOURCES` (colon-separated
|
||||
directories) lets a second library — Anthropic's official set, for instance —
|
||||
live alongside this one instead of being displaced by it; name collisions are
|
||||
logged rather than silently resolved, and the checkout wins (#27).
|
||||
|
||||
```
|
||||
curl -fsSL https://git.d-ma.be/mathias/skills/raw/branch/main/install.sh | bash
|
||||
```
|
||||
|
||||
`SKILLS_CHECKOUT_DIR` defaults to `~/.local/share/skills` and **must stay
|
||||
outside `~/dev`**. On this fleet `~/dev` is an iCloud folder shared by both
|
||||
Macs and spans two path roots (`/Users/mathias` vs `/home/mathias` on koala);
|
||||
a checkout there means a git working tree with two concurrent writers, and any
|
||||
absolute link stored there is broken on one side by construction. See #23.
|
||||
|
||||
### Check a host
|
||||
|
||||
`task doctor` (or `bin/doctor`) reports dangling links, links into a source
|
||||
nobody configured, skills in the checkout with no link, stray entries, leftover
|
||||
Claude symlinks, and a Claude Code plugin sitting on an older generation than
|
||||
the host already has. It also runs automatically at session start via the
|
||||
plugin, so drift announces itself instead of waiting to be found.
|
||||
|
||||
## Skill Relationships
|
||||
|
||||
@@ -48,14 +121,16 @@ problem-analysis
|
||||
│
|
||||
├── spec-driven-dev (PM-kickoff lifecycle)
|
||||
│ │
|
||||
│ └── feature-spec (per-feature, mid-implementation)
|
||||
│ │
|
||||
│ └── planning
|
||||
│ │
|
||||
│ └── atdd ──→ tdd (foundation)
|
||||
│ ├──→ debug (when tests fail)
|
||||
│ ├──→ clean-code (REFACTOR phase)
|
||||
│ └──→ test-design (review)
|
||||
│ ├── feature-spec (per-feature, mid-implementation)
|
||||
│ │ │
|
||||
│ │ └── planning
|
||||
│ │ │
|
||||
│ │ └── atdd ──→ tdd (foundation)
|
||||
│ │ ├──→ debug (when tests fail)
|
||||
│ │ ├──→ clean-code (REFACTOR phase)
|
||||
│ │ └──→ test-design (review)
|
||||
│ │
|
||||
│ └── experiment-spec (research/ML phase, instead of feature-spec)
|
||||
│
|
||||
└── planning
|
||||
|
||||
@@ -66,6 +141,7 @@ code-review ──→ refactoring ──→ clean-code
|
||||
session-retrospective ──→ trainer ──→ brain (via brain_write)
|
||||
|
||||
(planning & convergence)
|
||||
own-the-task ──→ grill-me (intent first, then stress-test the plan)
|
||||
grill-me ──→ planning (after plan is sharpened)
|
||||
──→ spec-driven-dev (after hypothesis is validated)
|
||||
```
|
||||
@@ -89,3 +165,6 @@ grill-me ──→ planning (after plan is sharpened)
|
||||
| "Grill me / stress-test this / is this ready?" | `grill-me` |
|
||||
| "End of Diamond 1 — should we build this?" | `grill-me` (Full Grill) |
|
||||
| "About to promote to pre-prod" | `grill-me` (Pre-mortem) |
|
||||
| "Take this off my plate / own this / act as my AI employee" | `own-the-task` |
|
||||
| "What are the risks?" / "compliance gate" / "risk register" | `regulatory-risk-assessment` |
|
||||
| "Start of session" / "load TELOS" / "what are we optimizing toward?" | `telos-load` |
|
||||
|
||||
+141
-133
@@ -2,21 +2,19 @@ version: '3'
|
||||
|
||||
# Skills library Taskfile.
|
||||
#
|
||||
# Primary entry point for project + host installation. Consumer projects
|
||||
# do NOT depend on this file directly — they ship their own
|
||||
# `skills:install` target that delegates here via `install.sh`. This
|
||||
# Taskfile is invoked by maintainers of the skills repo itself, plus by
|
||||
# install.sh during the post-clone wire step.
|
||||
# This repo is two things at once:
|
||||
# 1. A Claude Code PLUGIN (skills + hooks + MCP servers), distributed through
|
||||
# the marketplace this same repo hosts at .claude-plugin/marketplace.json.
|
||||
# 2. A plain skills library for harnesses with no plugin system — Crush, Pi,
|
||||
# OpenCode — wired by install.sh as ONE directory symlink per harness.
|
||||
#
|
||||
# The wiring loops that used to live here were five near-identical copies that
|
||||
# drifted; install.sh owns wiring now and this file delegates to it.
|
||||
|
||||
vars:
|
||||
REPO_URL: 'https://gitea.d-ma.be/mathias/skills.git'
|
||||
CHECKOUT_DIR: '{{.HOME}}/.local/share/skills'
|
||||
CLAUDE_GLOBAL_DIR: '{{.HOME}}/.claude/skills'
|
||||
CRUSH_DIR: '{{.HOME}}/.config/crush/skills'
|
||||
ANTIGRAVITY_DIR: '{{.HOME}}/.gemini/antigravity/skills'
|
||||
# Anything at the repo root that is NOT a skill directory. Both
|
||||
# Taskfile + install.sh share this exclusion regex.
|
||||
NON_SKILL_ENTRIES: '^(Taskfile.yml|install.sh|README.md|SKILLS_INDEX.md|.gitea|.git$)$'
|
||||
REPO_URL: 'https://git.d-ma.be/mathias/skills.git'
|
||||
SKILLS_DIR: '{{.TASKFILE_DIR}}/skills'
|
||||
PLUGIN_MANIFEST: '{{.TASKFILE_DIR}}/.claude-plugin/plugin.json'
|
||||
|
||||
tasks:
|
||||
|
||||
@@ -27,113 +25,146 @@ tasks:
|
||||
list:
|
||||
desc: 'Print every skill in this repo'
|
||||
cmds:
|
||||
- 'ls -1 {{.TASKFILE_DIR}} | grep -Ev "^(Taskfile.yml|install.sh|README.md|SKILLS_INDEX.md|.gitea|.git$)$" || true'
|
||||
- 'ls -1 {{.SKILLS_DIR}}'
|
||||
silent: true
|
||||
|
||||
install:
|
||||
desc: 'Wire skills into every supported harness (Claude Code, Crush, Antigravity).'
|
||||
desc: 'Wire THIS checkout into Crush / Pi / OpenCode. Claude Code uses the plugin instead.'
|
||||
cmds:
|
||||
- task: install:claude:global
|
||||
- task: install:claude:repo
|
||||
- task: install:crush
|
||||
- task: install:antigravity
|
||||
|
||||
install:claude:global:
|
||||
desc: 'Per-skill symlinks under ~/.claude/skills/<name> — visible in every Claude Code project on this host.'
|
||||
cmds:
|
||||
- mkdir -p {{.CLAUDE_GLOBAL_DIR}}
|
||||
- |
|
||||
for skill in $(ls -1 "{{.TASKFILE_DIR}}" | grep -Ev "{{.NON_SKILL_ENTRIES}}"); do
|
||||
target="{{.TASKFILE_DIR}}/${skill}"
|
||||
link="{{.CLAUDE_GLOBAL_DIR}}/${skill}"
|
||||
if [ -L "$link" ] || [ -e "$link" ]; then
|
||||
current=$(readlink "$link" 2>/dev/null || true)
|
||||
if [ "$current" = "$target" ]; then
|
||||
continue
|
||||
fi
|
||||
rm -rf "$link"
|
||||
fi
|
||||
ln -s "$target" "$link"
|
||||
echo "linked $link → $target"
|
||||
done
|
||||
|
||||
install:claude:repo:
|
||||
desc: 'Per-skill symlinks under $(pwd)/.claude/skills/<name> when invoked inside a git repo.'
|
||||
cmds:
|
||||
- |
|
||||
if ! git rev-parse --show-toplevel >/dev/null 2>&1; then
|
||||
echo "not in a git repo — skipping per-repo wire"; exit 0
|
||||
fi
|
||||
repo=$(git rev-parse --show-toplevel)
|
||||
if [ "$repo" = "{{.TASKFILE_DIR}}" ]; then
|
||||
echo "running from skills repo itself — skipping per-repo wire"; exit 0
|
||||
fi
|
||||
target_dir="$repo/.claude/skills"
|
||||
mkdir -p "$target_dir"
|
||||
for skill in $(ls -1 "{{.TASKFILE_DIR}}" | grep -Ev "{{.NON_SKILL_ENTRIES}}"); do
|
||||
target="{{.TASKFILE_DIR}}/${skill}"
|
||||
link="${target_dir}/${skill}"
|
||||
if [ -L "$link" ] || [ -e "$link" ]; then
|
||||
current=$(readlink "$link" 2>/dev/null || true)
|
||||
if [ "$current" = "$target" ]; then
|
||||
continue
|
||||
fi
|
||||
rm -rf "$link"
|
||||
fi
|
||||
ln -s "$target" "$link"
|
||||
echo "linked $link → $target"
|
||||
done
|
||||
|
||||
install:crush:
|
||||
desc: 'Per-skill symlinks under ~/.config/crush/skills/<name> — visible in every Crush session on this host.'
|
||||
cmds:
|
||||
- mkdir -p {{.CRUSH_DIR}}
|
||||
- |
|
||||
for skill in $(ls -1 "{{.TASKFILE_DIR}}" | grep -Ev "{{.NON_SKILL_ENTRIES}}"); do
|
||||
target="{{.TASKFILE_DIR}}/${skill}"
|
||||
link="{{.CRUSH_DIR}}/${skill}"
|
||||
if [ -L "$link" ] || [ -e "$link" ]; then
|
||||
current=$(readlink "$link" 2>/dev/null || true)
|
||||
if [ "$current" = "$target" ]; then
|
||||
continue
|
||||
fi
|
||||
rm -rf "$link"
|
||||
fi
|
||||
ln -s "$target" "$link"
|
||||
echo "linked $link → $target"
|
||||
done
|
||||
|
||||
install:antigravity:
|
||||
desc: 'Per-skill symlinks under ~/.gemini/antigravity/skills/<name>. SKILL.md frontmatter (name + description) is already antigravity-compatible.'
|
||||
cmds:
|
||||
- mkdir -p {{.ANTIGRAVITY_DIR}}
|
||||
- |
|
||||
for skill in $(ls -1 "{{.TASKFILE_DIR}}" | grep -Ev "{{.NON_SKILL_ENTRIES}}"); do
|
||||
target="{{.TASKFILE_DIR}}/${skill}"
|
||||
link="{{.ANTIGRAVITY_DIR}}/${skill}"
|
||||
if [ -L "$link" ] || [ -e "$link" ]; then
|
||||
current=$(readlink "$link" 2>/dev/null || true)
|
||||
if [ "$current" = "$target" ]; then
|
||||
continue
|
||||
fi
|
||||
rm -rf "$link"
|
||||
fi
|
||||
ln -s "$target" "$link"
|
||||
echo "linked $link → $target"
|
||||
done
|
||||
- SKILLS_SKIP_FETCH=1 SKILLS_CHECKOUT_DIR='{{.TASKFILE_DIR}}' bash '{{.TASKFILE_DIR}}/install.sh'
|
||||
|
||||
update:
|
||||
desc: 'git pull the canonical checkout then re-run install.'
|
||||
desc: 'Fast-forward this checkout and re-wire.'
|
||||
cmds:
|
||||
- |
|
||||
if [ ! -d "{{.CHECKOUT_DIR}}/.git" ]; then
|
||||
echo "no canonical checkout at {{.CHECKOUT_DIR}} — run install.sh first"; exit 1
|
||||
fi
|
||||
git -C "{{.CHECKOUT_DIR}}" pull --ff-only
|
||||
- git -C '{{.TASKFILE_DIR}}' pull --ff-only
|
||||
- task: install
|
||||
|
||||
doctor:
|
||||
desc: 'Report drift across every harness on this host. Non-zero exit means something is wrong.'
|
||||
cmds:
|
||||
- '{{.TASKFILE_DIR}}/bin/doctor'
|
||||
|
||||
validate:
|
||||
desc: 'Validate the plugin + marketplace manifests with the Claude Code CLI.'
|
||||
cmds:
|
||||
- claude plugin validate '{{.TASKFILE_DIR}}'
|
||||
|
||||
test:
|
||||
desc: 'Run the shell test suite (hooks + doctor).'
|
||||
cmds:
|
||||
- |
|
||||
fail=0
|
||||
for t in '{{.TASKFILE_DIR}}'/tests/*_test.sh; do
|
||||
[ -f "$t" ] || continue
|
||||
echo "--- $(basename "$t")"
|
||||
sh "$t" || fail=1
|
||||
done
|
||||
exit $fail
|
||||
|
||||
index:
|
||||
desc: 'Regenerate SKILLS_INDEX.md''s table from skill frontmatter.'
|
||||
cmds:
|
||||
- "'{{.TASKFILE_DIR}}/bin/generate-index' '{{.TASKFILE_DIR}}'"
|
||||
|
||||
check:
|
||||
desc: 'Structure gate — layout, frontmatter, surfaces, generated index, manifest/tag parity. Runs in CI.'
|
||||
cmds:
|
||||
- |
|
||||
fail=0
|
||||
|
||||
# 1. No stray entries at the repo root. A loose foo.md where
|
||||
# skills/foo/SKILL.md was meant loads in NO harness and errors in
|
||||
# none either — it just silently does nothing. (See #23.)
|
||||
for entry in "{{.TASKFILE_DIR}}"/*; do
|
||||
base=$(basename "$entry")
|
||||
case "$base" in
|
||||
install.sh|Taskfile.yml|README.md|SKILLS_INDEX.md|skills|hooks|bin|tests) continue ;;
|
||||
esac
|
||||
echo "ERROR: unexpected entry at repo root: $base" >&2
|
||||
fail=1
|
||||
done
|
||||
|
||||
# 2. Every skill is a directory with a SKILL.md carrying name + description.
|
||||
count=0
|
||||
for dir in "{{.SKILLS_DIR}}"/*; do
|
||||
name=$(basename "$dir")
|
||||
if [ ! -d "$dir" ]; then
|
||||
echo "ERROR: skills/$name is not a directory" >&2; fail=1; continue
|
||||
fi
|
||||
if [ ! -f "$dir/SKILL.md" ]; then
|
||||
echo "ERROR: skills/$name missing SKILL.md" >&2; fail=1; continue
|
||||
fi
|
||||
head -n 20 "$dir/SKILL.md" | grep -q '^name:' || { echo "ERROR: skills/$name SKILL.md has no 'name:' frontmatter" >&2; fail=1; }
|
||||
head -n 20 "$dir/SKILL.md" | grep -q '^description:' || { echo "ERROR: skills/$name SKILL.md has no 'description:' frontmatter" >&2; fail=1; }
|
||||
count=$((count + 1))
|
||||
done
|
||||
|
||||
# 3. SKILLS_INDEX.md's table is generated from frontmatter, so the
|
||||
# assertion is that regenerating it changes nothing. This replaces
|
||||
# bin/check-index: a generated table cannot drift in either
|
||||
# direction, so there is no separate rule left to check.
|
||||
sh '{{.TASKFILE_DIR}}/bin/generate-index' --check '{{.TASKFILE_DIR}}' || fail=1
|
||||
|
||||
# 4. Every skill says which surfaces it ships to, and names only
|
||||
# surfaces that exist — a wrong value silently drops a skill from a
|
||||
# harness instead of erroring.
|
||||
sh '{{.TASKFILE_DIR}}/bin/check-surfaces' '{{.TASKFILE_DIR}}' || fail=1
|
||||
|
||||
# 5. A documented session_log call must be one the tool would accept:
|
||||
# session_id is its only required field, and nine skills omitted it.
|
||||
sh '{{.TASKFILE_DIR}}/bin/check-session-log' '{{.TASKFILE_DIR}}' || fail=1
|
||||
|
||||
# 6. Every skill says when it stops and hands back (#5). Skills whose
|
||||
# rule is not written yet are listed in bin/escalation-pending.txt,
|
||||
# which only shrinks.
|
||||
sh '{{.TASKFILE_DIR}}/bin/check-escalation' '{{.TASKFILE_DIR}}' || fail=1
|
||||
|
||||
# 7. Plugin manifest version must match the latest tag, or installers
|
||||
# never see the update (Claude Code gates updates on this field).
|
||||
if [ -f '{{.PLUGIN_MANIFEST}}' ]; then
|
||||
manifest_v=$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' '{{.PLUGIN_MANIFEST}}' | head -1)
|
||||
tag_v=$(git -C '{{.TASKFILE_DIR}}' describe --tags --abbrev=0 2>/dev/null | sed 's/^v//' || echo '')
|
||||
# Ordering, not equality. The fault this guards is the manifest
|
||||
# failing to MOVE — a release tag whose manifest still names the old
|
||||
# version, so no installed host ever sees the update. A manifest
|
||||
# ahead of the newest tag this checkout knows about is the normal
|
||||
# state between the tagger's bump commit and a tag fetch (#34).
|
||||
if [ -n "$tag_v" ] && [ "$manifest_v" != "$tag_v" ] \
|
||||
&& [ "$(sh '{{.TASKFILE_DIR}}/bin/newer-version' "$manifest_v" "$tag_v")" = "$tag_v" ]; then
|
||||
echo "ERROR: plugin.json version ($manifest_v) is behind the latest tag ($tag_v) — installed hosts never see the update" >&2
|
||||
fail=1
|
||||
fi
|
||||
else
|
||||
echo "ERROR: missing .claude-plugin/plugin.json" >&2; fail=1
|
||||
fi
|
||||
|
||||
# Every ${VAR} a live .mcp.json server interpolates must be one the
|
||||
# session env-file defines. An undefined one is silent: the header
|
||||
# goes out empty and the server reports "requires authentication",
|
||||
# which reads as a revoked credential. Exit 2 means the check could
|
||||
# not run (no jq, or no env-file — CI has neither); that is reported
|
||||
# and not fatal, but it is never treated as a pass.
|
||||
if [ -x "{{.TASKFILE_DIR}}/bin/check-mcp-env" ]; then
|
||||
# `|| rc=$?` is load-bearing, not style. Task runs this block under
|
||||
# `sh -e`, so a bare invocation exiting non-zero kills the shell
|
||||
# before `case` is reached -- the tolerance below never ran, and the
|
||||
# gate died with `exit status 2` on the commit that added it.
|
||||
rc=0
|
||||
"{{.TASKFILE_DIR}}/bin/check-mcp-env" "{{.TASKFILE_DIR}}/.mcp.json" "$HOME/.op-env" || rc=$?
|
||||
case $rc in
|
||||
0) ;;
|
||||
2) echo "NOTE: MCP env wiring unverified on this host" >&2 ;;
|
||||
*) fail=1 ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
if [ $fail -ne 0 ]; then
|
||||
echo "check FAILED" >&2; exit 1
|
||||
fi
|
||||
echo "check OK — $count skills, manifest matches tag"
|
||||
|
||||
release:
|
||||
desc: 'Tag HEAD per Bump-Type in the latest commit footer. Normally CI handles this — run locally only when CI is unavailable.'
|
||||
desc: 'Tag HEAD per Bump-Type in the latest commit footer. Normally CI handles this.'
|
||||
cmds:
|
||||
- |
|
||||
latest=$(git -C "{{.TASKFILE_DIR}}" describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0")
|
||||
@@ -150,26 +181,3 @@ tasks:
|
||||
echo "tagging $next (previous $latest, bump=${bump:-patch})"
|
||||
git -C "{{.TASKFILE_DIR}}" tag -a "$next" -m "release $next"
|
||||
echo "now: git push origin $next"
|
||||
|
||||
check:
|
||||
desc: 'Sanity check — every skill dir has a SKILL.md, no stray files at root.'
|
||||
cmds:
|
||||
- |
|
||||
missing=0
|
||||
for skill in $(ls -1 "{{.TASKFILE_DIR}}" | grep -Ev "^(Taskfile.yml|install.sh|README.md|SKILLS_INDEX.md|.gitea|.git$)$"); do
|
||||
dir="{{.TASKFILE_DIR}}/${skill}"
|
||||
if [ ! -d "$dir" ]; then
|
||||
echo "ERROR: $skill is not a directory" >&2
|
||||
missing=$((missing + 1))
|
||||
continue
|
||||
fi
|
||||
if [ ! -f "$dir/SKILL.md" ]; then
|
||||
echo "ERROR: $dir missing SKILL.md" >&2
|
||||
missing=$((missing + 1))
|
||||
fi
|
||||
done
|
||||
if [ $missing -gt 0 ]; then
|
||||
echo "$missing skill(s) failed structure check" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "all skills have SKILL.md"
|
||||
|
||||
Executable
+88
@@ -0,0 +1,88 @@
|
||||
#!/bin/sh
|
||||
# check-escalation — every skill states when it stops and hands back.
|
||||
#
|
||||
# #5 decided this belongs in the body, not the frontmatter: no harness reads
|
||||
# frontmatter beyond name/description, so a `failure_criteria:` key would be a
|
||||
# guarantee nothing honours. The model reads the body.
|
||||
#
|
||||
# #37 then had to define which skills need one, and every obvious answer was
|
||||
# bad: a hardcoded list rots, sniffing the text for "does it write anything" is
|
||||
# unfalsifiable, and a frontmatter flag is the rejected option wearing a hat.
|
||||
#
|
||||
# So there is no acting set. EVERY skill answers the question. A read-only skill
|
||||
# answers it in one line — "read-only; findings are the output, nothing is
|
||||
# handed back" — which turns an absence into a claim someone can disagree with.
|
||||
#
|
||||
# bin/escalation-pending.txt is a ratchet for skills whose real rule has not
|
||||
# been written yet (a stop condition nobody thought about is not worth
|
||||
# enforcing). It is self-cleaning: a listed skill that HAS a section fails, so
|
||||
# the list cannot outlive its reason.
|
||||
#
|
||||
# Usage: check-escalation [checkout-root]
|
||||
|
||||
set -u
|
||||
|
||||
ROOT=${1:-$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)}
|
||||
PENDING="$ROOT/bin/escalation-pending.txt"
|
||||
fail=0
|
||||
|
||||
listed() {
|
||||
[ -f "$PENDING" ] || return 1
|
||||
sed 's/#.*//' "$PENDING" | grep -qx "[[:space:]]*$1[[:space:]]*"
|
||||
}
|
||||
|
||||
for dir in "$ROOT"/skills/*/; do
|
||||
[ -f "$dir/SKILL.md" ] || continue
|
||||
name=$(basename "$dir")
|
||||
|
||||
if grep -q '^## Escalation' "$dir/SKILL.md"; then
|
||||
if listed "$name"; then
|
||||
echo "ERROR: skills/$name has an Escalation section but is still in bin/escalation-pending.txt — remove it from the list" >&2
|
||||
fail=1
|
||||
fi
|
||||
continue
|
||||
fi
|
||||
|
||||
listed "$name" && continue
|
||||
echo "ERROR: skills/$name has no '## Escalation' section — say when it stops and hands back, or say it never does" >&2
|
||||
fail=1
|
||||
done
|
||||
|
||||
# A pending entry for a skill that no longer exists is a stale exemption, and a
|
||||
# stale exemption is how a gate quietly stops covering something. Looped without
|
||||
# a pipe on purpose: a `while read` on the right of a pipe runs in a subshell,
|
||||
# so `fail=1` would be set in a process that exits before it is read.
|
||||
if [ -f "$PENDING" ]; then
|
||||
entries=$(sed 's/#.*//' "$PENDING" | tr -d '[:blank:]' | grep -v '^$' || true)
|
||||
for entry in $entries; do
|
||||
[ -f "$ROOT/skills/$entry/SKILL.md" ] && continue
|
||||
echo "ERROR: bin/escalation-pending.txt lists '$entry', which has no skills/$entry/SKILL.md" >&2
|
||||
fail=1
|
||||
done
|
||||
fi
|
||||
|
||||
# --- the ratchet must actually ratchet ---------------------------------------
|
||||
# "This list only shrinks" was asserted in five places and enforced in none. A
|
||||
# traceability probe falsified it in one run: add an unsectioned skill, append it
|
||||
# to the list, gate returns 0. So compare against the list as committed at HEAD —
|
||||
# a convention nothing checks is a convention, and this repo has spent a day on
|
||||
# what those cost.
|
||||
if [ -f "$PENDING" ]; then
|
||||
if ! git -C "$ROOT" rev-parse --git-dir >/dev/null 2>&1; then
|
||||
echo "WARN: $ROOT is not a git checkout — cannot verify the pending list only shrank" >&2
|
||||
elif ! git -C "$ROOT" cat-file -e HEAD:bin/escalation-pending.txt 2>/dev/null; then
|
||||
: # first commit introducing the file — nothing to compare against yet
|
||||
else
|
||||
before=$(git -C "$ROOT" show HEAD:bin/escalation-pending.txt 2>/dev/null \
|
||||
| sed 's/#.*//' | tr -d '[:blank:]' | grep -v '^$' | sort -u || true)
|
||||
now=$(sed 's/#.*//' "$PENDING" | tr -d '[:blank:]' | grep -v '^$' | sort -u || true)
|
||||
added=$(printf '%s\n' "$now" | grep -vxF "$before" 2>/dev/null || true)
|
||||
for entry in $added; do
|
||||
[ -n "$entry" ] || continue
|
||||
echo "ERROR: '$entry' was added to bin/escalation-pending.txt — the list only shrinks. Write its '## Escalation' section instead of exempting it." >&2
|
||||
fail=1
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
exit $fail
|
||||
Executable
+89
@@ -0,0 +1,89 @@
|
||||
#!/bin/sh
|
||||
# check-mcp-env — assert every variable a live MCP server interpolates is one
|
||||
# the session env-file actually defines.
|
||||
#
|
||||
# Why this is a gate and not a comment: the failure is silent. A header of
|
||||
# "Bearer ${FOO}" where FOO is undefined does not error -- it goes out empty,
|
||||
# the server answers 401, and Claude Code reports "requires authentication",
|
||||
# which reads exactly like a revoked credential. On 2026-09-07 that cost a
|
||||
# full investigation on koala before the credential turned out to be fine.
|
||||
#
|
||||
# Servers under `_parked` are exempt by design. Parked means "reachable, but
|
||||
# nothing puts its token in the environment yet" -- flagging those would
|
||||
# report the intended state as a fault.
|
||||
#
|
||||
# Usage: check-mcp-env <mcp.json> <env-file>
|
||||
#
|
||||
# Exit 0 every live server's variables are defined
|
||||
# 1 at least one is not, named on stderr
|
||||
# 2 could not verify (bad usage, unreadable input, jq absent).
|
||||
# Deliberately distinct from 0: an unverified config is not a clean
|
||||
# one, and a gate that cannot run should say so rather than pass.
|
||||
|
||||
set -u
|
||||
|
||||
CONFIG=${1:-}
|
||||
ENVFILE=${2:-}
|
||||
|
||||
if [ -z "$CONFIG" ] || [ -z "$ENVFILE" ]; then
|
||||
echo "usage: check-mcp-env <mcp.json> <env-file>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if ! command -v jq >/dev/null 2>&1; then
|
||||
echo "SKIP: jq not installed -- MCP env wiring unverified" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ ! -f "$CONFIG" ]; then
|
||||
echo "ERROR: no such config: $CONFIG" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ ! -f "$ENVFILE" ]; then
|
||||
echo "ERROR: no such env-file: $ENVFILE -- cannot verify MCP variables" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Every "<server>\t<VAR>" pair a live server interpolates. `..` walks the whole
|
||||
# value, so a variable is found wherever it is placed, not only under headers.
|
||||
refs=$(jq -r '
|
||||
.mcpServers // {}
|
||||
| to_entries[]
|
||||
| .key as $server
|
||||
| (.value | .. | strings)
|
||||
| select(test("\\$\\{"))
|
||||
| [ scan("\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}")[] ]
|
||||
| .[]
|
||||
| "\($server)\t\(.)"
|
||||
' "$CONFIG" 2>/dev/null) || {
|
||||
echo "ERROR: $CONFIG is not valid JSON -- MCP env wiring unverified" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
if [ -z "$refs" ]; then
|
||||
echo "check-mcp-env: no interpolated variables in live servers"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
fail=0
|
||||
checked=0
|
||||
for pair in $(printf '%s\n' "$refs" | tr '\t' ':'); do
|
||||
server=${pair%%:*}
|
||||
var=${pair#*:}
|
||||
checked=$((checked + 1))
|
||||
if grep -qE "^[[:space:]]*(export[[:space:]]+)?$var=" "$ENVFILE"; then
|
||||
continue
|
||||
fi
|
||||
printf 'ERROR: MCP server %s interpolates %s, which %s does not define.\n' \
|
||||
"$server" "$var" "$ENVFILE" >&2
|
||||
printf ' It will send an empty Authorization header and report as "requires authentication".\n' >&2
|
||||
fail=1
|
||||
done
|
||||
|
||||
if [ "$fail" -ne 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf 'check-mcp-env: %d interpolated variable(s) across live MCP servers, all defined in %s\n' \
|
||||
"$checked" "$ENVFILE"
|
||||
Executable
+63
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
# check-session-log — a skill that documents a session_log call must document a
|
||||
# call the tool would actually accept.
|
||||
#
|
||||
# Nine skills documented the payload and none named `session_id`, which is the
|
||||
# tool's only REQUIRED field. An agent following any of them either failed the
|
||||
# call or invented an id — and invented ids do not group, so the pass-rate the
|
||||
# endpoint computes was being assembled from entries that could not be joined
|
||||
# (#36, found by a pressure test against `debug`).
|
||||
#
|
||||
# Also rejected: `duration_ms: <wall-clock>`. An agent does not observe a clock.
|
||||
# A documented field nobody can honestly populate gets fabricated or silently
|
||||
# dropped, and fabricated numbers in a metrics stream are worse than no numbers.
|
||||
#
|
||||
# Usage: check-session-log [checkout-root]
|
||||
|
||||
set -u
|
||||
|
||||
ROOT=${1:-$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)}
|
||||
fail=0
|
||||
|
||||
for dir in "$ROOT"/skills/*/; do
|
||||
[ -f "$dir/SKILL.md" ] || continue
|
||||
name=$(basename "$dir")
|
||||
|
||||
grep -q 'session_log' "$dir/SKILL.md" || continue
|
||||
|
||||
# Read the PAYLOAD, not the file. The first version of this gate grepped the
|
||||
# whole SKILL.md for "session_id", so a payload missing the field passed as
|
||||
# long as the word appeared anywhere — including in prose explaining that the
|
||||
# field is required. A traceability probe demonstrated it in one sed.
|
||||
payloads=$(grep -n 'session_log' "$dir/SKILL.md" | grep '{' || true)
|
||||
|
||||
if [ -z "$payloads" ]; then
|
||||
# Mentions the tool but documents no call. Nothing to check, and nothing to
|
||||
# get wrong.
|
||||
continue
|
||||
fi
|
||||
|
||||
printf '%s\n' "$payloads" | while IFS= read -r line; do
|
||||
[ -n "$line" ] || continue
|
||||
body=$(printf '%s' "$line" | sed 's/^[0-9]*://')
|
||||
lineno=$(printf '%s' "$line" | cut -d: -f1)
|
||||
|
||||
printf '%s' "$body" | grep -q 'session_id' \
|
||||
|| echo "ERROR: skills/$name:$lineno documents a session_log payload with no session_id — the tool's only required field" >&2
|
||||
|
||||
# Any spelling of the key, quoted or not, followed by anything that is not a
|
||||
# bare number. A placeholder nobody can fill gets fabricated or dropped; a
|
||||
# real measurement is fine.
|
||||
if printf '%s' "$body" | grep -Eq '"?duration_ms"?[[:space:]]*:[[:space:]]*[^0-9,}[:space:]]'; then
|
||||
echo "ERROR: skills/$name:$lineno documents duration_ms as something other than a real measurement — an agent does not observe a clock; omit it" >&2
|
||||
fi
|
||||
done > "$ROOT/.session_log_errors.$$" 2>&1
|
||||
|
||||
if [ -s "$ROOT/.session_log_errors.$$" ]; then
|
||||
cat "$ROOT/.session_log_errors.$$" >&2
|
||||
fail=1
|
||||
fi
|
||||
rm -f "$ROOT/.session_log_errors.$$"
|
||||
done
|
||||
|
||||
exit $fail
|
||||
Executable
+49
@@ -0,0 +1,49 @@
|
||||
#!/bin/sh
|
||||
# check-surfaces — every skill declares which surfaces it ships to, and only
|
||||
# names surfaces that exist.
|
||||
#
|
||||
# The repo distributes three ways: the Claude Code plugin, the symlinked
|
||||
# library (Crush/Pi/OpenCode), and claude.ai, which has no fetch path at all.
|
||||
# Treating every skill as belonging to all three installs skills that can never
|
||||
# fire — gitea-ci, playwright and web-shot have no shell or cluster in a chat
|
||||
# surface — and degrades selection for the ones that can (#29).
|
||||
#
|
||||
# Values are validated, not merely counted: a wrong surface silently removes a
|
||||
# skill from a harness rather than erroring, which is the failure mode this
|
||||
# whole file exists to prevent.
|
||||
#
|
||||
# Usage: check-surfaces [checkout-root]
|
||||
|
||||
set -u
|
||||
|
||||
ROOT=${1:-$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)}
|
||||
ALLOWED='claude-code library chat'
|
||||
fail=0
|
||||
|
||||
for dir in "$ROOT"/skills/*/; do
|
||||
[ -f "$dir/SKILL.md" ] || continue
|
||||
name=$(basename "$dir")
|
||||
|
||||
line=$(sed -n 's/^surfaces:[[:space:]]*//p' "$dir/SKILL.md" | head -1)
|
||||
if [ -z "$line" ]; then
|
||||
echo "ERROR: skills/$name declares no 'surfaces:' — say where it ships (${ALLOWED% *}, ${ALLOWED##* })" >&2
|
||||
fail=1
|
||||
continue
|
||||
fi
|
||||
|
||||
values=$(printf '%s' "$line" | tr -d '[]' | tr ',' ' ')
|
||||
count=0
|
||||
for v in $values; do
|
||||
count=$((count + 1))
|
||||
case " $ALLOWED " in
|
||||
*" $v "*) ;;
|
||||
*) echo "ERROR: skills/$name names surface '$v', which does not exist — allowed: $ALLOWED" >&2; fail=1 ;;
|
||||
esac
|
||||
done
|
||||
[ "$count" -gt 0 ] || {
|
||||
echo "ERROR: skills/$name has an empty 'surfaces:' list — a skill that ships nowhere should be deleted, not declared" >&2
|
||||
fail=1
|
||||
}
|
||||
done
|
||||
|
||||
exit $fail
|
||||
Executable
+341
@@ -0,0 +1,341 @@
|
||||
#!/bin/sh
|
||||
# doctor — report skills-library drift on this host.
|
||||
#
|
||||
# Written because every failure this fleet actually hit was SILENT: 243
|
||||
# dangling symlinks hidden from git by the **/.claude/skills/ ignore rule, a
|
||||
# checkout that still resolved but was 20 skills behind, a loose .md that
|
||||
# loaded in no harness, and two machines where the library was simply absent.
|
||||
# None of it errored. Exit status here is the signal that was missing.
|
||||
#
|
||||
# doctor human report, non-zero exit on drift
|
||||
# doctor --quiet print only when something is wrong (SessionStart hook)
|
||||
# doctor --json machine-readable findings
|
||||
# doctor --online ALSO ask origin for the latest tag (one network call)
|
||||
#
|
||||
# POSIX sh on purpose: it runs on macOS and Linux, before any toolchain is
|
||||
# guaranteed present, and inside a session-start hook where latency shows.
|
||||
# It does no network I/O and never shells out to git for a fetch.
|
||||
#
|
||||
# Test seams: $HOME drives harness paths, $DOCTOR_CHECKOUT names the checkout.
|
||||
|
||||
set -u
|
||||
|
||||
QUIET=0
|
||||
JSON=0
|
||||
ONLINE=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--quiet) QUIET=1 ;;
|
||||
--json) JSON=1 ;;
|
||||
--online) ONLINE=1 ;;
|
||||
-h|--help)
|
||||
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
|
||||
exit 0 ;;
|
||||
*) printf 'doctor: unknown option %s\n' "$arg" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
SELF_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
SELF_CHECKOUT=$(CDPATH= cd -- "$SELF_DIR/.." && pwd)
|
||||
|
||||
# The canonical checkout is whatever ~/.agents/skills resolves to — NOT the
|
||||
# copy doctor happens to be running from. When invoked as a plugin hook, $0
|
||||
# lives in the plugin cache, which is legitimately a second copy: judging the
|
||||
# harness links against it would flag every one of them as "outside".
|
||||
AGENTS_DIR="$HOME/.agents/skills"
|
||||
SOURCES_FILE="$(dirname -- "$AGENTS_DIR")/$(basename -- "$AGENTS_DIR")-sources"
|
||||
|
||||
if [ -n "${DOCTOR_CHECKOUT:-}" ]; then
|
||||
CHECKOUT="$DOCTOR_CHECKOUT"
|
||||
elif [ -f "$SOURCES_FILE" ]; then
|
||||
# Since #27 the canonical location is a real directory fed by several
|
||||
# sources, so it can no longer be resolved to a checkout. install.sh records
|
||||
# the list; the first line is always this repo's skills/ directory.
|
||||
CHECKOUT=$(dirname -- "$(head -n 1 "$SOURCES_FILE")")
|
||||
elif [ -L "$AGENTS_DIR" ]; then
|
||||
# Pre-#27 wiring: one link straight at the checkout. Resolve the link FIRST,
|
||||
# then take the parent. "cd X/.." resolves ".." lexically against the link
|
||||
# path, which lands back in ~/.agents.
|
||||
_resolved=$(CDPATH= cd -- "$AGENTS_DIR" 2>/dev/null && pwd -P)
|
||||
CHECKOUT=$(dirname -- "$_resolved")
|
||||
else
|
||||
CHECKOUT="$SELF_CHECKOUT"
|
||||
fi
|
||||
SKILLS_DIR="$CHECKOUT/skills"
|
||||
|
||||
findings=0
|
||||
report=""
|
||||
|
||||
# add <severity> <check> <detail>
|
||||
add() {
|
||||
findings=$((findings + 1))
|
||||
if [ "$JSON" -eq 1 ]; then
|
||||
report="${report}{\"severity\":\"$1\",\"check\":\"$2\",\"detail\":\"$(printf '%s' "$3" | sed 's/"/\\"/g')\"},"
|
||||
else
|
||||
report="${report}$1 $2: $3
|
||||
"
|
||||
fi
|
||||
}
|
||||
|
||||
# count_skills <dir> — directories containing a SKILL.md, one level down.
|
||||
# -L on purpose: since #27 the entries are per-skill symlinks, and find does
|
||||
# not descend into a symlinked directory without it.
|
||||
count_skills() {
|
||||
[ -d "$1" ] || { printf '0'; return; }
|
||||
find -L "$1"/ -mindepth 2 -maxdepth 2 -name SKILL.md 2>/dev/null | wc -l | tr -d ' '
|
||||
}
|
||||
|
||||
# under_known_source <physical-path> — 0 when the path lies inside a source
|
||||
# install.sh recorded, or inside the active checkout.
|
||||
under_known_source() {
|
||||
_path=$1
|
||||
_list="$SKILLS_DIR"
|
||||
[ -f "$SOURCES_FILE" ] && _list="$_list
|
||||
$(cat "$SOURCES_FILE")"
|
||||
printf '%s\n' "$_list" | while IFS= read -r _src; do
|
||||
[ -n "$_src" ] || continue
|
||||
_real=$(CDPATH= cd -- "$_src" 2>/dev/null && pwd -P) || continue
|
||||
[ -n "$_real" ] || continue
|
||||
case "$_path" in "$_real"/*|"$_real") printf 'yes'; break ;; esac
|
||||
done | grep -q yes
|
||||
}
|
||||
|
||||
# --- the checkout itself ----------------------------------------------------
|
||||
if [ ! -d "$SKILLS_DIR" ]; then
|
||||
add FAIL checkout "no skills/ directory at $CHECKOUT"
|
||||
# Nothing downstream can be judged without it.
|
||||
printf 'FAIL checkout: no skills/ directory at %s\n' "$CHECKOUT" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
EXPECTED=$(count_skills "$SKILLS_DIR")
|
||||
[ "$EXPECTED" -gt 0 ] || add FAIL checkout "skills/ holds no SKILL.md at all"
|
||||
|
||||
# --- stray entries in the checkout -----------------------------------------
|
||||
# A loose foo.md where foo/SKILL.md was meant loads in NO harness and errors
|
||||
# in none either. That is exactly how secret-hygiene.md sat dead for months.
|
||||
for entry in "$SKILLS_DIR"/*; do
|
||||
[ -e "$entry" ] || continue
|
||||
name=$(basename "$entry")
|
||||
if [ ! -d "$entry" ]; then
|
||||
add FAIL stray "$SKILLS_DIR/$name is not a directory — it loads nowhere"
|
||||
elif [ ! -f "$entry/SKILL.md" ]; then
|
||||
add FAIL stray "$SKILLS_DIR/$name has no SKILL.md"
|
||||
fi
|
||||
done
|
||||
|
||||
# --- the canonical directory --------------------------------------------------
|
||||
# Pre-#27 this was a symlink at the checkout. It is a real directory now, one
|
||||
# per-skill link per skill, fed by every configured source — that is what lets
|
||||
# a second library (Anthropic's official set on flamingo) coexist instead of
|
||||
# being displaced.
|
||||
if [ -L "$AGENTS_DIR" ]; then
|
||||
add WARN legacy "$AGENTS_DIR is the pre-#27 single-link wiring — re-run install.sh to adopt the multi-source layout"
|
||||
elif [ -d "$AGENTS_DIR" ]; then
|
||||
for entry in "$AGENTS_DIR"/*; do
|
||||
[ -e "$entry" ] || [ -L "$entry" ] || continue
|
||||
name=$(basename "$entry")
|
||||
|
||||
if [ ! -L "$entry" ]; then
|
||||
add FAIL unmanaged "$AGENTS_DIR/$name is not a link into any source — nothing manages it and nothing updates it"
|
||||
continue
|
||||
fi
|
||||
if [ ! -e "$entry" ]; then
|
||||
add FAIL dangling "$entry -> $(readlink "$entry") (target does not exist)"
|
||||
continue
|
||||
fi
|
||||
|
||||
resolved=$(CDPATH= cd -- "$entry" 2>/dev/null && pwd -P)
|
||||
if [ -n "$resolved" ] && ! under_known_source "$resolved"; then
|
||||
add FAIL outside "$entry resolves to $resolved, an unknown source — it works, so nothing complains, while serving content nobody updates"
|
||||
fi
|
||||
done
|
||||
|
||||
# A per-skill layout can lose one skill without changing any total, so the
|
||||
# invariant is per skill, not a count.
|
||||
for dir in "$SKILLS_DIR"/*/; do
|
||||
[ -f "$dir/SKILL.md" ] || continue
|
||||
name=$(basename "$dir")
|
||||
# Only skills that ship to the library belong here. A chat-only skill
|
||||
# missing from a Crush directory is correct, not drift (#29).
|
||||
surfaces=$(sed -n 's/^surfaces:[[:space:]]*//p' "$dir/SKILL.md" | head -1)
|
||||
if [ -n "$surfaces" ] \
|
||||
&& ! printf '%s' "$surfaces" | tr -d '[]' | tr ',' ' ' | grep -qw library; then
|
||||
continue
|
||||
fi
|
||||
[ -L "$AGENTS_DIR/$name" ] \
|
||||
|| add FAIL missing "$name is in the checkout but has no link in $AGENTS_DIR — re-run install.sh"
|
||||
done
|
||||
fi
|
||||
|
||||
# --- harness wiring ---------------------------------------------------------
|
||||
# Crush and OpenCode keep their single directory link at the canonical dir;
|
||||
# Pi reads it directly and needs no link of its own.
|
||||
for dir in \
|
||||
"$HOME/.config/crush/skills" \
|
||||
"$HOME/.config/opencode/skills"
|
||||
do
|
||||
[ -L "$dir" ] || [ -d "$dir" ] || continue
|
||||
|
||||
if [ -L "$dir" ] && [ ! -e "$dir" ]; then
|
||||
add FAIL dangling "$dir -> $(readlink "$dir") (target does not exist)"
|
||||
continue
|
||||
fi
|
||||
|
||||
# A real directory where a link belongs holds content nothing manages: it
|
||||
# cannot receive new skills and silently shadows the canonical dir. Since
|
||||
# #27 the fix is not only "move it aside" — it can be added as an extra
|
||||
# source instead, which is how flamingo keeps the official Anthropic set.
|
||||
if [ ! -L "$dir" ] && [ -d "$dir" ]; then
|
||||
add FAIL unmanaged "$dir is a real directory, not a link into the canonical dir — it holds $(count_skills "$dir") unmanaged skill(s); add it to SKILLS_EXTRA_SOURCES and re-run install.sh, or move it aside"
|
||||
continue
|
||||
fi
|
||||
|
||||
resolved=$(CDPATH= cd -- "$dir" 2>/dev/null && pwd -P)
|
||||
canonical=$(CDPATH= cd -- "$AGENTS_DIR" 2>/dev/null && pwd -P)
|
||||
if [ -n "$resolved" ] && [ -n "$canonical" ] && [ "$resolved" != "$canonical" ]; then
|
||||
add FAIL outside "$dir resolves to $resolved, not the canonical $canonical"
|
||||
fi
|
||||
done
|
||||
|
||||
# --- dangling links anywhere under the harness dirs -------------------------
|
||||
for dir in "$HOME/.config/crush/skills" \
|
||||
"$HOME/.config/opencode/skills" "$HOME/.claude/skills"
|
||||
do
|
||||
[ -d "$dir" ] || continue
|
||||
# Plain glob, not find|while: a while loop on the right of a pipe runs in a
|
||||
# subshell, so add() would increment a counter that dies with it and doctor
|
||||
# would exit 0 having found faults.
|
||||
for link in "$dir"/*; do
|
||||
[ -L "$link" ] || continue
|
||||
[ -e "$link" ] && continue
|
||||
add FAIL dangling "$link -> $(readlink "$link") (target does not exist)"
|
||||
done
|
||||
done
|
||||
|
||||
# --- Claude Code: plugin vs leftover per-skill symlinks ---------------------
|
||||
# Plugin skills do NOT override same-named user skills — both stay visible. So
|
||||
# leftover links from the pre-plugin era mean every skill appears twice.
|
||||
CLAUDE_SKILLS="$HOME/.claude/skills"
|
||||
if [ -d "$CLAUDE_SKILLS" ]; then
|
||||
legacy=$(find "$CLAUDE_SKILLS"/ -maxdepth 1 -type l 2>/dev/null | wc -l | tr -d ' ')
|
||||
if [ "$legacy" -gt 0 ]; then
|
||||
add FAIL legacy "$CLAUDE_SKILLS holds $legacy per-skill symlink(s) from the pre-plugin wiring — remove them or every skill loads twice"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Two delivery mechanisms means two copies that can drift apart: the plugin
|
||||
# (Claude Code) and the checkout the other harnesses link to. Same host,
|
||||
# different skill sets, no error — compare them.
|
||||
# Skipped when DOCTOR_CHECKOUT is set: that scopes doctor to an explicit
|
||||
# target, so comparing it against whatever copy the script lives in is
|
||||
# meaningless rather than informative.
|
||||
if [ -z "${DOCTOR_CHECKOUT:-}" ] && [ -f "$SELF_DIR/../.claude-plugin/plugin.json" ] \
|
||||
&& [ "$SELF_CHECKOUT" != "$CHECKOUT" ]; then
|
||||
plugin_count=$(count_skills "$SELF_CHECKOUT/skills")
|
||||
if [ "$plugin_count" != "$EXPECTED" ]; then
|
||||
add FAIL drift "Claude Code plugin serves $plugin_count skills, the other harnesses see $EXPECTED — the two copies have diverged"
|
||||
fi
|
||||
fi
|
||||
|
||||
INSTALLED="$HOME/.claude/plugins/installed_plugins.json"
|
||||
if [ -f "$INSTALLED" ]; then
|
||||
grep -q '"skills@mathias"' "$INSTALLED" 2>/dev/null \
|
||||
|| add WARN plugin "skills@mathias is not installed for Claude Code — /plugin marketplace add https://git.d-ma.be/mathias/skills.git"
|
||||
fi
|
||||
|
||||
# --- Claude Code: which GENERATION of the plugin is installed ---------------
|
||||
# Every check above is about symlink paths, which is the wrong shape for the
|
||||
# plugin: it is the only channel Claude Code has, and Claude Code gates updates
|
||||
# on plugin.json's version. A host that never picked up a release loads all the
|
||||
# skills successfully and is simply a generation behind — silently. Found on
|
||||
# koala 2026-08-29: installed 0.6.0, marketplace clone 0.7.0, repo 0.8.5,
|
||||
# doctor said "clean" (#30).
|
||||
#
|
||||
# Offline by construction, like the rest of doctor: "available" means the
|
||||
# newest manifest already on this host — the active checkout and any
|
||||
# marketplace clone — never a fetch.
|
||||
manifest_version() {
|
||||
[ -f "$1" ] || return 1
|
||||
grep -q '"name"[[:space:]]*:[[:space:]]*"skills"' "$1" || return 1
|
||||
sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$1" | head -1
|
||||
}
|
||||
|
||||
# newer_version a b — echoes whichever sorts higher on major.minor.patch.
|
||||
# Lives in bin/newer-version because `task check` needs the same ordering (#34)
|
||||
# and a second copy is a second thing to get wrong.
|
||||
newer_version() {
|
||||
sh "$SELF_DIR/newer-version" "$1" "$2"
|
||||
}
|
||||
|
||||
installed_v=''
|
||||
if [ -f "$INSTALLED" ]; then
|
||||
installed_v=$(sed -n '/"skills@mathias"/,/\]/p' "$INSTALLED" \
|
||||
| sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1)
|
||||
fi
|
||||
|
||||
available_v=''
|
||||
for manifest in "$CHECKOUT/.claude-plugin/plugin.json" \
|
||||
"$HOME"/.claude/plugins/marketplaces/*/.claude-plugin/plugin.json
|
||||
do
|
||||
v=$(manifest_version "$manifest") || continue
|
||||
[ -n "$v" ] || continue
|
||||
if [ -z "$available_v" ]; then
|
||||
available_v=$v
|
||||
else
|
||||
available_v=$(newer_version "$available_v" "$v")
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -n "$installed_v" ] && [ -n "$available_v" ] && [ "$installed_v" != "$available_v" ]; then
|
||||
add FAIL plugin-version "Claude Code has skills@mathias $installed_v installed but $available_v is available on this host — /plugin update skills@mathias (a host stale enough to matter is running the old doctor, so the first detection may need this run by hand)"
|
||||
fi
|
||||
|
||||
# --- optional: the release this host has never fetched ----------------------
|
||||
# Every check above compares copies already present, so a host whose checkout,
|
||||
# marketplace clone and installed plugin all agree reads as clean while sitting
|
||||
# a release behind origin (#38). Closing that needs a network call, which the
|
||||
# default run must not make — hence opt-in, for a scheduled per-host job rather
|
||||
# than the SessionStart hook.
|
||||
#
|
||||
# $DOCTOR_LATEST_TAG_CMD is the test seam; it prints the newest remote tag.
|
||||
if [ "$ONLINE" -eq 1 ]; then
|
||||
if [ -n "${DOCTOR_LATEST_TAG_CMD:-}" ]; then
|
||||
remote_tag=$(eval "$DOCTOR_LATEST_TAG_CMD" 2>/dev/null | tail -1 | tr -d '[:space:]')
|
||||
else
|
||||
# The URL is never printed: a remote rewritten by url.insteadOf can expand
|
||||
# into a live token.
|
||||
origin=$(git -C "$CHECKOUT" config --get remote.origin.url 2>/dev/null || true)
|
||||
if [ -n "$origin" ]; then
|
||||
remote_tag=$(git ls-remote --tags --refs "$origin" 2>/dev/null \
|
||||
| sed 's#.*refs/tags/##' | sort -t. -k1,1n -k2,2n -k3,3n | tail -1 | tr -d '[:space:]')
|
||||
else
|
||||
remote_tag=''
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$remote_tag" ]; then
|
||||
# Not drift. A host that cannot reach origin has an unanswered question,
|
||||
# not a stale library, and saying otherwise would make the two look alike.
|
||||
add WARN offline "could not reach origin for the latest tag — this run proves nothing about staleness"
|
||||
else
|
||||
remote_v=${remote_tag#v}
|
||||
if [ -n "$available_v" ] && [ "$remote_v" != "$available_v" ] \
|
||||
&& [ "$(newer_version "$available_v" "$remote_v")" = "$remote_v" ]; then
|
||||
add FAIL behind "this host has $available_v; origin has released $remote_v — run 'task update' and '/plugin update skills@mathias'"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- output -----------------------------------------------------------------
|
||||
if [ "$JSON" -eq 1 ]; then
|
||||
printf '{"checkout":"%s","expected":%s,"plugin":{"installed":"%s","available":"%s"},"findings":[%s]}\n' \
|
||||
"$CHECKOUT" "$EXPECTED" "$installed_v" "$available_v" "${report%,}"
|
||||
elif [ "$findings" -gt 0 ]; then
|
||||
printf 'skills doctor — %s finding(s), checkout %s\n\n%s\n' \
|
||||
"$findings" "$CHECKOUT" "$report"
|
||||
elif [ "$QUIET" -eq 0 ]; then
|
||||
printf 'skills doctor: clean — %s skills, checkout %s\n' "$EXPECTED" "$CHECKOUT"
|
||||
fi
|
||||
|
||||
[ "$findings" -eq 0 ]
|
||||
@@ -0,0 +1,42 @@
|
||||
# Skills whose escalation rule has not been written yet (#37).
|
||||
#
|
||||
# This list only shrinks. A skill here is exempt from the '## Escalation'
|
||||
# requirement until someone writes its real stop conditions; a skill that HAS a
|
||||
# section and is still listed fails the gate, so the list cannot outlive its
|
||||
# reason.
|
||||
#
|
||||
# The ones already done were the advisory and read-only skills, where the honest
|
||||
# answer is a line. What is left is the acting set — skills that write files,
|
||||
# dispatch agents, touch credentials or move releases — and each of those needs
|
||||
# a rule someone thought about, not a rote paragraph. Per #19, one at a time.
|
||||
|
||||
atdd
|
||||
dream
|
||||
experiment-spec
|
||||
feature-spec
|
||||
gitea-ci
|
||||
own-the-task
|
||||
planning
|
||||
playwright
|
||||
problem-analysis
|
||||
refactoring
|
||||
regulatory-risk-assessment
|
||||
secret-hygiene
|
||||
session-retrospective
|
||||
spec-driven-dev
|
||||
superpowers-brainstorming
|
||||
superpowers-dispatching-parallel-agents
|
||||
superpowers-executing-plans
|
||||
superpowers-finishing-a-development-branch
|
||||
superpowers-receiving-code-review
|
||||
superpowers-requesting-code-review
|
||||
superpowers-subagent-driven-development
|
||||
superpowers-using-git-worktrees
|
||||
superpowers-using-superpowers
|
||||
superpowers-verification-before-completion
|
||||
superpowers-writing-plans
|
||||
superpowers-writing-skills
|
||||
tdd
|
||||
trainer
|
||||
user-stories
|
||||
web-shot
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/bin/sh
|
||||
# generate-index — rebuild SKILLS_INDEX.md's table from skill frontmatter.
|
||||
#
|
||||
# The index was hand-maintained and drifted: `dream` and `experiment-spec`
|
||||
# shipped with no row at all, because their rows lived on branches that were
|
||||
# squash-merged after a directory reorg (#15). A gate catches that after the
|
||||
# fact; generating removes the class (#29).
|
||||
#
|
||||
# The curated summary and trigger live in each SKILL.md as `summary:` and
|
||||
# `use_when:` rather than being derived from `description:` — description is a
|
||||
# paragraph written for model selection, and truncating it produces a worse
|
||||
# table than the one being replaced.
|
||||
#
|
||||
# Everything outside the markers is left untouched: the wiring docs, the
|
||||
# relationships tree and the trigger table are prose, not data.
|
||||
#
|
||||
# generate-index [root] rewrite the table in place
|
||||
# generate-index --check [root] exit 1 if the table is out of date
|
||||
|
||||
set -u
|
||||
|
||||
CHECK=0
|
||||
if [ "${1:-}" = "--check" ]; then CHECK=1; shift; fi
|
||||
ROOT=${1:-$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)}
|
||||
INDEX="$ROOT/SKILLS_INDEX.md"
|
||||
|
||||
BEGIN='<!-- BEGIN skills-table -->'
|
||||
END='<!-- END skills-table -->'
|
||||
|
||||
[ -f "$INDEX" ] || { echo "ERROR: missing $INDEX" >&2; exit 1; }
|
||||
grep -qF "$BEGIN" "$INDEX" || { echo "ERROR: $INDEX has no $BEGIN marker" >&2; exit 1; }
|
||||
grep -qF "$END" "$INDEX" || { echo "ERROR: $INDEX has no $END marker" >&2; exit 1; }
|
||||
|
||||
# field <file> <key> — a scalar frontmatter value, quotes stripped.
|
||||
field() {
|
||||
sed -n "s/^$2:[[:space:]]*//p" "$1" | head -1 | sed 's/^"//; s/"$//'
|
||||
}
|
||||
|
||||
table=$(mktemp)
|
||||
fail=0
|
||||
|
||||
{
|
||||
printf '| Skill | Description | Use when | Surfaces |\n'
|
||||
printf '|-------|-------------|----------|----------|\n'
|
||||
} > "$table"
|
||||
|
||||
for dir in "$ROOT"/skills/*/; do
|
||||
[ -f "$dir/SKILL.md" ] || continue
|
||||
name=$(basename "$dir")
|
||||
summary=$(field "$dir/SKILL.md" summary)
|
||||
use_when=$(field "$dir/SKILL.md" use_when)
|
||||
surfaces=$(field "$dir/SKILL.md" surfaces | tr -d '[]')
|
||||
|
||||
if [ -z "$summary" ] || [ -z "$use_when" ]; then
|
||||
echo "ERROR: skills/$name has no 'summary:'/'use_when:' — the index table is generated from them" >&2
|
||||
fail=1
|
||||
continue
|
||||
fi
|
||||
printf '| `%s` | %s | %s | %s |\n' "$name" "$summary" "$use_when" "$surfaces" >> "$table"
|
||||
done
|
||||
|
||||
if [ "$fail" -ne 0 ]; then
|
||||
rm -f "$table"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
out=$(mktemp)
|
||||
awk -v begin="$BEGIN" -v end="$END" -v tablefile="$table" '
|
||||
$0 == begin { print; while ((getline line < tablefile) > 0) print line; skip = 1; next }
|
||||
$0 == end { print; skip = 0; next }
|
||||
!skip { print }
|
||||
' "$INDEX" > "$out"
|
||||
rm -f "$table"
|
||||
|
||||
if [ "$CHECK" -eq 1 ]; then
|
||||
if cmp -s "$out" "$INDEX"; then
|
||||
rm -f "$out"
|
||||
exit 0
|
||||
fi
|
||||
rm -f "$out"
|
||||
echo "ERROR: SKILLS_INDEX.md is out of date — run 'task index' and commit the result" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mv "$out" "$INDEX"
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# newer-version A B — echo whichever of two dotted versions sorts higher.
|
||||
# Equal versions echo A. Missing components count as zero, so 0.9 == 0.9.0.
|
||||
#
|
||||
# Exists because two callers need ordering rather than equality:
|
||||
# - bin/doctor, comparing the installed plugin generation against the newest
|
||||
# manifest on the host (#30);
|
||||
# - task check, which must fail when plugin.json is BEHIND the latest tag and
|
||||
# stay quiet when it is ahead — the normal state on a checkout that has not
|
||||
# fetched the tag CI just pushed (#34).
|
||||
#
|
||||
# sort -V would do it in one line and is not portable enough for this fleet.
|
||||
|
||||
set -u
|
||||
|
||||
[ $# -eq 2 ] || { echo "usage: newer-version A B" >&2; exit 2; }
|
||||
|
||||
printf '%s\n%s\n' "$1" "$2" | awk -F. '
|
||||
{ raw[NR] = $0; for (i = 1; i <= 3; i++) n[NR, i] = ($i == "" ? 0 : $i + 0) }
|
||||
END {
|
||||
for (i = 1; i <= 3; i++) {
|
||||
if (n[1, i] > n[2, i]) { print raw[1]; exit }
|
||||
if (n[1, i] < n[2, i]) { print raw[2]; exit }
|
||||
}
|
||||
print raw[1]
|
||||
}'
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
# should-skip-release — reads a commit message on stdin. Exits 0 when the
|
||||
# release tagger should skip this commit, 1 when it should tag.
|
||||
#
|
||||
# Skipping is opt-in via a git trailer:
|
||||
#
|
||||
# Skip-Release: true
|
||||
#
|
||||
# It is a TRAILER, matched anchored to its own line, deliberately. The first
|
||||
# version searched the whole message for a bracketed marker as a substring,
|
||||
# and the very commit that introduced the manifest-bump step described that
|
||||
# marker in its body — so the tagger read its own documentation as an
|
||||
# instruction and skipped the release. Success, no tag, no bump, no error
|
||||
# (run 15, 2026-08-23). A marker you cannot mention without triggering is a
|
||||
# footgun, not a mechanism.
|
||||
|
||||
set -u
|
||||
|
||||
msg=$(cat)
|
||||
|
||||
if printf '%s\n' "$msg" | grep -qiE '^[[:space:]]*Skip-Release:[[:space:]]*true[[:space:]]*$'; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
exit 1
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
---
|
||||
name: debug
|
||||
description: Systematic hypothesis-first debugging. Generate 3-5 ranked hypotheses with verification steps before suggesting any fix. Use when encountering a bug, test failure, or unexpected behavior.
|
||||
---
|
||||
|
||||
# Debug
|
||||
|
||||
## Overview
|
||||
|
||||
Debugging is hypothesis generation, not fix generation. The first instinct — "try this and see if it works" — wastes time and teaches nothing. A disciplined debug session produces a small set of ranked, falsifiable hypotheses, each with a concrete verification command. The fix comes after one hypothesis is confirmed, not before.
|
||||
|
||||
**Core principle:** A hypothesis you cannot verify in one command is not a hypothesis — it is a guess.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Any test failure whose cause is not immediately obvious
|
||||
- Any production error or unexpected behavior
|
||||
- Any bug report from a user or stakeholder
|
||||
- Before reaching for a debugger or adding print statements: form hypotheses first
|
||||
|
||||
**Do not use for:**
|
||||
- Compile errors with clear messages (just fix the typo)
|
||||
- Already-diagnosed bugs where you know the cause (go straight to TDD with a regression test)
|
||||
|
||||
## Iron Laws
|
||||
|
||||
1. **Never suggest "try X and see what happens."** Every hypothesis must have a specific expected outcome if correct.
|
||||
2. **Generate 3-5 hypotheses, ordered by likelihood (most likely first).** Fewer than 3 means you stopped thinking; more than 5 means you are not prioritizing.
|
||||
3. **Diagnose only — do not fix in this skill.** The fix happens in a separate TDD cycle (load `tdd` skill) once a hypothesis is confirmed.
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Read the failure
|
||||
|
||||
Before forming hypotheses:
|
||||
- Read the full error message and stack trace, not just the headline
|
||||
- Read the file where the failure originated, around the failing line
|
||||
- If the failure is from a test, read the test and the code under test
|
||||
- Identify the **failure mode** — what actually went wrong (e.g. "nil pointer dereference in goroutine spawned by handler") not just what the error says ("runtime error")
|
||||
|
||||
### Step 2: Generate hypotheses
|
||||
|
||||
For each hypothesis, capture three things:
|
||||
|
||||
- **Mechanism:** what specific code path or state would produce this exact failure
|
||||
- **Verification:** the single command or file inspection that confirms or denies it
|
||||
- **Expected outcome if correct:** the specific output you would see
|
||||
|
||||
Order by likelihood. The most likely cause is hypothesis 1.
|
||||
|
||||
### Step 3: Output
|
||||
|
||||
Use this format:
|
||||
|
||||
```
|
||||
HYPOTHESIS 1 (likelihood: high): <mechanism in one sentence>
|
||||
VERIFY: <exact command or file:line to inspect>
|
||||
EXPECTED IF CORRECT: <specific output, value, or condition>
|
||||
|
||||
HYPOTHESIS 2 (likelihood: medium): <mechanism>
|
||||
VERIFY: <exact command>
|
||||
EXPECTED IF CORRECT: <specific output>
|
||||
|
||||
[... up to 5 ...]
|
||||
|
||||
RECOMMENDED NEXT STEP: Run VERIFY for hypothesis 1 first.
|
||||
```
|
||||
|
||||
End with the recommendation, not a fix.
|
||||
|
||||
## Worked Example
|
||||
|
||||
**Failure:**
|
||||
```
|
||||
--- FAIL: TestInvoiceParser_HandlesEmptyPDF (0.00s)
|
||||
parser_test.go:47: panic: runtime error: index out of range [0] with length 0
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
HYPOTHESIS 1 (likelihood: high): parser indexes into pages[0] before checking len(pages) > 0; empty PDFs produce a zero-page document
|
||||
VERIFY: rg -n 'pages\[0\]' internal/parser/
|
||||
EXPECTED IF CORRECT: at least one site reads pages[0] without a preceding length check
|
||||
|
||||
HYPOTHESIS 2 (likelihood: medium): the test fixture is a zero-byte file rather than a valid empty PDF; pdf library returns nil pages slice instead of empty
|
||||
VERIFY: ls -la testdata/empty.pdf && file testdata/empty.pdf
|
||||
EXPECTED IF CORRECT: file size 0 bytes or "data" rather than "PDF document"
|
||||
|
||||
HYPOTHESIS 3 (likelihood: low): a recently changed dependency reordered the page-extraction API; pages[0] now refers to metadata, not content
|
||||
VERIFY: git log --oneline -10 -- go.sum | grep -i pdf
|
||||
EXPECTED IF CORRECT: a pdf-library bump in the last few commits
|
||||
|
||||
RECOMMENDED NEXT STEP: Run VERIFY for hypothesis 1 first.
|
||||
```
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
| Anti-Pattern | Why It Fails |
|
||||
|---|---|
|
||||
| "Maybe try restarting the service" | Not a mechanism. Not falsifiable. Teaches nothing if it works. |
|
||||
| "Could be a race condition" | Mechanism without specifics. Which two operations race? On what state? |
|
||||
| "Let me add some print statements and see" | Skips hypothesis generation. Generates noise, not understanding. |
|
||||
| Single hypothesis presented as fact | If you are sure, write the regression test, do not run a debug skill. |
|
||||
| Mixing hypotheses with fix suggestions | The skill is diagnose-only. The fix is a TDD task on its hypothesis. |
|
||||
|
||||
## Brain MCP Integration
|
||||
|
||||
The brain holds prior debug sessions across the project. Use it to skip rediscovering known failure modes.
|
||||
|
||||
**At debug start:**
|
||||
- Run `brain_query` with the error message snippet + the package name. Past sessions may have logged identical or similar failures with their resolved hypotheses.
|
||||
|
||||
**After a hypothesis is confirmed:**
|
||||
- Run `brain_write` with the failure signature → confirmed mechanism. Future debug sessions on the same area get the answer immediately.
|
||||
|
||||
**Never:**
|
||||
- Run `brain_write` for an unconfirmed hypothesis. Speculation in the brain pollutes future queries.
|
||||
|
||||
### Logging
|
||||
|
||||
Call `session_log` once at the end of every phase to record the outcome.
|
||||
Pass-rate is computed downstream by the `/pass-rate` HTTP endpoint, which
|
||||
treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
|
||||
**At end of each phase:**
|
||||
- `session_log` with `{skill: "debug", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", duration_ms: <wall-clock>, project_root: "<absolute path>"}`
|
||||
|
||||
**Phases for this skill:** read-failure, generate-hypotheses, output
|
||||
|
||||
**Status semantics:**
|
||||
- `pass` — the phase's intended outcome was reached.
|
||||
- `fail` — the phase's intended outcome was NOT reached.
|
||||
- `skip` — phase was skipped intentionally.
|
||||
|
||||
**Why this matters:** the routing pod (Plan 6) reads pass-rate to decide whether to route a future call to a local model. If your skill never logs, the routing pod sees no data.
|
||||
|
||||
## Mode 2 Routing Note
|
||||
|
||||
This skill produces high-volume mechanical output (hypothesis enumeration) and is a candidate for Mode 2 routing to a local model in the future. Until Plan 6 ships the routing pod, treat as Mode 1 only. The hypothesis format and discipline are identical regardless of which model generates them.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- After a hypothesis is confirmed, load `tdd` skill — write a failing regression test that proves the bug exists, then fix it.
|
||||
- For test failures specifically caused by mock-vs-real divergence, also load `tdd/references/testing-anti-patterns.md`.
|
||||
- Load `code-review` skill if the diagnosis surfaces a structural issue (god object, shotgun surgery) rather than a pointwise bug.
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/doctor\" --quiet",
|
||||
"timeout": 5,
|
||||
"statusMessage": "Checking skills wiring..."
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/pre-task-ritual.sh\"",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/secret-guard.sh\"",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
# Surfaces rule 0 on every prompt so the pre-task ritual is visible in context.
|
||||
echo "Rule 0 (non-negotiable): brain_query → load skill → failing test → state success criterion"
|
||||
Executable
+125
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env bash
|
||||
# PreToolUse hook (Bash matcher) — hard-blocks command patterns that reveal
|
||||
# secret values into the transcript, rather than relying on remembering an
|
||||
# existence-only check every time.
|
||||
#
|
||||
# Triggered by two real leaks in one session (2026-07-30):
|
||||
# 1. `op item get <name> --format json` — JSON mode has NO masking, unlike
|
||||
# the human-readable table view (`op item get <name>` alone masks
|
||||
# concealed fields with bullets by default). Printed a live Gitea MCP
|
||||
# token into the transcript.
|
||||
# 2. `env | grep -i gitea` (infra#228, 2026-07-27) — same shape: an
|
||||
# inspection command that dumps values instead of checking existence.
|
||||
#
|
||||
# Policy: block ALL direct reads of secret material via these command
|
||||
# shapes, unconditionally, regardless of flags. Existence/rotation must go
|
||||
# through a wrapper script (e.g. infra's scripts/op-safe.sh, scripts/rotate-
|
||||
# *.sh) that strips values before anything reaches stdout — those scripts
|
||||
# call the same underlying commands internally, but as a subprocess of the
|
||||
# script, never as a literal Bash tool call the model composes and can typo.
|
||||
#
|
||||
# Reads PreToolUse hook JSON on stdin, decides allow/deny for the Bash tool.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
INPUT="$(cat)"
|
||||
TOOL_NAME="$(printf '%s' "$INPUT" | jq -r '.tool_name // empty')"
|
||||
[ "$TOOL_NAME" = "Bash" ] || { printf '%s' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}'; exit 0; }
|
||||
|
||||
CMD="$(printf '%s' "$INPUT" | jq -r '.tool_input.command // empty')"
|
||||
|
||||
deny() {
|
||||
local reason="$1"
|
||||
jq -n --arg reason "$reason" \
|
||||
'{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $reason}, systemMessage: $reason}'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# 1Password CLI raw reads — block unconditionally, any flags.
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|\s)op\s+item\s+get\b'; then
|
||||
deny "Blocked: 'op item get' prints secret values to stdout (JSON mode has no masking at all; even table mode can leak via --fields/--reveal). Use a wrapper that strips .fields[].value before output (e.g. scripts/op-safe.sh exists|meta), or op item edit to WRITE without ever printing the value."
|
||||
fi
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|\s)op\s+item\s+list\b'; then
|
||||
deny "Blocked: 'op item list' can include concealed field previews. Use a wrapper that filters to titles only (e.g. scripts/op-safe.sh list)."
|
||||
fi
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|\s)op\s+read\b'; then
|
||||
deny "Blocked: 'op read' prints the raw secret value directly. Consume it inside a subprocess only (op run -- <cmd>, or a script that never echoes/captures it to stdout)."
|
||||
fi
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|\s)op\s+document\s+get\b'; then
|
||||
deny "Blocked: 'op document get' prints document contents (may contain secrets) to stdout. Use a wrapper script instead."
|
||||
fi
|
||||
|
||||
# Raw env/secret-file dumps (infra#228/#229 root cause).
|
||||
#
|
||||
# `env` is a dump only when nothing but options and VAR=value assignments
|
||||
# follow it. `env -u VAR cmd` and `env FOO=bar cmd` EXEC a command with a
|
||||
# modified environment and print nothing themselves — piping those into grep
|
||||
# filters the command's own output, not the environment (#25). The earlier
|
||||
# pattern matched any `env` token followed anywhere later by a pipe into
|
||||
# grep, which blocked the documented 1Password write path
|
||||
# (`env -u OP_SERVICE_ACCOUNT_TOKEN op item create`) and cost a workaround.
|
||||
# Denying only the "no command word follows" shape also catches `env FOO=bar`
|
||||
# with no command, which the two previous rules let through.
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|[[:space:]])env([[:space:]]+-[iu][[:space:]]*[A-Za-z_][A-Za-z0-9_]*|[[:space:]]+-[iu]|[[:space:]]+[A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*)*[[:space:]]*($|[|;&])'; then
|
||||
deny "Blocked: this 'env' prints every variable's value, including secrets (no command word follows it, so it dumps rather than execs). Use an existence-only check: [ -n \"\$VAR\" ] && echo set. Note 'env -u VAR cmd' and 'env FOO=bar cmd' are allowed — they run a command."
|
||||
fi
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|\s)printenv\b'; then
|
||||
deny "Blocked: printenv dumps all env values. Use: [ -n \"\$VAR\" ] && echo set"
|
||||
fi
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|\s)cat\b[^;&|]*\.env'; then
|
||||
deny "Blocked: cat of a .env file prints secret values. Use: grep -c '=' file.env (count only) or [ -s file.env ] && echo present"
|
||||
fi
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|\s)cat\b[^;&|]*(\.llmkeys|\.op-env|\.op-agent-write\.env)\b'; then
|
||||
deny "Blocked: cat of a known secrets file prints raw values. Use: grep -o '^[A-Z_]*=' file (key names only, never the value)."
|
||||
fi
|
||||
|
||||
# kubectl secrets — -o yaml/json prints base64 (trivially reversible).
|
||||
if printf '%s' "$CMD" | grep -Eqi '(^|[;&|]|\s)kubectl\b[^;&|]*\bget\s+secrets?\b[^;&|]*(-o|--output)[[:space:]=]*(yaml|json)'; then
|
||||
deny "Blocked: 'kubectl get secret -o yaml/json' prints base64-encoded values (trivially reversible, same as plaintext). Use 'kubectl describe secret <name>' (shows keys + byte lengths only, never values) for existence checks."
|
||||
fi
|
||||
|
||||
# Gitea app.ini — mixes plain config ([queue]/[indexer]/[repository]) with
|
||||
# live secrets ([security].INTERNAL_TOKEN/SECRET_KEY, [oauth2].JWT_SECRET,
|
||||
# [server].LFS_JWT_SECRET) in the SAME file, auto-generated on install and
|
||||
# not git/SOPS-tracked. A context-range grep (-A/-B/-C) doesn't respect
|
||||
# section boundaries and silently pulls a secret line into stdout even when
|
||||
# targeting an unrelated section. Root cause of a real leak, infra sprint
|
||||
# 2026-08-04 (`kubectl exec ... cat app.ini | grep -A15 "^\[queue\]"` pulled
|
||||
# through into [oauth2].JWT_SECRET).
|
||||
# Tight on purpose: requires "cat" immediately followed by a bare path-shaped
|
||||
# token ending in app.ini (no intervening whitespace) so this only fires on
|
||||
# an actual invocation ('cat /data/gitea/conf/app.ini', 'cat app.ini') and
|
||||
# never on prose that merely mentions both words, e.g. a commit message
|
||||
# describing this exact guard (that false-positived once while writing the
|
||||
# fix — commands are matched as raw strings, heredoc bodies included).
|
||||
if printf '%s' "$CMD" | grep -Eq '\bcat[[:space:]]+[A-Za-z0-9_./-]*app\.ini\b'; then
|
||||
deny "Blocked: cat of Gitea's app.ini prints secrets mixed into the same file ([security]/[oauth2]/[server].LFS_JWT_SECRET). Use exact-key checks: grep -c '^KEY = ' app.ini (existence only) — never cat the whole file."
|
||||
fi
|
||||
if printf '%s' "$CMD" | grep -Eq '\bgrep\b[^;&|]*-[A-Za-z]*[ABC][A-Za-z]*[[:space:]]*[0-9][^;&|]*app\.ini\b'; then
|
||||
deny "Blocked: grep -A/-B/-C context flags against app.ini can bleed past section boundaries into [security]/[oauth2]/[server] secrets, even when targeting an unrelated section (this is exactly how the 2026-08-04 leak happened). Use an exact anchor instead: grep '^KEY = ' app.ini, or bound to one section with awk '/^\\[section\\]/,/^\\[/' and confirm the section has no secret keys first."
|
||||
fi
|
||||
|
||||
# sops decrypt output inspected directly — infra sweep-sprint incident,
|
||||
# 2026-08-05: `sops -d ntfy-tokens.enc.yaml > /tmp/plain.yaml` (safe,
|
||||
# redirected to a file) immediately followed by `cat /tmp/plain.yaml | head`
|
||||
# in the SAME command block printed a live ntfy token into the transcript.
|
||||
# Re-encrypting a secret (e.g. switching a file to data-only encryption per
|
||||
# infra#177's pattern) requires decrypting it locally at some point — that
|
||||
# redirect-to-file step alone is fine, the leak is any print command touching
|
||||
# the plaintext afterward. Block the combination unconditionally rather than
|
||||
# trying to track which file a decrypt wrote to across separate tool calls.
|
||||
if printf '%s' "$CMD" | grep -Eq '\bsops\b[^;&|]*(-d\b|--decrypt\b|[[:space:]]decrypt\b)' \
|
||||
&& printf '%s' "$CMD" | grep -Eq '\b(cat|head|tail|less|more|bat|od|xxd)\b'; then
|
||||
deny "Blocked: this command decrypts a sops-encrypted file AND runs a print command (cat/head/tail/etc) in the same invocation — that's exactly the 2026-08-05 ntfy-token leak shape. Decrypt to a temp file (sops -d file > /tmp/x, fine on its own), do whatever transform is needed WITHOUT printing it (e.g. sops -e --encrypted-regex '^(data|stringData)\$' /tmp/x > newfile), then shred -u the temp file. Never cat/head/tail a sops-decrypted file, even to 'just check a few lines'."
|
||||
fi
|
||||
|
||||
# base64 transform of a secret-shaped env var — the documented 2026-06-11
|
||||
# 'defeats op run masking' bypass.
|
||||
if printf '%s' "$CMD" | grep -Eqi '\$\{?[A-Za-z0-9_]*(TOKEN|SECRET|PASSWORD|API_KEY|_KEY|DSN|CREDENTIAL|PAT)[A-Za-z0-9_]*\}?[^;&|]*\|[^;&|]*base64'; then
|
||||
deny "Blocked: piping a secret-shaped variable through base64 to inspect it. base64 is an encoding, not masking — op run's own masking only recognizes the raw value, so this is a known bypass (2026-06-11 incident). Never transform a secret to look at it."
|
||||
fi
|
||||
if printf '%s' "$CMD" | grep -Eqi 'base64[^;&|]*<<<\s*"?\$\{?[A-Za-z0-9_]*(TOKEN|SECRET|PASSWORD|API_KEY|_KEY|DSN|CREDENTIAL|PAT)'; then
|
||||
deny "Blocked: base64 <<< of a secret-shaped variable. Same bypass as above — never transform a secret to inspect it."
|
||||
fi
|
||||
|
||||
jq -n '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "allow"}}'
|
||||
+227
-70
@@ -2,27 +2,84 @@
|
||||
# install.sh — bootstrap installer for the skills library.
|
||||
#
|
||||
# Usage (one-liner, hosts without Task):
|
||||
# curl -fsSL https://gitea.d-ma.be/mathias/skills/raw/branch/main/install.sh | bash
|
||||
# curl -fsSL https://git.d-ma.be/mathias/skills/raw/branch/main/install.sh | bash
|
||||
#
|
||||
# Pinned to a specific tag:
|
||||
# SKILLS_REF=v0.1.0 bash install.sh
|
||||
# SKILLS_REF=v0.4.0 bash install.sh
|
||||
#
|
||||
# Idempotent: re-running pulls the latest changes for the configured ref
|
||||
# (default: main) and re-wires symlinks. Existing correct links are
|
||||
# left alone; mismatched ones are replaced.
|
||||
# (default: main) and re-wires the links.
|
||||
#
|
||||
# Claude Code is NOT wired here. It installs this repo as a plugin from the
|
||||
# marketplace this repo also hosts:
|
||||
#
|
||||
# /plugin marketplace add https://git.d-ma.be/mathias/skills.git
|
||||
# /plugin install skills@mathias
|
||||
#
|
||||
# That path carries the hooks and MCP server definitions too, which symlinks
|
||||
# cannot. This script covers the harnesses with no plugin system: Crush, Pi,
|
||||
# OpenCode, and Antigravity.
|
||||
#
|
||||
# Wiring model — one managed directory, one link per harness:
|
||||
#
|
||||
# ~/.agents/skills/tdd -> $CHECKOUT_DIR/skills/tdd (canonical; Pi reads the dir directly)
|
||||
# ~/.agents/skills/xlsx -> $OTHER_SOURCE/xlsx
|
||||
# ~/.config/crush/skills -> ~/.agents/skills
|
||||
# ~/.config/opencode/skills -> ~/.agents/skills
|
||||
#
|
||||
# Antigravity has no symlink-directory discovery — it reads a path-entries
|
||||
# JSON instead (~/.gemini/config/skills.json:
|
||||
# {"entries":[{"path":"..."}]}). One entry points at ~/.agents/skills, so it
|
||||
# sees exactly the same surfaces-filtered, collision-resolved set every other
|
||||
# harness does. Requires jq; skipped with a warning if jq is unavailable —
|
||||
# every other target in this script stays dependency-free on purpose.
|
||||
#
|
||||
# ~/.agents/skills was itself a link to this checkout until #27. That encoded
|
||||
# an assumption nobody had stated — that this checkout is the ONLY source of
|
||||
# skills on the host — and on flamingo the only way to install this library
|
||||
# was to displace Anthropic's official set, which lived in Crush's directory.
|
||||
# A real directory of per-skill links serves several sources at once: total
|
||||
# links are N + one per harness, still not N x harnesses (#23's actual point).
|
||||
#
|
||||
# Extra sources come from SKILLS_EXTRA_SOURCES, a colon-separated list of
|
||||
# directories each holding <skill>/SKILL.md. The checkout is always first and
|
||||
# always wins a name collision — but the collision is logged, never resolved
|
||||
# in silence, because quietly picking one is how stale content wins.
|
||||
#
|
||||
# CHECKOUT_DIR deliberately defaults OUTSIDE any file-synced or
|
||||
# cross-platform-shared directory. Do not "fix" it to point into ~/dev: on a
|
||||
# fleet whose workspace is shared between macOS (/Users/...) and Linux
|
||||
# (/home/...), an absolute link stored there is broken on one side by
|
||||
# construction. See mathias/skills#23.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
REPO_URL="${SKILLS_REPO_URL:-https://gitea.d-ma.be/mathias/skills.git}"
|
||||
REPO_URL="${SKILLS_REPO_URL:-https://git.d-ma.be/mathias/skills.git}"
|
||||
REF="${SKILLS_REF:-main}"
|
||||
CHECKOUT_DIR="${SKILLS_CHECKOUT_DIR:-$HOME/.local/share/skills}"
|
||||
CLAUDE_GLOBAL_DIR="${CLAUDE_SKILLS_DIR:-$HOME/.claude/skills}"
|
||||
AGENTS_DIR="${AGENTS_SKILLS_DIR:-$HOME/.agents/skills}"
|
||||
CRUSH_DIR="${CRUSH_SKILLS_DIR:-$HOME/.config/crush/skills}"
|
||||
ANTIGRAVITY_DIR="${ANTIGRAVITY_SKILLS_DIR:-$HOME/.gemini/antigravity/skills}"
|
||||
OPENCODE_DIR="${OPENCODE_SKILLS_DIR:-$HOME/.config/opencode/skills}"
|
||||
ANTIGRAVITY_SKILLS_JSON="${ANTIGRAVITY_SKILLS_JSON:-$HOME/.gemini/config/skills.json}"
|
||||
EXTRA_SOURCES="${SKILLS_EXTRA_SOURCES:-}"
|
||||
# Overridable so the jq-absent branch is testable on a host that has jq. That
|
||||
# branch is a contract, not a fallback: jq is optional here while every other
|
||||
# target in this script is dependency-free.
|
||||
JQ="${SKILLS_JQ:-jq}"
|
||||
# Recorded beside the managed directory rather than inside it: a stray file in
|
||||
# there would look like a skill to every harness reading the dir.
|
||||
SOURCES_MANIFEST="$(dirname "$AGENTS_DIR")/$(basename "$AGENTS_DIR")-sources"
|
||||
|
||||
log() { printf '[skills] %s\n' "$*"; }
|
||||
|
||||
ensure_checkout() {
|
||||
# Wiring an existing working checkout (task install) must not fetch or
|
||||
# move HEAD — that would discard in-progress work.
|
||||
if [ "${SKILLS_SKIP_FETCH:-}" = "1" ]; then
|
||||
[ -d "$CHECKOUT_DIR/skills" ] || { log "no skills/ under $CHECKOUT_DIR"; exit 1; }
|
||||
log "using $CHECKOUT_DIR as-is (SKILLS_SKIP_FETCH=1)"
|
||||
return
|
||||
fi
|
||||
if [ -d "$CHECKOUT_DIR/.git" ]; then
|
||||
log "updating $CHECKOUT_DIR"
|
||||
git -C "$CHECKOUT_DIR" fetch --tags --quiet
|
||||
@@ -39,86 +96,186 @@ ensure_checkout() {
|
||||
fi
|
||||
}
|
||||
|
||||
list_skills() {
|
||||
# Every top-level entry that isn't a known meta file.
|
||||
(cd "$CHECKOUT_DIR" && ls -1) | grep -Ev '^(Taskfile\.yml|install\.sh|README\.md|SKILLS_INDEX\.md|\.gitea|\.git)$' || true
|
||||
count_skills() {
|
||||
find "$CHECKOUT_DIR/skills" -mindepth 2 -maxdepth 2 -name SKILL.md 2>/dev/null | wc -l | tr -d ' '
|
||||
}
|
||||
|
||||
link_skill() {
|
||||
# link_skill <target_dir> <skill_name>
|
||||
local target_dir="$1"
|
||||
local skill="$2"
|
||||
local target="$CHECKOUT_DIR/$skill"
|
||||
local link="$target_dir/$skill"
|
||||
|
||||
if [ -L "$link" ] || [ -e "$link" ]; then
|
||||
local current
|
||||
current=$(readlink "$link" 2>/dev/null || true)
|
||||
if [ "$current" = "$target" ]; then
|
||||
return
|
||||
# sources — every configured source directory, primary first, one per line.
|
||||
sources() {
|
||||
printf '%s\n' "$CHECKOUT_DIR/skills"
|
||||
[ -n "$EXTRA_SOURCES" ] || return 0
|
||||
# printf '%s\n' deliberately: without the trailing newline `read` hits EOF
|
||||
# on the final entry and the loop body never runs for it.
|
||||
printf '%s\n' "$EXTRA_SOURCES" | tr ':' '\n' | while IFS= read -r src; do
|
||||
[ -n "$src" ] || continue
|
||||
if [ -d "$src" ]; then
|
||||
printf '%s\n' "$src"
|
||||
else
|
||||
log "extra source $src does not exist — skipping"
|
||||
fi
|
||||
rm -rf "$link"
|
||||
done
|
||||
}
|
||||
|
||||
# prepare_agents_dir — the canonical location is a real directory now. A host
|
||||
# still on the single-link wiring is migrated in place.
|
||||
prepare_agents_dir() {
|
||||
if [ -L "$AGENTS_DIR" ]; then
|
||||
log "migrating $AGENTS_DIR from the single-link wiring to a per-skill directory"
|
||||
rm -f "$AGENTS_DIR"
|
||||
elif [ -e "$AGENTS_DIR" ] && [ ! -d "$AGENTS_DIR" ]; then
|
||||
log "REFUSING to replace $AGENTS_DIR — it exists and is not a directory"
|
||||
return 1
|
||||
fi
|
||||
mkdir -p "$AGENTS_DIR"
|
||||
}
|
||||
|
||||
# wire_skills — one symlink per skill, from every configured source.
|
||||
wire_skills() {
|
||||
local src_list desired name src dir link target
|
||||
src_list="$(mktemp)"
|
||||
sources > "$src_list"
|
||||
|
||||
desired=""
|
||||
while IFS= read -r src; do
|
||||
[ -d "$src" ] || continue
|
||||
for dir in "$src"/*/; do
|
||||
[ -f "$dir/SKILL.md" ] || continue
|
||||
name="$(basename "$dir")"
|
||||
target="${dir%/}"
|
||||
|
||||
# A skill declares its surfaces; this installer serves exactly one of
|
||||
# them. A chat-only skill linked into Crush can never fire and competes
|
||||
# for selection with ones that can (#29). A source with no declaration
|
||||
# is foreign — Anthropic's official set has no reason to know this
|
||||
# convention — so silence means "link it".
|
||||
surfaces="$(sed -n 's/^surfaces:[[:space:]]*//p' "$dir/SKILL.md" | head -1)"
|
||||
if [ -n "$surfaces" ] && ! printf '%s' "$surfaces" | tr -d '[]' | tr ',' ' ' | grep -qw library; then
|
||||
log "skipping $name — surfaces: $surfaces does not include the library"
|
||||
continue
|
||||
fi
|
||||
|
||||
if printf '%s' "$desired" | grep -qx -- "$name"; then
|
||||
log "COLLISION: $name is offered by $target too; keeping $AGENTS_DIR/$name -> $(readlink "$AGENTS_DIR/$name" 2>/dev/null || echo '?')"
|
||||
continue
|
||||
fi
|
||||
|
||||
link="$AGENTS_DIR/$name"
|
||||
if [ -L "$link" ]; then
|
||||
if [ "$(readlink "$link")" = "$target" ]; then
|
||||
desired="$desired$name
|
||||
"
|
||||
continue
|
||||
fi
|
||||
rm -f "$link"
|
||||
elif [ -e "$link" ]; then
|
||||
log "unmanaged: $link is not a symlink — left in place; move it aside to let $target take the name"
|
||||
continue
|
||||
fi
|
||||
ln -s "$target" "$link"
|
||||
desired="$desired$name
|
||||
"
|
||||
done
|
||||
done < "$src_list"
|
||||
rm -f "$src_list"
|
||||
|
||||
# Removing a skill from a source must remove its link, or the previous
|
||||
# generation's problem (links resolving to nothing, invisible to git)
|
||||
# returns in a new shape.
|
||||
for link in "$AGENTS_DIR"/*; do
|
||||
[ -e "$link" ] || [ -L "$link" ] || continue
|
||||
name="$(basename "$link")"
|
||||
if [ ! -L "$link" ]; then
|
||||
log "unmanaged: $link is not a symlink and no source offers it — left in place"
|
||||
continue
|
||||
fi
|
||||
printf '%s' "$desired" | grep -qx -- "$name" && continue
|
||||
rm -f "$link"
|
||||
log "pruned $name — no configured source offers it any more"
|
||||
done
|
||||
|
||||
sources > "$SOURCES_MANIFEST"
|
||||
# Reported through a global, not stdout: wire_skills logs collisions and
|
||||
# unmanaged entries as it goes, and capturing its stdout for a count would
|
||||
# swallow exactly the warnings this change exists to surface.
|
||||
LINKED_COUNT=$(printf '%s' "$desired" | grep -c . || true)
|
||||
}
|
||||
|
||||
# link_dir <link_path> <target_path>
|
||||
# Replaces whatever is there — including a directory left behind by the old
|
||||
# per-skill wiring — with a single symlink.
|
||||
link_dir() {
|
||||
local link="$1" target="$2"
|
||||
if [ -L "$link" ]; then
|
||||
[ "$(readlink "$link")" = "$target" ] && return
|
||||
rm -f "$link"
|
||||
elif [ -d "$link" ]; then
|
||||
# Refuse to discard a directory holding anything but symlinks: that
|
||||
# would be someone's real skills, not our old wiring.
|
||||
if find "$link" -mindepth 1 -maxdepth 1 ! -type l | grep -q .; then
|
||||
log "REFUSING to replace $link — it holds non-symlink entries; move them and re-run"
|
||||
return 1
|
||||
fi
|
||||
find "$link" -mindepth 1 -maxdepth 1 -type l -delete
|
||||
rmdir "$link"
|
||||
elif [ -e "$link" ]; then
|
||||
rm -f "$link"
|
||||
fi
|
||||
mkdir -p "$(dirname "$link")"
|
||||
ln -s "$target" "$link"
|
||||
log "linked $link → $target"
|
||||
}
|
||||
|
||||
wire_claude_global() {
|
||||
mkdir -p "$CLAUDE_GLOBAL_DIR"
|
||||
while IFS= read -r skill; do
|
||||
[ -n "$skill" ] || continue
|
||||
link_skill "$CLAUDE_GLOBAL_DIR" "$skill"
|
||||
done < <(list_skills)
|
||||
}
|
||||
|
||||
wire_crush() {
|
||||
# Crush reads skills from ~/.config/crush/skills/<name>/SKILL.md.
|
||||
# Pre-creating the dir is cheap even when Crush isn't installed.
|
||||
mkdir -p "$CRUSH_DIR"
|
||||
while IFS= read -r skill; do
|
||||
[ -n "$skill" ] || continue
|
||||
link_skill "$CRUSH_DIR" "$skill"
|
||||
done < <(list_skills)
|
||||
}
|
||||
|
||||
# wire_antigravity — register $AGENTS_DIR in Antigravity's skills.json.
|
||||
# Merges rather than overwrites: skills.json is a documented user-editable
|
||||
# config (json_configs.md), so a hand-added entry (e.g. a personal skills
|
||||
# dir) must survive a re-run untouched.
|
||||
wire_antigravity() {
|
||||
# Antigravity (Google's VS Code extension) reads global skills from
|
||||
# ~/.gemini/antigravity/skills/<name>/SKILL.md. Our SKILL.md files
|
||||
# already carry the required `name` + `description` YAML frontmatter,
|
||||
# so symlinks are sufficient — no manifest translation step.
|
||||
mkdir -p "$ANTIGRAVITY_DIR"
|
||||
while IFS= read -r skill; do
|
||||
[ -n "$skill" ] || continue
|
||||
link_skill "$ANTIGRAVITY_DIR" "$skill"
|
||||
done < <(list_skills)
|
||||
}
|
||||
if ! command -v "$JQ" >/dev/null 2>&1; then
|
||||
log "Antigravity: jq not found — skipping (needed to merge $ANTIGRAVITY_SKILLS_JSON safely)"
|
||||
return
|
||||
fi
|
||||
|
||||
wire_claude_repo() {
|
||||
# Only wire per-repo when invoked from inside a git repo and it isn't
|
||||
# the skills repo itself.
|
||||
if ! git rev-parse --show-toplevel >/dev/null 2>&1; then
|
||||
local existing already updated
|
||||
mkdir -p "$(dirname "$ANTIGRAVITY_SKILLS_JSON")"
|
||||
|
||||
if [ -s "$ANTIGRAVITY_SKILLS_JSON" ]; then
|
||||
existing="$(cat "$ANTIGRAVITY_SKILLS_JSON")"
|
||||
else
|
||||
existing='{}'
|
||||
fi
|
||||
|
||||
already="$(printf '%s' "$existing" | "$JQ" --arg p "$AGENTS_DIR" \
|
||||
'[.entries // [] | .[] | select(.path == $p)] | length' 2>/dev/null)" || {
|
||||
log "Antigravity: $ANTIGRAVITY_SKILLS_JSON is not valid JSON — leaving it untouched"
|
||||
return 1
|
||||
}
|
||||
|
||||
if [ "$already" -gt 0 ]; then
|
||||
log "Antigravity: $AGENTS_DIR already registered in $ANTIGRAVITY_SKILLS_JSON"
|
||||
return
|
||||
fi
|
||||
local repo
|
||||
repo=$(git rev-parse --show-toplevel)
|
||||
if [ "$repo" = "$CHECKOUT_DIR" ]; then
|
||||
return
|
||||
fi
|
||||
local target_dir="$repo/.claude/skills"
|
||||
mkdir -p "$target_dir"
|
||||
while IFS= read -r skill; do
|
||||
[ -n "$skill" ] || continue
|
||||
link_skill "$target_dir" "$skill"
|
||||
done < <(list_skills)
|
||||
|
||||
updated="$(printf '%s' "$existing" | "$JQ" --arg p "$AGENTS_DIR" \
|
||||
'.entries = ((.entries // []) + [{path: $p}])')"
|
||||
printf '%s\n' "$updated" > "$ANTIGRAVITY_SKILLS_JSON"
|
||||
log "Antigravity: registered $AGENTS_DIR in $ANTIGRAVITY_SKILLS_JSON"
|
||||
}
|
||||
|
||||
main() {
|
||||
ensure_checkout
|
||||
wire_claude_global
|
||||
wire_claude_repo
|
||||
wire_crush
|
||||
|
||||
# Canonical location. Pi reads ~/.agents/skills directly, so it needs no
|
||||
# harness-specific link of its own.
|
||||
prepare_agents_dir
|
||||
LINKED_COUNT=0
|
||||
wire_skills
|
||||
|
||||
link_dir "$CRUSH_DIR" "$AGENTS_DIR"
|
||||
link_dir "$OPENCODE_DIR" "$AGENTS_DIR"
|
||||
wire_antigravity
|
||||
log "done — $(list_skills | wc -l | tr -d ' ') skill(s) wired at ref=$REF"
|
||||
|
||||
log "done — $LINKED_COUNT skill(s) linked from $(sources | wc -l | tr -d ' ') source(s), ref=$REF"
|
||||
log "Claude Code: install the plugin instead — /plugin marketplace add $REPO_URL"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
---
|
||||
name: adr
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Architecture Decision Records — house format, and how to record a decision you cannot make yet"
|
||||
use_when: "Recording an architectural decision; revisiting one; or deciding between options where the right answer genuinely is not knowable yet"
|
||||
description: Write an Architecture Decision Record in this estate's format — YAML frontmatter, Status/Context/Decision/Consequences/Validation — including the case where the tradeoff is genuinely context-dependent and forcing a resolution would be worse than preserving the tension. Use when recording or superseding an architectural decision, or when a decision keeps getting re-litigated because nobody wrote down why.
|
||||
---
|
||||
|
||||
# ADR
|
||||
|
||||
## Overview
|
||||
|
||||
An ADR is the *record* of a decision — the artifact someone reads in eight months when
|
||||
they are about to undo it without knowing why it exists. It does not confer the decision;
|
||||
a person with authority does that, and this skill never is that person.
|
||||
|
||||
Two things make one useful, and neither is the prose quality: a **format consistent
|
||||
enough to grep across repos**, and an honest account of **what was not decided**.
|
||||
|
||||
## Before you write
|
||||
|
||||
Both of these change what goes in the ADR, so they are not cross-references, they are
|
||||
steps:
|
||||
|
||||
1. **`lineage`** — was this decided before and reversed? The reason it was dropped is
|
||||
usually the most valuable sentence in your Context, and if an earlier ADR exists,
|
||||
yours supersedes it rather than ignoring it.
|
||||
2. **`grill-me`** (Full Grill) — find the hole now. It is cheaper here than in the
|
||||
Consequences section of the ADR that supersedes yours.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Any choice where a reasonable alternative existed and was not taken
|
||||
- Superseding or amending an earlier ADR (never edit the old one — see Status)
|
||||
- A decision that keeps getting re-litigated, which means the reasoning was never recorded
|
||||
- A tradeoff that is genuinely context-dependent — see *Preserving a productive tension*
|
||||
|
||||
**Do not use for:** implementation choices with no alternative worth naming, or anything
|
||||
a code comment answers. An ADR per function is an ADR nobody reads.
|
||||
|
||||
## The format
|
||||
|
||||
**Where it goes:** `docs/adr/NNNN-kebab-slug.md`, zero-padded to four digits, numbered
|
||||
sequentially within the repo. Frontmatter you cannot locate is not greppable, and half
|
||||
the value of the format is that `docs/adr/*` is a known path in every repo here.
|
||||
|
||||
**The number is repo-local.** `cad` ADR-0002 and `infra` ADR-0002 are different
|
||||
documents. When referring across repos — including in `supersedes` — qualify it:
|
||||
`cad#0002`. Within a repo the bare number is fine.
|
||||
|
||||
Frontmatter first. It exists so the corpus is machine-readable — "which ADRs does 0004
|
||||
supersede", "what is still `proposed`" — and a bespoke header block, however well
|
||||
written, cannot answer those.
|
||||
|
||||
```markdown
|
||||
---
|
||||
adr: 0004
|
||||
title: <the decision, as a sentence — not "database choice">
|
||||
status: proposed | accepted | superseded | amended
|
||||
date: 2026-08-29
|
||||
deciders: <who accepted it, by name — or "pending: <name>" (QUOTED) while proposed>
|
||||
supersedes: <adr number, or null>
|
||||
---
|
||||
|
||||
# ADR-0004 — <same title>
|
||||
|
||||
## Status
|
||||
|
||||
**The frontmatter is authoritative for status and date.** This section exists for the one
|
||||
thing the frontmatter cannot hold: *why* it moved — what superseded it and on what
|
||||
evidence, or what accepting it was contingent on. If it would only restate the YAML,
|
||||
delete it.
|
||||
|
||||
## Context
|
||||
|
||||
The forces. What is true that makes this a decision rather than a default — constraints,
|
||||
the failure that prompted it, what was tried. Name the unknowns explicitly; a decision
|
||||
made under uncertainty is not weaker for saying so, it is auditable.
|
||||
|
||||
## Decision
|
||||
|
||||
One sentence of what was decided, then why *this* option rather than the named
|
||||
alternatives. Address the strongest case against, not the weakest.
|
||||
|
||||
## Consequences
|
||||
|
||||
**Positive:** what this buys.
|
||||
|
||||
**Negative / watch:** what it costs, and the specific thing to watch that would tell you
|
||||
it was wrong. "Some added complexity" is not a consequence; "the event schema is now the
|
||||
coupling surface between cad and every executor — version it deliberately" is.
|
||||
|
||||
## Validation
|
||||
|
||||
How you will know. A link to the experiment or the metric that proves or kills it, and
|
||||
the condition that fires a revisit. An ADR with no validation section is a preference
|
||||
with a template around it.
|
||||
```
|
||||
|
||||
### The frontmatter must actually parse
|
||||
|
||||
It exists to be machine-read, so a block that does not load is worse than no block at
|
||||
all: it drops that ADR silently out of every "what is still open?" query, while looking
|
||||
correct. Two shapes this template used to suggest are invalid YAML, and both were found
|
||||
live in the estate on 2026-09-05 — `openbanking-api` ADR-0001 and `infra` ADR-0019, each
|
||||
copied verbatim from here:
|
||||
|
||||
| Wrong | Why | Right |
|
||||
|---|---|---|
|
||||
| `supersedes: -` | a bare dash is a YAML *sequence entry*, not a string | `supersedes: null` |
|
||||
| `deciders: pending: Mathias` | the second, unquoted colon reads as a nested mapping | `deciders: "pending: Mathias"` |
|
||||
|
||||
Check before committing:
|
||||
|
||||
```sh
|
||||
python3 -c "import yaml,sys;yaml.safe_load(open(sys.argv[1]).read().split('---')[1]);print('ok')" docs/adr/0004-*.md
|
||||
```
|
||||
|
||||
## Preserving a productive tension
|
||||
|
||||
Some tradeoffs are not unresolved because nobody thought hard enough. They are
|
||||
context-dependent, the context is not settled, and picking now means picking blind.
|
||||
Forcing resolution there produces a confident record that is wrong half the time.
|
||||
|
||||
Record the tension instead, in the Decision section:
|
||||
|
||||
```markdown
|
||||
## Decision
|
||||
|
||||
Provisional: **<option A>**, on this reasoning: <what makes it safe to pick now>.
|
||||
|
||||
<The strongest case for the option you did NOT take, and why it does not win today. The
|
||||
plain format demands this and a preserved tension does not get an exemption — the whole
|
||||
point is that the loser is still live.>
|
||||
|
||||
### The tension, preserved
|
||||
|
||||
- **Option A** — <what it assumes, what it costs>
|
||||
- **Option B** — <what it assumes, what it costs>
|
||||
|
||||
**What we do not know:** <the variable that decides it>
|
||||
|
||||
**Preservation strategy:** <what we build now so BOTH stay reachable. This is the
|
||||
technical content of the ADR, not a one-liner — enumerate it. It is usually the part both
|
||||
options need anyway, which is often most of the work: the schema, the interface seam, the
|
||||
idempotency key. Name each piece and say which option it keeps alive.>
|
||||
|
||||
**Resolution triggers:** <plural, and one per unknown. Two independent unknowns do not
|
||||
collapse into one condition, and a trigger may exist that neither unknown implies.>
|
||||
```
|
||||
|
||||
Two rules keep this from becoming an excuse:
|
||||
|
||||
1. **A preserved tension still ships a decision.** "We will decide later" is not one.
|
||||
Prefer the option whose correctness does not depend on the unknown, say so, and mark
|
||||
it provisional.
|
||||
|
||||
**When no such option exists** — and often none does, because a tension is productive
|
||||
precisely when both options are hostage to the same unknown — do not manufacture a
|
||||
reason that one of them is. That reads as reasoned and will not be re-examined, which
|
||||
makes it worse than an honest arbitrary pick. Fall back, in order: the option that is
|
||||
cheaper to reverse; the one with the lower switching cost given your preservation
|
||||
strategy; the one already built. Then **say that is why you picked it.** "Chosen
|
||||
because it is the cheaper mistake" is a real justification and an auditable one.
|
||||
2. **The resolution trigger must be observable by someone who is not you.** "When it
|
||||
becomes a problem" is not a trigger. "When executor count passes five and they are all
|
||||
long-lived services in one cluster" is. A trigger nobody can evaluate is a decision
|
||||
that quietly becomes permanent.
|
||||
|
||||
`cad`'s ADR-0001 does this informally under *"Known refinements (recorded, deliberately
|
||||
not built yet)"* — sovereignty deferred to a 3-class model *"until a client actually opts
|
||||
into an EU provider"*. That clause is the pattern: option, cost, and the event that
|
||||
forces the choice.
|
||||
|
||||
## Status discipline
|
||||
|
||||
- **Never edit an accepted ADR to change its decision.** Write a new one and set
|
||||
`supersedes`. The record of what was believed, and when, is the whole value.
|
||||
- **Amend** for corrections that do not change the decision (a broken link, a clarified
|
||||
consequence). Note the amendment inline with its date.
|
||||
- **`proposed` is not a parking space.** An ADR that sits proposed for a month *with no
|
||||
named decider* is a decision nobody is making; either accept it provisionally or close
|
||||
it as declined. With a named decider it is a decision waiting on a person, which is a
|
||||
different thing and is chased rather than closed.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
| Anti-pattern | Why it fails |
|
||||
|---|---|
|
||||
| Consequences that are all positive | Then it was not a decision, it was an announcement |
|
||||
| "We chose X because it is better" | Names no alternative and no force; unfalsifiable |
|
||||
| Written after the code shipped | Reverse-engineers a justification. Record the reasoning while it is still contested |
|
||||
| One ADR amended repeatedly | Destroys the history the format exists to keep |
|
||||
| No Validation section | Nothing distinguishes a good decision from a lucky one |
|
||||
| A tension "resolved" by picking arbitrarily | The next person re-litigates it, having lost the reasoning |
|
||||
|
||||
## Escalation
|
||||
|
||||
Writes a file, so it acts — but it decides nothing.
|
||||
|
||||
Stop and hand back when: the deciders are not you — which, for an agent, is always. An
|
||||
ADR records a decision someone with authority made; writing one to *create* that
|
||||
authority is how a preference acquires a document number.
|
||||
|
||||
So the deliverable is a draft marked `proposed` with **the person who must accept it named
|
||||
in `deciders` as `pending: <name>`**, and that hand-back stated in the response, not left
|
||||
implied. Naming the decider is the escalation, not a formality — an unnamed one is how a
|
||||
proposal sits for a month.
|
||||
|
||||
That is the intended state for an agent-authored ADR, and it is not the parking-space
|
||||
failure below: a `proposed` ADR with a named decider is waiting on someone; one without is
|
||||
waiting on nobody.
|
||||
|
||||
Also stop when the Context cannot be written without inventing a constraint. A missing
|
||||
force means the decision has not been thought through yet, and an ADR built on an
|
||||
invented one is worse than none: it will be cited.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- `lineage` and `grill-me` — see *Before you write*; they change the content, so they are
|
||||
steps rather than references.
|
||||
- `spec-driven-dev` / `feature-spec` — an ADR is the *why*; a spec is the *what*. If you
|
||||
are describing behaviour, you are writing a spec.
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: atdd
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Acceptance Test-Driven Development workflow"
|
||||
use_when: "Feature development with acceptance criteria"
|
||||
description: Implement user stories using the ATDD workflow — Red (failing acceptance test) → Green (minimal implementation) → Refactor. One story at a time.
|
||||
---
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
---
|
||||
name: cad-babysit
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Focused human-in-the-loop session working CAD's stuck queue (read-only)"
|
||||
use_when: "Picking up whatever `cad stuck` flags, with a human present"
|
||||
description: Focused human-in-the-loop session working CAD's stuck queue (cad-stuck output). Read-only — diagnoses, never dispatches, arms a label, or closes an issue. Use when picking up whatever CAD has run into trouble on, with a human present.
|
||||
---
|
||||
|
||||
# CAD Babysit
|
||||
|
||||
## Overview
|
||||
|
||||
A deliberately narrow session: pick up whatever CAD has run into trouble on, work it with a
|
||||
human present, and stop. This is not an autonomous supervisor — it is a babysitter with a
|
||||
person in the room, and that is the point, not a limitation to route around later.
|
||||
|
||||
**Core principle:** an unattended supervisor reproduces the exact failure it exists to catch.
|
||||
`dispatch` ran dead for eight weeks because it exited 0 and nobody noticed (`dispatch#33`); a
|
||||
long-running watcher process that dies quietly has the same property one level up, and
|
||||
manufactures false confidence while doing it. With a human present, **the human is the
|
||||
liveness check** — that removes the objection entirely and needs no new machinery.
|
||||
|
||||
This skill is the ritual around `cad stuck` (`mathias/cad#14`), not a replacement for it.
|
||||
Without that query it would be a checklist with no input; the query without this skill is
|
||||
data nobody reads carefully. Neither closes the loop alone.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Picking up CAD's stuck queue with a human present and time set aside to work it
|
||||
- After `dispatch` (or any executor) reports a failure and it is not immediately obvious
|
||||
whether it is an infrastructure fault or a real task outcome
|
||||
- Reviewing the "awaiting human" queue (issues CI has verified but nobody has closed)
|
||||
|
||||
**Do not use for:**
|
||||
- Unattended/scheduled runs. This skill assumes a human is present for its entire duration —
|
||||
if nobody is watching, its central safety property (human-as-liveness-check) does not hold.
|
||||
- Dispatching, arming a redispatch label, or closing an issue. This skill only ever diagnoses;
|
||||
see Iron Laws.
|
||||
|
||||
## Iron Laws
|
||||
|
||||
1. **Read-only, always.** No dispatching, no arming labels (including `status:redispatch`), no
|
||||
closing or reopening an issue. A reviewer that can act on its own findings has no
|
||||
independent check — control stays where it already is.
|
||||
2. **Every finding cites a locator.** A run id, commit sha, comment permalink, or a specific
|
||||
log line. A finding without one is an unfalsifiable opinion about a machine — do not emit
|
||||
it, and do not soften this into "probably" language instead of dropping it.
|
||||
3. **Re-derive, never recall.** State lives in Gitea and Actions, not in this session. Start
|
||||
cold every time: run `cad stuck` fresh, do not carry forward a prior session's worklist.
|
||||
Sessions get compacted and lose exactly the cross-run history that makes a stale worklist
|
||||
dangerous to trust.
|
||||
4. **Distinguish "blocked" from "awaiting human".** `cad stuck` already makes this split
|
||||
(`stuck` vs `awaiting_human`); preserve it in every summary. The `awaiting_human` class is
|
||||
the human gate working, not a bottleneck — do not report it as one.
|
||||
5. **Anything that is the operator's call surfaces as `DECISION NEEDED`, never gets decided
|
||||
for them.** See Output Format.
|
||||
|
||||
## Process
|
||||
|
||||
### Phase 1 — Query (re-derive the worklist)
|
||||
|
||||
Run `cad stuck` against the estate (the `dispatch-repos.txt` scope, or whatever repo set the
|
||||
operator names). This is the only input. Do not substitute a memory of a prior run, a brain
|
||||
note, or this issue's own worked examples — all three can be stale within the same day (a
|
||||
taxonomy row's cited live example can stop reproducing between when it was written and when
|
||||
you run the query, because the underlying state genuinely changed; that is the design working,
|
||||
not a bug to paper over).
|
||||
|
||||
Group the output by class exactly as `cad stuck` returns it: `stuck` first, `awaiting_human`
|
||||
second. Pick ONE row to work per pass — this skill is deliberately narrow, not a full-estate
|
||||
sweep.
|
||||
|
||||
### Phase 2 — Read the issue's own comments FIRST
|
||||
|
||||
Before anything else, before touching Actions or pod logs: read every comment on the issue,
|
||||
oldest first. This step exists because it was skipped once and it cost a session — a confident
|
||||
wrong root cause was produced from pod logs while the correct diagnosis sat in the issue's own
|
||||
comment thread from nine days earlier (`cad-atlas#10`). The rule "read issue comments before
|
||||
working" was already written down elsewhere and was not followed; it is written down again
|
||||
here because that is exactly the kind of already-known thing a rushed session skips.
|
||||
|
||||
What to look for: the bot's own report comments (routing decision, ground-truth verdict,
|
||||
attempt count), and any human comment that already contains the diagnosis.
|
||||
|
||||
### Phase 3 — THEN the Actions job logs
|
||||
|
||||
Only after Phase 2 turns up nothing conclusive, read the CI job logs:
|
||||
|
||||
```
|
||||
GET /repos/{owner}/{repo}/actions/runs # find the run, match on .run_number
|
||||
GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs # returns 200, full text, secrets masked
|
||||
```
|
||||
|
||||
This endpoint works. A prior note claiming it 404s was wrong and cost a diagnosis the day this
|
||||
skill was written — do not rediscover that. Get the run id from `/actions/runs`, not from the
|
||||
`run_number` shown in a comment (they are different fields; match on `.run_number` to find the
|
||||
internal `id` the jobs endpoint needs).
|
||||
|
||||
This is where the two most valuable findings of the day this skill is drawn from lived: an
|
||||
agent issuing the identical refused command five times and stopping (never trying the tools it
|
||||
was actually permitted to use), and a different model, same denial, writing a Go program to
|
||||
route around it. Neither is visible from the issue comments alone — no metric produces either
|
||||
of them. They need a reader of the raw transcript.
|
||||
|
||||
### Phase 4 — Separate infrastructure fault from task outcome
|
||||
|
||||
A run that died before turn 1 says nothing about the issue itself. Before concluding anything
|
||||
about the WORK, check whether the run reached the model at all:
|
||||
|
||||
- Zero turns, a 2-3 record transcript, a "could not start" comment, or a claim label with no
|
||||
attempt comment behind it → infrastructure fault. This is not evidence the issue is hard, ill
|
||||
specified, or that the assigned model is unsuitable — it is evidence something upstream
|
||||
(credit, a key, MCP connectivity, the executor binary) is broken.
|
||||
- A run that reached the model, drove tools, and stopped on a ceiling, a denial loop, or a
|
||||
genuine task failure → a real task outcome, worth diagnosing on its own terms.
|
||||
|
||||
Four claim labels were burned this exact way in one estate sweep and the tracker read them as
|
||||
four handled issues (`dispatch#33`). Get this distinction wrong and everything downstream is
|
||||
about the wrong thing.
|
||||
|
||||
### Phase 5 — Decide, or say `DECISION NEEDED`
|
||||
|
||||
For each row worked, produce one of:
|
||||
|
||||
- **A closed diagnosis** — cause identified, cited to a locator, no operator judgment call
|
||||
required (e.g. "infrastructure fault, credit exhausted, see comment #N — retry is automatic
|
||||
on the next cycle, no action needed").
|
||||
- **A `DECISION NEEDED`** — anything that is genuinely the operator's call: whether to close a
|
||||
verified-but-open issue, whether to raise a ceiling, whether to abandon an issue that keeps
|
||||
hitting the same denial. Never make this call on the operator's behalf.
|
||||
|
||||
This skill's OWN last act, every time, is to stop — not to dispatch, not to redispatch, not to
|
||||
close. Ending a pass is itself the enforcement of Iron Law 1.
|
||||
|
||||
## Output Format
|
||||
|
||||
For a closed diagnosis:
|
||||
|
||||
```
|
||||
DIAGNOSIS: <repo>#<issue> — <category from cad stuck, e.g. ceiling_hit>
|
||||
CAUSE: <one sentence, cites the mechanism>
|
||||
LOCATOR: <url or run id / log line>
|
||||
ACTION: <what happens automatically, or "none — informational">
|
||||
```
|
||||
|
||||
For anything requiring a human call:
|
||||
|
||||
```
|
||||
DECISION NEEDED: <repo>#<issue>
|
||||
QUESTION: <the exact thing only the operator can decide>
|
||||
OPTIONS:
|
||||
1. <option> — <consequence>
|
||||
2. <option> — <consequence>
|
||||
RECOMMENDATION: <your pick, with reasoning — but the operator decides>
|
||||
BLOCKS: <what stays stuck until this is answered, if anything>
|
||||
```
|
||||
|
||||
End every pass with a one-line summary: `N diagnosed, M decisions needed, stopping.`
|
||||
|
||||
## Worked Example
|
||||
|
||||
`cad stuck` returns `mathias/cad-atlas#10 [near_attempt_cap] 4 dispatch attempts recorded, at
|
||||
or above the near-cap threshold (4 of MaxAttempts=5).`
|
||||
|
||||
Phase 2 (issue comments): the issue's own thread already explains the pattern — repeated
|
||||
`status:redispatch` re-arming without the label being cleared after a completed attempt.
|
||||
|
||||
Phase 3: not needed — Phase 2 was conclusive.
|
||||
|
||||
Phase 4: each of the 4 attempts reached the model and ran (not an infrastructure fault) — a
|
||||
real re-fire pattern, not a claim-label artifact.
|
||||
|
||||
Phase 5 output:
|
||||
|
||||
```
|
||||
DECISION NEEDED: mathias/cad-atlas#10
|
||||
QUESTION: one more automatic attempt remains before MaxAttempts=5 gives up permanently. Let
|
||||
it fire, or intervene now (fix the underlying cause, or manually close/redirect the issue)?
|
||||
OPTIONS:
|
||||
1. Let it fire — costs one more headless run; if it fails the same way, dispatch gives up
|
||||
automatically and posts a terminal comment. No action needed until then.
|
||||
2. Intervene now — diagnose why redispatch keeps re-arming (likely: the watcher isn't
|
||||
clearing RedispatchLabel after a serviced run) and fix that before the cap is spent on
|
||||
a symptom rather than the cause.
|
||||
RECOMMENDATION: option 2. The pattern (redispatch not self-clearing after a completed run) is
|
||||
already documented as a known operational hazard (dispatch#54) — spending the last attempt
|
||||
on it again teaches nothing new.
|
||||
BLOCKS: nothing else; this issue's own progress.
|
||||
```
|
||||
|
||||
`1 diagnosed, 1 decision needed, stopping.`
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
| Anti-Pattern | Why It Fails |
|
||||
|---|---|
|
||||
| Diagnosing from pod/Actions logs before reading issue comments | The exact mistake that cost a session — the answer was already written down nine days earlier. |
|
||||
| Reporting `awaiting_human` rows as a backlog or bottleneck | It is the human gate working. Misreporting it manufactures urgency that isn't there and trains the operator to distrust the queue. |
|
||||
| Treating a zero-turn, could-not-start run as evidence about the issue | It is an infrastructure fault. Four claim labels were burned exactly this way and read as four handled issues. |
|
||||
| Deciding a `DECISION NEEDED` case on the operator's behalf "to save time" | Removes the one property that makes this skill safe to run unattended-adjacent: the human decides, this skill only prepares the decision. |
|
||||
| Applying `status:redispatch`, closing an issue, or adding any label from this skill | Control stays where it is. This skill has no write path and should never be given one. |
|
||||
| Carrying forward a worklist from an earlier session instead of re-running `cad stuck` | State changes between sessions (see the worked note on `brain-gardener#190` in `cad#14`'s own acceptance run — its trigger label was gone hours later). A stale worklist gives false confidence, which is the specific failure mode this whole skill exists to avoid. |
|
||||
|
||||
## Honest Limitation
|
||||
|
||||
This skill encodes the *repeatable* diagnostic sequence: read comments, then logs, separate
|
||||
fault from outcome, verify by exit code, re-derive rather than recall. It reliably catches the
|
||||
taxonomy `cad stuck` already knows about. It will not, by itself, produce a genuinely novel
|
||||
finding the way an unhurried human-plus-agent reading session did the day this skill was
|
||||
written — that came from noticing things (an agent editing the file that authorizes it, an
|
||||
issue body recommending a command the policy forbids) that no checklist anticipates. Expect
|
||||
this skill to be reliable on known failure modes and to miss the next new one. That is an
|
||||
acceptable trade as long as nobody mistakes a clean pass through this skill for "nothing is
|
||||
wrong" — it means "nothing on the known list is wrong."
|
||||
|
||||
## Brain MCP Integration
|
||||
|
||||
**At session start:**
|
||||
- Run `brain_query` for the domain (`cad`, `dispatch`, the specific repo) to check whether a
|
||||
finding this session is about to produce has already been diagnosed and written up. Do not
|
||||
re-diagnose a known pattern from scratch every session.
|
||||
|
||||
**After a genuinely novel finding (not already in the taxonomy or the brain):**
|
||||
- `brain_write` the pattern, generalized beyond the specific issue — the failure mode, not the
|
||||
issue number. Do not write routine, already-known-taxonomy findings; that is what `cad
|
||||
stuck`'s own output already records, durably, in Gitea.
|
||||
|
||||
**Never:**
|
||||
- Write a `DECISION NEEDED` outcome to the brain before the operator has actually decided —
|
||||
that would record a guess as a resolution.
|
||||
|
||||
### Logging
|
||||
|
||||
Call `session_log` once at the end of every phase to record the outcome.
|
||||
|
||||
**At end of each phase:**
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "cad-babysit", phase: "<phase-name>", final_status: "pass" |
|
||||
"fail" | "skip", message: "<one-line summary>", project_root:
|
||||
"<absolute path>"}`
|
||||
|
||||
**Phases for this skill:** query, read-comments, read-actions-logs, classify-fault-vs-outcome,
|
||||
decide
|
||||
|
||||
**Status semantics:**
|
||||
- `pass` — the phase's intended outcome was reached (worklist re-derived; comments read;
|
||||
fault/outcome separated; a diagnosis or `DECISION NEEDED` was produced).
|
||||
- `fail` — the phase could not be completed (e.g. `cad stuck` errored, Gitea was unreachable).
|
||||
- `skip` — phase intentionally skipped (e.g. Phase 3 skipped because Phase 2 was conclusive).
|
||||
|
||||
## Cross-References
|
||||
|
||||
- Depends on `mathias/cad#14`'s `cad stuck` query — this skill is the ritual around it, not a
|
||||
replacement.
|
||||
- Load `debug` for the hypothesis-generation discipline if Phase 4's fault/outcome split is
|
||||
itself ambiguous.
|
||||
- Load `secret-hygiene` before reading raw Actions job logs if the repo is client-tagged —
|
||||
logs are secret-masked by Gitea but a pasted excerpt into a summary is not.
|
||||
- `mathias/cad-atlas#11` renders the same `cad stuck` output as a pipeline overlay — read that
|
||||
instead of this skill's text output when a visual "where is everything stuck" view is wanted
|
||||
over working one row in depth.
|
||||
|
||||
## Escalation
|
||||
|
||||
Read-only by construction, and the Iron Laws above are the escalation rule: never close
|
||||
an issue, never dispatch, never write a label. Everything that is the operator's call
|
||||
leaves as a `DECISION NEEDED` block (question / options / recommendation / blocks).
|
||||
|
||||
Stop and hand back when: the stuck queue is empty; a diagnosis needs a write you are not
|
||||
allowed to make; or two runs in a row produce the same finding, which means the finding
|
||||
is not being acted on and repeating it is noise.
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: clean-code
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Clean code principles with Go adaptation"
|
||||
use_when: "Code review, refactoring, new code"
|
||||
description: Write code that humans can read, understand, and safely change. Apply SOLID, GRASP, and Clean Code principles during the REFACTOR phase of TDD.
|
||||
---
|
||||
|
||||
@@ -278,5 +281,14 @@ During refactoring:
|
||||
|
||||
- `references/clean-code.md` — detailed naming rules, object calisthenics
|
||||
- `references/code-smells.md` — comprehensive smell catalog with examples
|
||||
- `references/python-adaptation.md` — Python conventions: error chaining, dataclasses, the truthiness trap
|
||||
- Load `solid` skill for SOLID principles with Go examples
|
||||
- Load `refactoring` skill for systematic refactoring techniques
|
||||
|
||||
## Escalation
|
||||
|
||||
Advisory during the REFACTOR phase. Suggests; does not restructure behaviour.
|
||||
|
||||
Stop and hand back when: the cleanup you are proposing changes behaviour. That is not
|
||||
refactoring, it is a change, and it needs its own failing test first — hand back to
|
||||
`tdd`.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Clean Code: Python Adaptation
|
||||
|
||||
The principles in `SKILL.md` are language-agnostic. This file covers the places where
|
||||
Python's idioms differ from the Go examples, and where following the Go shape produces
|
||||
bad Python.
|
||||
|
||||
The canonical stack (ruff, mypy --strict, pytest, uv, pydantic-settings, src-layout)
|
||||
lives in `~/dev/.context/AGENT.md` and is not restated here — one source of truth, and
|
||||
it is not this file.
|
||||
|
||||
## Reveal intent with types, not comments
|
||||
|
||||
`mypy --strict` is the Python analogue of Go's compiler, and it is non-negotiable for
|
||||
the same reason: a type is a claim the machine checks, and a comment is a claim nobody
|
||||
checks. Two consequences for clean code specifically:
|
||||
|
||||
- **`Any` is a hole in the argument.** Each one says "the reader is on their own here".
|
||||
If a value is genuinely polymorphic, say so precisely — `Protocol`, a union, a
|
||||
`TypeVar` — rather than surrendering.
|
||||
- **A `# type: ignore` needs the error code and a reason**: `# type: ignore[arg-type] #
|
||||
boto3 stubs lag the API`. A bare ignore is an unexplained exception to a rule the rest
|
||||
of the file follows.
|
||||
|
||||
## Errors: chain them, never swallow them
|
||||
|
||||
Go's `fmt.Errorf("operation: %w", err)` is `raise` with `from`:
|
||||
|
||||
```python
|
||||
# Bad — the original cause is gone, and so is the stack that produced it
|
||||
try:
|
||||
row = fetch(invoice_id)
|
||||
except KeyError:
|
||||
raise InvoiceNotFound(invoice_id)
|
||||
|
||||
# Good — the chain survives; the traceback shows both
|
||||
try:
|
||||
row = fetch(invoice_id)
|
||||
except KeyError as e:
|
||||
raise InvoiceNotFound(invoice_id) from e
|
||||
```
|
||||
|
||||
Two rules with no exceptions:
|
||||
|
||||
- **Never bare `except:`.** It catches `KeyboardInterrupt` and `SystemExit` too, so it
|
||||
turns Ctrl-C into a swallowed error. `except Exception` if you truly mean everything.
|
||||
- **Never a silent `pass`.** An exception handler that does nothing is a decision to
|
||||
ignore a failure; if that is genuinely right, the handler needs a comment saying why,
|
||||
and usually a log line. Most of the time it is a bug being stored for later.
|
||||
|
||||
## Data classes over dicts
|
||||
|
||||
A `dict[str, Any]` passed between functions is Go's `map[string]interface{}` — every
|
||||
reader has to reconstruct the shape from the code that writes it.
|
||||
|
||||
```python
|
||||
# Bad: shape known only by reading every producer
|
||||
def total(invoice: dict[str, Any]) -> int: ...
|
||||
|
||||
# Good: shape declared once, checked everywhere
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Invoice:
|
||||
id: InvoiceId
|
||||
lines: tuple[Line, ...]
|
||||
currency: str # ISO 4217
|
||||
|
||||
def total(invoice: Invoice) -> Money: ...
|
||||
```
|
||||
|
||||
`frozen=True` where the value is conceptually immutable — it makes accidental mutation
|
||||
an error rather than a surprise at a distance. Use `pydantic` models at the *boundary*
|
||||
(env config, HTTP payloads) where validation is the point, and dataclasses inside,
|
||||
where validation has already happened.
|
||||
|
||||
## Two Python-specific traps that read as clean code
|
||||
|
||||
**Mutable default arguments** are evaluated once, at definition:
|
||||
|
||||
```python
|
||||
def add_line(line: Line, lines: list[Line] = []) -> list[Line]: # shared across calls
|
||||
```
|
||||
|
||||
Use `None` and build inside. Ruff catches this (`B006`); the point of naming it here is
|
||||
that the broken version looks tidier than the correct one.
|
||||
|
||||
**Truthiness is not presence.** `if not amount:` is true for `0`, `0.0`, `""`, `[]` and
|
||||
`None` alike. For anything where zero is a legitimate value — money, counts, offsets —
|
||||
write `if amount is None:`. This is the single most common way a Python function
|
||||
silently mishandles a valid input.
|
||||
|
||||
## Structure
|
||||
|
||||
- `src/` layout, `pyproject.toml` only. A flat layout lets tests import the working
|
||||
directory instead of the installed package, so the suite passes on a package that
|
||||
cannot actually be installed.
|
||||
- Module names are the unit of cohesion, as Go packages are. `utils.py` is the Python
|
||||
spelling of a god package: it has no reason to change because it has no subject.
|
||||
- Prefer functions to classes with one method. A class whose only job is to hold
|
||||
constructor arguments and expose `run()` is a closure with ceremony.
|
||||
|
||||
## See also
|
||||
|
||||
- `references/clean-code.md` — the language-agnostic practices
|
||||
- `references/code-smells.md` — the smell catalogue, all of which apply here
|
||||
- `tdd/references/python.md` — the test-side conventions
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: code-review
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Code smell detection + Go-specific checklist"
|
||||
use_when: "Pre-merge review"
|
||||
description: Systematic code smell detection and Go-specific review checklist. Load before any pre-merge review.
|
||||
---
|
||||
|
||||
@@ -11,6 +14,8 @@ Code review is smell detection and principle verification, not style policing. T
|
||||
|
||||
**This skill is read-only analysis.** When you find issues, document them with specific file:line references and prioritize by architectural impact. For fixes, load the `refactoring` or `clean-code` skill.
|
||||
|
||||
Three similarly-named skills cover orthogonal concerns, and landing on one is no reason to miss the others: this one is **what to check**, `superpowers-requesting-code-review` is **how to commission a reviewer**, and `superpowers-receiving-code-review` is **how to behave when the feedback arrives**.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Pre-merge review of any pull request
|
||||
@@ -248,7 +253,7 @@ Pass-rate is computed downstream by the `/pass-rate` HTTP endpoint, which
|
||||
treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
|
||||
**At end of each phase:**
|
||||
- `session_log` with `{skill: "code-review", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", duration_ms: <wall-clock>, project_root: "<absolute path>"}`
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "code-review", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", project_root: "<absolute path>"}`
|
||||
|
||||
**Phases for this skill:** phase-0-iron-laws, phase-1-context, phase-2-architectural-analysis, phase-3-go-checklist, phase-4-code-smell-detection, phase-5-test-quality
|
||||
|
||||
@@ -257,7 +262,7 @@ treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
- `fail` — the phase's intended outcome was NOT reached.
|
||||
- `skip` — phase was skipped intentionally.
|
||||
|
||||
**Why this matters:** the routing pod (Plan 6) reads pass-rate to decide whether to route a future call to a local model. If your skill never logs, the routing pod sees no data.
|
||||
**Why this matters:** pass-rate is what a future routing decision would be based on — whether a given call can be served by a local model instead of a cloud one. A skill that never logs contributes no evidence either way.
|
||||
|
||||
## Common Go Anti-Patterns
|
||||
|
||||
@@ -274,11 +279,18 @@ treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
|
||||
## References
|
||||
|
||||
- `references/python-adaptation.md` — the Python anti-pattern table, and what ruff/mypy
|
||||
should have caught before review
|
||||
- `clean-code/references/code-smells.md` — comprehensive smell catalog
|
||||
- Load `refactoring` skill when recommending fixes
|
||||
- Load `test-design` skill for reviewing test quality
|
||||
- Load `solid` skill for SOLID principle violations
|
||||
|
||||
## Mode 2 Routing Note
|
||||
## Escalation
|
||||
|
||||
This skill is invoked identically in Mode 1 (cloud Claude) and Mode 2 (client-local with supervisor routing). The routing layer (Plan 6) does not exist yet; treat this skill as Mode 1 only for now. Findings format and severity classification are unchanged across modes.
|
||||
Read-only analysis. Findings are the output; nothing is handed back mid-review.
|
||||
|
||||
Stop and hand back when: the diff is large enough that a review would be a skim — say so
|
||||
and ask for it in parts, rather than producing confident coverage of a fraction of it; or
|
||||
the problem is structural rather than pointwise, in which case name it and hand off to
|
||||
`solid` or `refactoring` instead of filing twenty line-level comments about one cause.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Code Review: Python Anti-Patterns
|
||||
|
||||
`SKILL.md` carries the Go anti-pattern table. This is the Python one. The review
|
||||
process, severity classification and output format above it are language-neutral and
|
||||
apply unchanged.
|
||||
|
||||
Canonical stack in `~/dev/.context/AGENT.md`. Two gates decide most of this file:
|
||||
`ruff` and `mypy --strict`. **If a finding is something ruff or mypy already catches,
|
||||
the review comment is not "fix this line" — it is "why is the gate not running?"**
|
||||
|
||||
## The table
|
||||
|
||||
| Anti-pattern | What to look for | Why it matters |
|
||||
|---|---|---|
|
||||
| Bare `except:` | `except:` with no exception class | Swallows `KeyboardInterrupt` and `SystemExit`; Ctrl-C stops working |
|
||||
| Silent `pass` | `except X: pass` with no comment | A decision to ignore a failure, recorded nowhere |
|
||||
| Lost cause | `raise Y(...)` inside `except X as e` with no `from e` | Traceback loses the original failure — the Python analogue of a naked `fmt.Errorf` |
|
||||
| Mutable default | `def f(x, acc=[])` or `={}` | Evaluated once at definition; state leaks between calls |
|
||||
| Truthiness for presence | `if not amount:` where `0` is valid | Silently mishandles zero, empty string, empty list |
|
||||
| `Any` as an escape | `Any` in a signature that could be `Protocol`/union/`TypeVar` | Removes exactly the checking `--strict` was adopted for |
|
||||
| Unexplained ignore | bare `# type: ignore` | No error code, no reason; permanent by default |
|
||||
| `assert` in production code | `assert user.is_admin` outside tests | `python -O` strips asserts — the check vanishes in a tuned deployment |
|
||||
| Import-time side effects | connections, env reads, or I/O at module scope | Cannot be injected, cannot be tested, ordering-dependent |
|
||||
| Sync I/O in `async def` | `requests.get`, `time.sleep`, blocking file reads | Blocks the whole event loop; looks concurrent, is not |
|
||||
| Un-awaited coroutine | a call to an `async def` with no `await` | Silently does nothing; "coroutine was never awaited" is a warning, not an error |
|
||||
| `float` for money | `float` amounts, `round()` on currency | `0.1 + 0.2 != 0.3`; use `Decimal` or int minor units |
|
||||
| Broad `Exception` re-raise | `except Exception` around a whole function body | Turns a specific failure into an unclassifiable one |
|
||||
| Mutating a shared default/global | module-level `list`/`dict` mutated by functions | The Python spelling of shared mutable state |
|
||||
| `dict[str, Any]` as a domain type | dicts passed between layers | Shape known only by reading every producer; use a dataclass |
|
||||
| Star imports | `from x import *` | Breaks `--strict`, hides shadowing, defeats grep |
|
||||
| `os.path` string surgery | manual path joining, `+ "/"` | `pathlib` exists and is correct on every platform |
|
||||
| `subprocess(..., shell=True)` with interpolation | f-strings into a shell command | Injection; pass a list, no shell |
|
||||
|
||||
## What to check that a linter cannot
|
||||
|
||||
- **Does the test suite assert the failure mode, or only the happy path?** `pytest.raises`
|
||||
with no `match=` accepts any message, including one from an unrelated bug.
|
||||
- **Are fixtures doing real work?** A `conftest.py` fixture with a `session` scope and
|
||||
mutable state couples every test that touches it; failures then depend on ordering.
|
||||
- **Is the mock mocking a boundary or a collaborator you own?** The latter tests the mock.
|
||||
- **Does the type say what the code means?** `-> dict` and `-> tuple[int, int]` both pass
|
||||
`--strict` and both tell the reader nothing. A named type is a review comment worth
|
||||
making.
|
||||
- **Would `--strict` actually run on this file?** Check for a per-module override in
|
||||
`pyproject.toml` silently exempting it. An exemption nobody revisits is a hole with a
|
||||
changelog entry.
|
||||
|
||||
## Severity in this context
|
||||
|
||||
- **Blocking:** anything in the table above under security or correctness — `shell=True`
|
||||
interpolation, `assert` as an authorization check, `float` money, sync I/O in async.
|
||||
- **Should fix:** typing escapes (`Any`, unexplained ignores), mutable defaults,
|
||||
truthiness-for-presence.
|
||||
- **Consider:** structural comments — dataclass instead of dict, narrower Protocol.
|
||||
|
||||
## See also
|
||||
|
||||
- `clean-code/references/python-adaptation.md` — the style-level conventions
|
||||
- `solid/references/python-adaptation.md` — Protocol over ABC, DIP in Python
|
||||
- `tdd/references/python.md` — the test-side conventions this review checks against
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: cognitive-load
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Cognitive complexity analysis (CLI score)"
|
||||
use_when: "Identifying hotspots, before refactoring"
|
||||
description: Measure how much mental effort a codebase demands from developers. Use when identifying hotspots, before architectural decisions, or when code feels hard to understand.
|
||||
---
|
||||
|
||||
@@ -344,3 +347,12 @@ type UserWriter interface {
|
||||
- Load `refactoring` skill for systematic techniques to reduce identified hotspots
|
||||
- Load `solid` skill for structural fixes (coupling, cohesion)
|
||||
- Load `clean-code` skill for naming improvements
|
||||
|
||||
## Escalation
|
||||
|
||||
Read-only measurement. The score is the output.
|
||||
|
||||
Stop and hand back when: the measurement disagrees with the reader's lived experience of
|
||||
the code. A metric that says "fine" about code everyone finds hard is evidence about the
|
||||
metric, not about the code, and continuing to defend the number is how a measure becomes
|
||||
a target.
|
||||
@@ -0,0 +1,239 @@
|
||||
---
|
||||
name: debug
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Hypothesis-first debugging discipline"
|
||||
use_when: "Any test failure or bug whose cause is not immediately obvious — or a bug report with no failure text, which this skill refuses rather than guesses at"
|
||||
description: Systematic hypothesis-first debugging. Requires the failure itself — error text, stack, run id or log — and names what it needs and stops if the report has none, rather than hypothesising into a vacuum. Given evidence, generates 3-5 ranked, falsifiable hypotheses with verification steps before suggesting any fix. Use when encountering a bug, test failure, or unexpected behavior.
|
||||
---
|
||||
|
||||
# Debug
|
||||
|
||||
## Overview
|
||||
|
||||
Debugging is hypothesis generation, not fix generation. The first instinct — "try this and see if it works" — wastes time and teaches nothing. A disciplined debug session produces a small set of ranked, falsifiable hypotheses, each with a concrete verification command. The fix comes after one hypothesis is confirmed, not before.
|
||||
|
||||
**Core principle:** A hypothesis you cannot verify with a single bounded, decisive observation is not a hypothesis — it is a guess. In a repo that observation is usually one command. Above one it may be an instrumented run, or partitioning the last twenty CI runs by trigger type; what makes it a hypothesis is that the observation *discriminates*, not that it fits on one line.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Any test failure whose cause is not immediately obvious
|
||||
- Any production error or unexpected behavior
|
||||
- Any bug report from a user or stakeholder
|
||||
- Before reaching for a debugger or adding print statements: form hypotheses first
|
||||
|
||||
**Do not use for:**
|
||||
- Compile errors with clear messages (just fix the typo)
|
||||
- Already-diagnosed bugs where you know the cause (go straight to TDD with a regression test)
|
||||
|
||||
### Is it actually diagnosed?
|
||||
|
||||
That last exclusion is the one people get wrong, because a confident wrong diagnosis feels
|
||||
exactly like a right one. It is diagnosed if you can state the mechanism *and* name the
|
||||
observation that would have proved it wrong. If the evidence is "we changed X and it got
|
||||
better", that is correlation with a deployment, and this skill applies.
|
||||
|
||||
The strongest tell is a run of failed fixes — see below. Three plausible fixes that did
|
||||
not eliminate the symptom is not bad luck, it is the diagnosis being wrong.
|
||||
|
||||
### Intake: what you need before hypothesising
|
||||
|
||||
Before generating anything, confirm you have the failure itself — the error text, the
|
||||
stack, the failing run's id, the log. If the report is "it's flaky again" with no
|
||||
artifact, **name the specific thing you need and stop**. Iron Law 1 forbids "try X and
|
||||
see"; hypothesising into a vacuum is the same failure with better grammar, and it is
|
||||
worse because the output looks like analysis.
|
||||
|
||||
This is the rule `cad-babysit` already enforces from the other side: read the issue's own
|
||||
comments and the job log *first*.
|
||||
|
||||
## Iron Laws
|
||||
|
||||
1. **Never suggest "try X and see what happens."** Every hypothesis must have a specific expected outcome if correct.
|
||||
2. **Generate 3-5 hypotheses, ordered by likelihood (most likely first).** Fewer than 3 means you stopped thinking; more than 5 means you are not prioritizing.
|
||||
3. **Diagnose only — do not fix in this skill.** The fix happens in a separate TDD cycle (load `tdd` skill) once a hypothesis is confirmed.
|
||||
|
||||
## When the bug spans components
|
||||
|
||||
A system with boundaries (CI → build → signing, API → service → database) hides the
|
||||
question "which component is wrong?" behind the question "why is the output wrong?".
|
||||
Specify, as a pre-step, what to log entering and leaving **each** boundary, plus
|
||||
whether config and environment actually propagated. One run *that reproduces the failure* narrows the search to a
|
||||
single component. On an intermittent fault a passing run narrows nothing, so leave the
|
||||
instrumentation in across several runs rather than concluding from one.
|
||||
|
||||
This does not suspend Iron Law 2. Still emit 3-5 hypotheses — the boundary spec comes
|
||||
first in the output, and each hypothesis says which boundary observation would kill it.
|
||||
What the pre-step forbids is hypotheses that quietly assume a component is the faulty
|
||||
one before any evidence says so.
|
||||
|
||||
## When several fixes have already failed
|
||||
|
||||
Three or more plausible fixes that failed to eliminate a symptom is not a run of bad
|
||||
luck — it is evidence that nobody has identified the mechanism. (Fixes that changed
|
||||
nothing at all count double: they are stronger evidence of a misidentified mechanism
|
||||
than fixes that partially worked.) Each one has been narrowing a window rather than
|
||||
closing it, and a fourth guess buys another tenth of the rate plus a layer of
|
||||
interacting guards nobody can reason about.
|
||||
|
||||
Intake still gates this section. A report of three failed fixes with no artifacts fires
|
||||
both rules at once, and intake wins: you cannot aim hypotheses at a premise you have no
|
||||
evidence about either. Ask for the log, then aim.
|
||||
|
||||
Say that explicitly — the refusal is the finding, not a preamble to it. Then aim the
|
||||
hypotheses one level up: the premise those fixes share is itself the thing to falsify.
|
||||
This is not an exemption from the output format. It is the format, pointed at the
|
||||
assumption instead of at the symptom.
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Read the failure
|
||||
|
||||
Before forming hypotheses:
|
||||
- Read the full error message and stack trace, not just the headline
|
||||
- Read the file where the failure originated, around the failing line
|
||||
- If the failure is from a test, read the test and the code under test
|
||||
- Identify the **failure mode** — what actually went wrong (e.g. "nil pointer dereference in goroutine spawned by handler") not just what the error says ("runtime error")
|
||||
|
||||
### Step 2: Generate hypotheses
|
||||
|
||||
For each hypothesis, capture three things:
|
||||
|
||||
- **Mechanism:** what specific code path or state would produce this exact failure
|
||||
- **Verification:** the single command or file inspection that confirms or denies it
|
||||
- **Expected outcome if correct:** the specific output you would see
|
||||
|
||||
Order by likelihood, most likely first. **The ordering is the ranking — do not also
|
||||
attach `high`/`medium`/`low` labels.** With five slots and three labels the labels stop
|
||||
discriminating (two hypotheses are genuinely both "high" and the label cannot say which
|
||||
comes first), and a reader then has two orderings that can disagree. Position already
|
||||
carries it.
|
||||
|
||||
Where you can say *why* one outranks another — a prior brain entry, a matching symptom,
|
||||
a recent change in that area — say that instead of a label. That is information; a label
|
||||
is a restatement of the order it sits next to.
|
||||
|
||||
### Step 3: Output
|
||||
|
||||
Use this format:
|
||||
|
||||
```
|
||||
HYPOTHESIS 1: <mechanism in one sentence>
|
||||
WHY FIRST: <what makes it likeliest — a matching symptom, a recent change, a brain entry>
|
||||
VERIFY: <exact command, or the bounded observation that discriminates>
|
||||
EXPECTED IF CORRECT: <specific output, value, or condition>
|
||||
|
||||
HYPOTHESIS 2: <mechanism>
|
||||
WHY FIRST: <or why it ranks here rather than first>
|
||||
VERIFY: <exact command>
|
||||
EXPECTED IF CORRECT: <specific output>
|
||||
|
||||
[... up to 5 ...]
|
||||
|
||||
RECOMMENDED NEXT STEP: Run VERIFY for hypothesis 1 first.
|
||||
```
|
||||
|
||||
End with the recommendation, not a fix.
|
||||
|
||||
## Worked Example
|
||||
|
||||
**Failure:**
|
||||
```
|
||||
--- FAIL: TestInvoiceParser_HandlesEmptyPDF (0.00s)
|
||||
parser_test.go:47: panic: runtime error: index out of range [0] with length 0
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
HYPOTHESIS 1: parser indexes into pages[0] before checking len(pages) > 0; empty PDFs produce a zero-page document
|
||||
VERIFY: rg -n 'pages\[0\]' internal/parser/
|
||||
EXPECTED IF CORRECT: at least one site reads pages[0] without a preceding length check
|
||||
|
||||
HYPOTHESIS 2: the test fixture is a zero-byte file rather than a valid empty PDF; pdf library returns nil pages slice instead of empty
|
||||
VERIFY: ls -la testdata/empty.pdf && file testdata/empty.pdf
|
||||
EXPECTED IF CORRECT: file size 0 bytes or "data" rather than "PDF document"
|
||||
|
||||
HYPOTHESIS 3: a recently changed dependency reordered the page-extraction API; pages[0] now refers to metadata, not content
|
||||
VERIFY: git log --oneline -10 -- go.sum | grep -i pdf
|
||||
EXPECTED IF CORRECT: a pdf-library bump in the last few commits
|
||||
|
||||
RECOMMENDED NEXT STEP: Run VERIFY for hypothesis 1 first.
|
||||
```
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
| Anti-Pattern | Why It Fails |
|
||||
|---|---|
|
||||
| "Maybe try restarting the service" | Not a mechanism. Not falsifiable. Teaches nothing if it works. |
|
||||
| "Could be a race condition" | Mechanism without specifics. Which two operations race? On what state? |
|
||||
| "Let me add some print statements and see" | Skips hypothesis generation. Generates noise, not understanding. |
|
||||
| Answering "what's the fix?" from a report with no artifact | Hypothesising into a vacuum. The output looks like analysis, which is what makes it worse than saying "I need the log". |
|
||||
| Single hypothesis presented as fact | If you are sure, write the regression test, do not run a debug skill. |
|
||||
| Mixing hypotheses with fix suggestions | The skill is diagnose-only. The fix is a TDD task on its hypothesis. |
|
||||
|
||||
## Brain MCP Integration
|
||||
|
||||
The brain holds prior debug sessions across the project. Use it to skip rediscovering known failure modes.
|
||||
|
||||
**At debug start:**
|
||||
- Run `brain_query` with the error message snippet + the package name. On an intake stop you have neither — query the symptom and the component instead ("signed artifact missing CI"), which is worth doing precisely because it may name the artifact to ask for. Past sessions may have logged identical or similar failures with their resolved hypotheses.
|
||||
- **A hit is evidence, so cite it inline in the hypothesis it informs** — `(brain: <entry-name>)` — rather than mentioning it once at the top. If a prior entry is why a hypothesis ranks first, the reader needs that at the hypothesis, not in a preamble. If a prior entry contradicts your ranking, say so and rank it anyway if the evidence here is better; the brain records what was true then.
|
||||
|
||||
**After a hypothesis is confirmed:**
|
||||
- Run `brain_write` with the failure signature → confirmed mechanism. Future debug sessions on the same area get the answer immediately.
|
||||
|
||||
**Never:**
|
||||
- Run `brain_write` for an unconfirmed hypothesis. Speculation in the brain pollutes future queries.
|
||||
|
||||
### Logging
|
||||
|
||||
Call `session_log` once at the end of every phase to record the outcome.
|
||||
Pass-rate is computed downstream by the `/pass-rate` HTTP endpoint, which
|
||||
treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
|
||||
**At end of each phase:**
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "debug", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", project_root: "<absolute path>"}`
|
||||
|
||||
**Phases for this skill:** intake, read-failure, generate-hypotheses, output
|
||||
|
||||
`intake` exists so that refusing correctly is recordable. A run that stops for want of a
|
||||
run id has done the right thing and logs `intake` / `pass`; without that phase the
|
||||
refusal logs as a failed `read-failure`, and a metric that penalises the skill's best
|
||||
behaviour teaches the next model to hypothesise into the vacuum instead.
|
||||
|
||||
**Status semantics:**
|
||||
- `pass` — the phase's intended outcome was reached.
|
||||
- `fail` — the phase's intended outcome was NOT reached.
|
||||
- `skip` — phase was skipped intentionally.
|
||||
|
||||
**Why this matters:** pass-rate is what a future routing decision would be based on — whether a given call can be served by a local model instead of a cloud one. A skill that never logs contributes no evidence either way.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- After a hypothesis is confirmed, load `tdd` skill — write a failing regression test that proves the bug exists, then fix it.
|
||||
- For test failures specifically caused by mock-vs-real divergence, also load `tdd/references/testing-anti-patterns.md`.
|
||||
- Load `code-review` skill if the diagnosis surfaces a structural issue (god object, shotgun surgery) rather than a pointwise bug.
|
||||
|
||||
Techniques kept in `debug/references/`, inherited from the deleted
|
||||
`superpowers-systematic-debugging` (#14):
|
||||
|
||||
- `root-cause-tracing.md` — load when the failure surfaces far from its trigger and the
|
||||
stack is the only thread back to it.
|
||||
- `defense-in-depth.md` — load after a root cause is confirmed, to decide which layers
|
||||
should have caught it.
|
||||
- `condition-based-waiting.md` — load whenever a timeout appears anywhere in the report,
|
||||
including as one of the fixes already tried. A bumped timeout is a symptom. Not during an
|
||||
intake stop: if you are not analysing yet, a symptom-analysis reference is on the wrong
|
||||
side of the gate.
|
||||
- `find-polluter.sh` — run when a test passes alone and fails in the suite, or when
|
||||
something in the tree appears that no test admits to creating.
|
||||
|
||||
## Escalation
|
||||
|
||||
Diagnose only — Iron Law 3 is already an escalation rule: the fix is a separate TDD cycle,
|
||||
not this skill's output.
|
||||
|
||||
Stop and hand back when: the report contains no failure text and no locator, in which case
|
||||
name the specific artifact you need (run id, job log, stack trace) and stop rather than
|
||||
hypothesising into a vacuum; or the evidence needed to discriminate between your top two
|
||||
hypotheses requires access you do not have.
|
||||
@@ -0,0 +1,158 @@
|
||||
// Complete implementation of condition-based waiting utilities
|
||||
// From: Lace test infrastructure improvements (2025-10-03)
|
||||
// Context: Fixed 15 flaky tests by replacing arbitrary timeouts
|
||||
|
||||
import type { ThreadManager } from '~/threads/thread-manager';
|
||||
import type { LaceEvent, LaceEventType } from '~/threads/types';
|
||||
|
||||
/**
|
||||
* Wait for a specific event type to appear in thread
|
||||
*
|
||||
* @param threadManager - The thread manager to query
|
||||
* @param threadId - Thread to check for events
|
||||
* @param eventType - Type of event to wait for
|
||||
* @param timeoutMs - Maximum time to wait (default 5000ms)
|
||||
* @returns Promise resolving to the first matching event
|
||||
*
|
||||
* Example:
|
||||
* await waitForEvent(threadManager, agentThreadId, 'TOOL_RESULT');
|
||||
*/
|
||||
export function waitForEvent(
|
||||
threadManager: ThreadManager,
|
||||
threadId: string,
|
||||
eventType: LaceEventType,
|
||||
timeoutMs = 5000
|
||||
): Promise<LaceEvent> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const startTime = Date.now();
|
||||
|
||||
const check = () => {
|
||||
const events = threadManager.getEvents(threadId);
|
||||
const event = events.find((e) => e.type === eventType);
|
||||
|
||||
if (event) {
|
||||
resolve(event);
|
||||
} else if (Date.now() - startTime > timeoutMs) {
|
||||
reject(new Error(`Timeout waiting for ${eventType} event after ${timeoutMs}ms`));
|
||||
} else {
|
||||
setTimeout(check, 10); // Poll every 10ms for efficiency
|
||||
}
|
||||
};
|
||||
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a specific number of events of a given type
|
||||
*
|
||||
* @param threadManager - The thread manager to query
|
||||
* @param threadId - Thread to check for events
|
||||
* @param eventType - Type of event to wait for
|
||||
* @param count - Number of events to wait for
|
||||
* @param timeoutMs - Maximum time to wait (default 5000ms)
|
||||
* @returns Promise resolving to all matching events once count is reached
|
||||
*
|
||||
* Example:
|
||||
* // Wait for 2 AGENT_MESSAGE events (initial response + continuation)
|
||||
* await waitForEventCount(threadManager, agentThreadId, 'AGENT_MESSAGE', 2);
|
||||
*/
|
||||
export function waitForEventCount(
|
||||
threadManager: ThreadManager,
|
||||
threadId: string,
|
||||
eventType: LaceEventType,
|
||||
count: number,
|
||||
timeoutMs = 5000
|
||||
): Promise<LaceEvent[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const startTime = Date.now();
|
||||
|
||||
const check = () => {
|
||||
const events = threadManager.getEvents(threadId);
|
||||
const matchingEvents = events.filter((e) => e.type === eventType);
|
||||
|
||||
if (matchingEvents.length >= count) {
|
||||
resolve(matchingEvents);
|
||||
} else if (Date.now() - startTime > timeoutMs) {
|
||||
reject(
|
||||
new Error(
|
||||
`Timeout waiting for ${count} ${eventType} events after ${timeoutMs}ms (got ${matchingEvents.length})`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
setTimeout(check, 10);
|
||||
}
|
||||
};
|
||||
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for an event matching a custom predicate
|
||||
* Useful when you need to check event data, not just type
|
||||
*
|
||||
* @param threadManager - The thread manager to query
|
||||
* @param threadId - Thread to check for events
|
||||
* @param predicate - Function that returns true when event matches
|
||||
* @param description - Human-readable description for error messages
|
||||
* @param timeoutMs - Maximum time to wait (default 5000ms)
|
||||
* @returns Promise resolving to the first matching event
|
||||
*
|
||||
* Example:
|
||||
* // Wait for TOOL_RESULT with specific ID
|
||||
* await waitForEventMatch(
|
||||
* threadManager,
|
||||
* agentThreadId,
|
||||
* (e) => e.type === 'TOOL_RESULT' && e.data.id === 'call_123',
|
||||
* 'TOOL_RESULT with id=call_123'
|
||||
* );
|
||||
*/
|
||||
export function waitForEventMatch(
|
||||
threadManager: ThreadManager,
|
||||
threadId: string,
|
||||
predicate: (event: LaceEvent) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 5000
|
||||
): Promise<LaceEvent> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const startTime = Date.now();
|
||||
|
||||
const check = () => {
|
||||
const events = threadManager.getEvents(threadId);
|
||||
const event = events.find(predicate);
|
||||
|
||||
if (event) {
|
||||
resolve(event);
|
||||
} else if (Date.now() - startTime > timeoutMs) {
|
||||
reject(new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`));
|
||||
} else {
|
||||
setTimeout(check, 10);
|
||||
}
|
||||
};
|
||||
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
// Usage example from actual debugging session:
|
||||
//
|
||||
// BEFORE (flaky):
|
||||
// ---------------
|
||||
// const messagePromise = agent.sendMessage('Execute tools');
|
||||
// await new Promise(r => setTimeout(r, 300)); // Hope tools start in 300ms
|
||||
// agent.abort();
|
||||
// await messagePromise;
|
||||
// await new Promise(r => setTimeout(r, 50)); // Hope results arrive in 50ms
|
||||
// expect(toolResults.length).toBe(2); // Fails randomly
|
||||
//
|
||||
// AFTER (reliable):
|
||||
// ----------------
|
||||
// const messagePromise = agent.sendMessage('Execute tools');
|
||||
// await waitForEventCount(threadManager, threadId, 'TOOL_CALL', 2); // Wait for tools to start
|
||||
// agent.abort();
|
||||
// await messagePromise;
|
||||
// await waitForEventCount(threadManager, threadId, 'TOOL_RESULT', 2); // Wait for results
|
||||
// expect(toolResults.length).toBe(2); // Always succeeds
|
||||
//
|
||||
// Result: 60% pass rate → 100%, 40% faster execution
|
||||
@@ -0,0 +1,115 @@
|
||||
# Condition-Based Waiting
|
||||
|
||||
## Overview
|
||||
|
||||
Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.
|
||||
|
||||
**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes.
|
||||
|
||||
## When to Use
|
||||
|
||||
```dot
|
||||
digraph when_to_use {
|
||||
"Test uses setTimeout/sleep?" [shape=diamond];
|
||||
"Testing timing behavior?" [shape=diamond];
|
||||
"Document WHY timeout needed" [shape=box];
|
||||
"Use condition-based waiting" [shape=box];
|
||||
|
||||
"Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"];
|
||||
"Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"];
|
||||
"Testing timing behavior?" -> "Use condition-based waiting" [label="no"];
|
||||
}
|
||||
```
|
||||
|
||||
**Use when:**
|
||||
- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`)
|
||||
- Tests are flaky (pass sometimes, fail under load)
|
||||
- Tests timeout when run in parallel
|
||||
- Waiting for async operations to complete
|
||||
|
||||
**Don't use when:**
|
||||
- Testing actual timing behavior (debounce, throttle intervals)
|
||||
- Always document WHY if using arbitrary timeout
|
||||
|
||||
## Core Pattern
|
||||
|
||||
```typescript
|
||||
// ❌ BEFORE: Guessing at timing
|
||||
await new Promise(r => setTimeout(r, 50));
|
||||
const result = getResult();
|
||||
expect(result).toBeDefined();
|
||||
|
||||
// ✅ AFTER: Waiting for condition
|
||||
await waitFor(() => getResult() !== undefined);
|
||||
const result = getResult();
|
||||
expect(result).toBeDefined();
|
||||
```
|
||||
|
||||
## Quick Patterns
|
||||
|
||||
| Scenario | Pattern |
|
||||
|----------|---------|
|
||||
| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` |
|
||||
| Wait for state | `waitFor(() => machine.state === 'ready')` |
|
||||
| Wait for count | `waitFor(() => items.length >= 5)` |
|
||||
| Wait for file | `waitFor(() => fs.existsSync(path))` |
|
||||
| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` |
|
||||
|
||||
## Implementation
|
||||
|
||||
Generic polling function:
|
||||
```typescript
|
||||
async function waitFor<T>(
|
||||
condition: () => T | undefined | null | false,
|
||||
description: string,
|
||||
timeoutMs = 5000
|
||||
): Promise<T> {
|
||||
const startTime = Date.now();
|
||||
|
||||
while (true) {
|
||||
const result = condition();
|
||||
if (result) return result;
|
||||
|
||||
if (Date.now() - startTime > timeoutMs) {
|
||||
throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);
|
||||
}
|
||||
|
||||
await new Promise(r => setTimeout(r, 10)); // Poll every 10ms
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU
|
||||
**✅ Fix:** Poll every 10ms
|
||||
|
||||
**❌ No timeout:** Loop forever if condition never met
|
||||
**✅ Fix:** Always include timeout with clear error
|
||||
|
||||
**❌ Stale data:** Cache state before loop
|
||||
**✅ Fix:** Call getter inside loop for fresh data
|
||||
|
||||
## When Arbitrary Timeout IS Correct
|
||||
|
||||
```typescript
|
||||
// Tool ticks every 100ms - need 2 ticks to verify partial output
|
||||
await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition
|
||||
await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior
|
||||
// 200ms = 2 ticks at 100ms intervals - documented and justified
|
||||
```
|
||||
|
||||
**Requirements:**
|
||||
1. First wait for triggering condition
|
||||
2. Based on known timing (not guessing)
|
||||
3. Comment explaining WHY
|
||||
|
||||
## Real-World Impact
|
||||
|
||||
From debugging session (2025-10-03):
|
||||
- Fixed 15 flaky tests across 3 files
|
||||
- Pass rate: 60% → 100%
|
||||
- Execution time: 40% faster
|
||||
- No more race conditions
|
||||
@@ -0,0 +1,122 @@
|
||||
# Defense-in-Depth Validation
|
||||
|
||||
## Overview
|
||||
|
||||
When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.
|
||||
|
||||
**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible.
|
||||
|
||||
## Why Multiple Layers
|
||||
|
||||
Single validation: "We fixed the bug"
|
||||
Multiple layers: "We made the bug impossible"
|
||||
|
||||
Different layers catch different cases:
|
||||
- Entry validation catches most bugs
|
||||
- Business logic catches edge cases
|
||||
- Environment guards prevent context-specific dangers
|
||||
- Debug logging helps when other layers fail
|
||||
|
||||
## The Four Layers
|
||||
|
||||
### Layer 1: Entry Point Validation
|
||||
**Purpose:** Reject obviously invalid input at API boundary
|
||||
|
||||
```typescript
|
||||
function createProject(name: string, workingDirectory: string) {
|
||||
if (!workingDirectory || workingDirectory.trim() === '') {
|
||||
throw new Error('workingDirectory cannot be empty');
|
||||
}
|
||||
if (!existsSync(workingDirectory)) {
|
||||
throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
|
||||
}
|
||||
if (!statSync(workingDirectory).isDirectory()) {
|
||||
throw new Error(`workingDirectory is not a directory: ${workingDirectory}`);
|
||||
}
|
||||
// ... proceed
|
||||
}
|
||||
```
|
||||
|
||||
### Layer 2: Business Logic Validation
|
||||
**Purpose:** Ensure data makes sense for this operation
|
||||
|
||||
```typescript
|
||||
function initializeWorkspace(projectDir: string, sessionId: string) {
|
||||
if (!projectDir) {
|
||||
throw new Error('projectDir required for workspace initialization');
|
||||
}
|
||||
// ... proceed
|
||||
}
|
||||
```
|
||||
|
||||
### Layer 3: Environment Guards
|
||||
**Purpose:** Prevent dangerous operations in specific contexts
|
||||
|
||||
```typescript
|
||||
async function gitInit(directory: string) {
|
||||
// In tests, refuse git init outside temp directories
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
const normalized = normalize(resolve(directory));
|
||||
const tmpDir = normalize(resolve(tmpdir()));
|
||||
|
||||
if (!normalized.startsWith(tmpDir)) {
|
||||
throw new Error(
|
||||
`Refusing git init outside temp dir during tests: ${directory}`
|
||||
);
|
||||
}
|
||||
}
|
||||
// ... proceed
|
||||
}
|
||||
```
|
||||
|
||||
### Layer 4: Debug Instrumentation
|
||||
**Purpose:** Capture context for forensics
|
||||
|
||||
```typescript
|
||||
async function gitInit(directory: string) {
|
||||
const stack = new Error().stack;
|
||||
logger.debug('About to git init', {
|
||||
directory,
|
||||
cwd: process.cwd(),
|
||||
stack,
|
||||
});
|
||||
// ... proceed
|
||||
}
|
||||
```
|
||||
|
||||
## Applying the Pattern
|
||||
|
||||
When you find a bug:
|
||||
|
||||
1. **Trace the data flow** - Where does bad value originate? Where used?
|
||||
2. **Map all checkpoints** - List every point data passes through
|
||||
3. **Add validation at each layer** - Entry, business, environment, debug
|
||||
4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it
|
||||
|
||||
## Example from Session
|
||||
|
||||
Bug: Empty `projectDir` caused `git init` in source code
|
||||
|
||||
**Data flow:**
|
||||
1. Test setup → empty string
|
||||
2. `Project.create(name, '')`
|
||||
3. `WorkspaceManager.createWorkspace('')`
|
||||
4. `git init` runs in `process.cwd()`
|
||||
|
||||
**Four layers added:**
|
||||
- Layer 1: `Project.create()` validates not empty/exists/writable
|
||||
- Layer 2: `WorkspaceManager` validates projectDir not empty
|
||||
- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests
|
||||
- Layer 4: Stack trace logging before git init
|
||||
|
||||
**Result:** All 1847 tests passed, bug impossible to reproduce
|
||||
|
||||
## Key Insight
|
||||
|
||||
All four layers were necessary. During testing, each layer caught bugs the others missed:
|
||||
- Different code paths bypassed entry validation
|
||||
- Mocks bypassed business logic checks
|
||||
- Edge cases on different platforms needed environment guards
|
||||
- Debug logging identified structural misuse
|
||||
|
||||
**Don't stop at one validation point.** Add checks at every layer.
|
||||
Executable
+63
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
# Bisection script to find which test creates unwanted files/state
|
||||
# Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>
|
||||
# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'
|
||||
|
||||
set -e
|
||||
|
||||
if [ $# -ne 2 ]; then
|
||||
echo "Usage: $0 <file_to_check> <test_pattern>"
|
||||
echo "Example: $0 '.git' 'src/**/*.test.ts'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
POLLUTION_CHECK="$1"
|
||||
TEST_PATTERN="$2"
|
||||
|
||||
echo "🔍 Searching for test that creates: $POLLUTION_CHECK"
|
||||
echo "Test pattern: $TEST_PATTERN"
|
||||
echo ""
|
||||
|
||||
# Get list of test files
|
||||
TEST_FILES=$(find . -path "$TEST_PATTERN" | sort)
|
||||
TOTAL=$(echo "$TEST_FILES" | wc -l | tr -d ' ')
|
||||
|
||||
echo "Found $TOTAL test files"
|
||||
echo ""
|
||||
|
||||
COUNT=0
|
||||
for TEST_FILE in $TEST_FILES; do
|
||||
COUNT=$((COUNT + 1))
|
||||
|
||||
# Skip if pollution already exists
|
||||
if [ -e "$POLLUTION_CHECK" ]; then
|
||||
echo "⚠️ Pollution already exists before test $COUNT/$TOTAL"
|
||||
echo " Skipping: $TEST_FILE"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "[$COUNT/$TOTAL] Testing: $TEST_FILE"
|
||||
|
||||
# Run the test
|
||||
npm test "$TEST_FILE" > /dev/null 2>&1 || true
|
||||
|
||||
# Check if pollution appeared
|
||||
if [ -e "$POLLUTION_CHECK" ]; then
|
||||
echo ""
|
||||
echo "🎯 FOUND POLLUTER!"
|
||||
echo " Test: $TEST_FILE"
|
||||
echo " Created: $POLLUTION_CHECK"
|
||||
echo ""
|
||||
echo "Pollution details:"
|
||||
ls -la "$POLLUTION_CHECK"
|
||||
echo ""
|
||||
echo "To investigate:"
|
||||
echo " npm test $TEST_FILE # Run just this test"
|
||||
echo " cat $TEST_FILE # Review test code"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "✅ No polluter found - all tests clean!"
|
||||
exit 0
|
||||
@@ -0,0 +1,169 @@
|
||||
# Root Cause Tracing
|
||||
|
||||
## Overview
|
||||
|
||||
Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom.
|
||||
|
||||
**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source.
|
||||
|
||||
## When to Use
|
||||
|
||||
```dot
|
||||
digraph when_to_use {
|
||||
"Bug appears deep in stack?" [shape=diamond];
|
||||
"Can trace backwards?" [shape=diamond];
|
||||
"Fix at symptom point" [shape=box];
|
||||
"Trace to original trigger" [shape=box];
|
||||
"BETTER: Also add defense-in-depth" [shape=box];
|
||||
|
||||
"Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"];
|
||||
"Can trace backwards?" -> "Trace to original trigger" [label="yes"];
|
||||
"Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"];
|
||||
"Trace to original trigger" -> "BETTER: Also add defense-in-depth";
|
||||
}
|
||||
```
|
||||
|
||||
**Use when:**
|
||||
- Error happens deep in execution (not at entry point)
|
||||
- Stack trace shows long call chain
|
||||
- Unclear where invalid data originated
|
||||
- Need to find which test/code triggers the problem
|
||||
|
||||
## The Tracing Process
|
||||
|
||||
### 1. Observe the Symptom
|
||||
```
|
||||
Error: git init failed in ~/project/packages/core
|
||||
```
|
||||
|
||||
### 2. Find Immediate Cause
|
||||
**What code directly causes this?**
|
||||
```typescript
|
||||
await execFileAsync('git', ['init'], { cwd: projectDir });
|
||||
```
|
||||
|
||||
### 3. Ask: What Called This?
|
||||
```typescript
|
||||
WorktreeManager.createSessionWorktree(projectDir, sessionId)
|
||||
→ called by Session.initializeWorkspace()
|
||||
→ called by Session.create()
|
||||
→ called by test at Project.create()
|
||||
```
|
||||
|
||||
### 4. Keep Tracing Up
|
||||
**What value was passed?**
|
||||
- `projectDir = ''` (empty string!)
|
||||
- Empty string as `cwd` resolves to `process.cwd()`
|
||||
- That's the source code directory!
|
||||
|
||||
### 5. Find Original Trigger
|
||||
**Where did empty string come from?**
|
||||
```typescript
|
||||
const context = setupCoreTest(); // Returns { tempDir: '' }
|
||||
Project.create('name', context.tempDir); // Accessed before beforeEach!
|
||||
```
|
||||
|
||||
## Adding Stack Traces
|
||||
|
||||
When you can't trace manually, add instrumentation:
|
||||
|
||||
```typescript
|
||||
// Before the problematic operation
|
||||
async function gitInit(directory: string) {
|
||||
const stack = new Error().stack;
|
||||
console.error('DEBUG git init:', {
|
||||
directory,
|
||||
cwd: process.cwd(),
|
||||
nodeEnv: process.env.NODE_ENV,
|
||||
stack,
|
||||
});
|
||||
|
||||
await execFileAsync('git', ['init'], { cwd: directory });
|
||||
}
|
||||
```
|
||||
|
||||
**Critical:** Use `console.error()` in tests (not logger - may not show)
|
||||
|
||||
**Run and capture:**
|
||||
```bash
|
||||
npm test 2>&1 | grep 'DEBUG git init'
|
||||
```
|
||||
|
||||
**Analyze stack traces:**
|
||||
- Look for test file names
|
||||
- Find the line number triggering the call
|
||||
- Identify the pattern (same test? same parameter?)
|
||||
|
||||
## Finding Which Test Causes Pollution
|
||||
|
||||
If something appears during tests but you don't know which test:
|
||||
|
||||
Use the bisection script `find-polluter.sh` in this directory:
|
||||
|
||||
```bash
|
||||
./find-polluter.sh '.git' 'src/**/*.test.ts'
|
||||
```
|
||||
|
||||
Runs tests one-by-one, stops at first polluter. See script for usage.
|
||||
|
||||
## Real Example: Empty projectDir
|
||||
|
||||
**Symptom:** `.git` created in `packages/core/` (source code)
|
||||
|
||||
**Trace chain:**
|
||||
1. `git init` runs in `process.cwd()` ← empty cwd parameter
|
||||
2. WorktreeManager called with empty projectDir
|
||||
3. Session.create() passed empty string
|
||||
4. Test accessed `context.tempDir` before beforeEach
|
||||
5. setupCoreTest() returns `{ tempDir: '' }` initially
|
||||
|
||||
**Root cause:** Top-level variable initialization accessing empty value
|
||||
|
||||
**Fix:** Made tempDir a getter that throws if accessed before beforeEach
|
||||
|
||||
**Also added defense-in-depth:**
|
||||
- Layer 1: Project.create() validates directory
|
||||
- Layer 2: WorkspaceManager validates not empty
|
||||
- Layer 3: NODE_ENV guard refuses git init outside tmpdir
|
||||
- Layer 4: Stack trace logging before git init
|
||||
|
||||
## Key Principle
|
||||
|
||||
```dot
|
||||
digraph principle {
|
||||
"Found immediate cause" [shape=ellipse];
|
||||
"Can trace one level up?" [shape=diamond];
|
||||
"Trace backwards" [shape=box];
|
||||
"Is this the source?" [shape=diamond];
|
||||
"Fix at source" [shape=box];
|
||||
"Add validation at each layer" [shape=box];
|
||||
"Bug impossible" [shape=doublecircle];
|
||||
"NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
|
||||
|
||||
"Found immediate cause" -> "Can trace one level up?";
|
||||
"Can trace one level up?" -> "Trace backwards" [label="yes"];
|
||||
"Can trace one level up?" -> "NEVER fix just the symptom" [label="no"];
|
||||
"Trace backwards" -> "Is this the source?";
|
||||
"Is this the source?" -> "Trace backwards" [label="no - keeps going"];
|
||||
"Is this the source?" -> "Fix at source" [label="yes"];
|
||||
"Fix at source" -> "Add validation at each layer";
|
||||
"Add validation at each layer" -> "Bug impossible";
|
||||
}
|
||||
```
|
||||
|
||||
**NEVER fix just where the error appears.** Trace back to find the original trigger.
|
||||
|
||||
## Stack Trace Tips
|
||||
|
||||
**In tests:** Use `console.error()` not logger - logger may be suppressed
|
||||
**Before operation:** Log before the dangerous operation, not after it fails
|
||||
**Include context:** Directory, cwd, environment variables, timestamps
|
||||
**Capture stack:** `new Error().stack` shows complete call chain
|
||||
|
||||
## Real-World Impact
|
||||
|
||||
From debugging session (2025-10-03):
|
||||
- Found root cause through 5-level trace
|
||||
- Fixed at source (getter validation)
|
||||
- Added 4 layers of defense
|
||||
- 1847 tests passed, zero pollution
|
||||
@@ -0,0 +1,163 @@
|
||||
---
|
||||
name: discovery-framing
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Problem-before-solution discovery/framing method"
|
||||
use_when: "Framing/validating a problem before any solution; opportunity sizing"
|
||||
description: Run the discovery / framing phase of product innovation — define and quantify a focused customer problem BEFORE any solution exists. Four movements: understand the problem space, learn about customers, identify and size problems, decide pursue/table/kill. Produces a problem brief per prioritized opportunity. Use when an idea is still vague, when someone is jumping to solutions before the problem is validated, when scoping early research, or when deciding which problems are worth pursuing. Trigger phrases include "frame the problem", "discovery", "problem statement", "is this worth building", "early research", "opportunity sizing", "we have an idea for", "how might we", "what problem are we solving".
|
||||
---
|
||||
|
||||
# Discovery / Framing
|
||||
|
||||
The phase before solutioning. Goal: **define and quantify a focused customer problem,
|
||||
tied to a specific target segment, validated with external evidence** — so that later
|
||||
investment rides on a real problem, not a pet idea. Products built on a validated problem
|
||||
have a materially higher success rate; solving an unvalidated problem builds something
|
||||
that solves nothing.
|
||||
|
||||
This is the de-identified pattern. When run for a named client, the wrapper (their phase
|
||||
names, internal tools, region structure, named teams) stays in the client boundary.
|
||||
|
||||
> Pairs with [[stage-gate-review]] (this is the Frame→Concept gate's content) and the brain
|
||||
> principle on solutions-looking-for-problems. Killing a bad problem here is the cheapest
|
||||
> kill you will ever make.
|
||||
|
||||
---
|
||||
|
||||
## The four movements
|
||||
|
||||
```
|
||||
1. Understand the problem space → 2. Learn about customers
|
||||
↓ ↓
|
||||
4. Decide: pursue / table / kill ← 3. Identify & size problems
|
||||
```
|
||||
|
||||
Typical envelope: weeks, not months; cheap. The whole point is to de-risk before spend.
|
||||
|
||||
### 1. Understand the problem space (the ecosystem)
|
||||
Map the field before judging any idea. You are not validating a solution — you are
|
||||
learning the terrain.
|
||||
- **Ecosystem analysis** — top trends, market size (the whole pie, not your slice),
|
||||
key players (end users, customers, intermediaries), competitors and their gaps.
|
||||
- **Value-exchange map** — list every player; for each, the qualitative + quantitative
|
||||
value flowing to/from them; score it. **A scalable ecosystem has roughly equal value
|
||||
per player** — lopsided value = it won't scale across the chain. This is the single
|
||||
most overlooked check.
|
||||
- **External-forces scan (PESTL + localization)** — Political, Economic, Social,
|
||||
Technological, Legal, plus local/regulatory constraints that break the business model
|
||||
in a given market.
|
||||
|
||||
### 2. Learn about customers and end-customers
|
||||
- **Personas / design targets** — behaviours, needs & values, pain points, gains. Keep
|
||||
them universal where possible (cut across segments), specific where it matters.
|
||||
- **Journey maps** — steps & touchpoints, emotional valence per step, pain points and
|
||||
opportunity areas. Separate the customer journey from the end-customer journey.
|
||||
- **Assumptions → hypotheses** — dump everything you believe true about the target
|
||||
(quantity over quality), then prioritize on a **risk × certainty grid**: attack the
|
||||
assumptions that are *high risk AND low certainty* first. Sort each into
|
||||
**Desirability** (do they want it?), **Feasibility** (can we build it?),
|
||||
**Viability** (can we make money?). Convert each prioritized assumption into a testable
|
||||
hypothesis: *"If we do X, then Y will happen"* — falsifiable, specific outcome.
|
||||
- **Validate externally** — research with real customers/end-customers (interviews,
|
||||
focus groups, surveys, diaries). Record per persona: assumption → learning →
|
||||
validated/invalidated. **External validation is non-negotiable** — a problem confirmed
|
||||
only internally is not confirmed.
|
||||
|
||||
### 3. Identify and size the problems
|
||||
- **Problem statement** — one tight form: *"[who] needs a way to [need], but [compelling
|
||||
insight from research]."* The insight cites where/how the opportunity actually manifests,
|
||||
not a guess.
|
||||
- **Total Addressable Problem (TAP)** — *not* market size. Market size is the pie-in-the-sky
|
||||
figure. TAP = (what would they pay to solve *this specific problem*) × (how many have it),
|
||||
summed across use cases. A subset of the market, honestly bounded. Sizing the problem —
|
||||
not the market — is what makes prioritization real.
|
||||
|
||||
### 4. Determine next steps
|
||||
- **Prioritize** by TAP × strategic fit.
|
||||
- **Pursue / table / kill** — every problem gets one verdict. *Kill* is a first-class
|
||||
output, not a failure; a tabled problem is parked with its reason.
|
||||
- **How-Might-We** — reframe each pursued pain point as an open question to spark
|
||||
solution ideation. **Use verbs, not nouns — never pre-pack a solution into the HMW.**
|
||||
("HMW increase awareness…" not "HMW build an app that…").
|
||||
- **Problem brief** — one per pursued opportunity (see below). This is the deliverable that
|
||||
carries into the solutioning gate.
|
||||
|
||||
---
|
||||
|
||||
## The Problem Brief (required deliverable)
|
||||
|
||||
A problem brief, not a solution brief. Fields:
|
||||
|
||||
1. **Problem** — "We believe [user/customer/market] needs a way to [need], because/but/
|
||||
surprisingly [insight]." Quantitative proof where possible.
|
||||
2. **Customer** — who has it; segment specifics; their pain points / desired gains.
|
||||
3. **End-customer** (if different) — who you're ultimately innovating for.
|
||||
4. **Why it matters** — to them and to you; what you observed that makes this a priority.
|
||||
5. **Ecosystem** — relevant signals, localization needs, competitive/comparative landscape.
|
||||
6. **Total Addressable Problem** — the bounded value of the problem.
|
||||
7. **Thought-starters / HMW** — reframed questions, no solutions.
|
||||
8. **Desired value & outcomes** — impact if the problem were solved.
|
||||
9. **Strategic benefit** — how success is measured for the business; strategy fit.
|
||||
|
||||
If a brief drifts into describing a solution, it has failed — send it back to the problem.
|
||||
|
||||
---
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- **Solution smuggling** — an HMW or brief that already names the answer. The discovery
|
||||
is over before it began.
|
||||
- **Internal-only validation** — "we all agree it's a problem." That is conviction, not
|
||||
evidence. See [[stage-gate-gate-killers]].
|
||||
- **Market size as problem size** — quoting a $XXbn TAM to justify a narrow bet.
|
||||
- **Skipping the kill** — every idea "has potential." A discovery phase that never kills a
|
||||
problem is theatre.
|
||||
- **Lopsided value exchange** — a solution that enriches one player and starves another;
|
||||
it will not scale no matter how good the UX.
|
||||
|
||||
---
|
||||
|
||||
## Operator judgment (hard-won)
|
||||
|
||||
### Compressing discovery by stakes
|
||||
- **High-stakes bet:** run all four movements hard — especially external customer research
|
||||
and the riskiest-assumption tests. Don't thin the validation.
|
||||
- **Low-stakes bet:** keep movement 1 (ecosystem) + movement 3 (problem statement + a rough
|
||||
size). Size with **TAM / SAM / SOM** instead of a full Total Addressable Problem build.
|
||||
- **Customer research can be skipped or AI-simulated for low stakes** — a well-framed agent,
|
||||
prompted *as* the target persona, can give a directional read fast. Treat this as a
|
||||
cheap directional signal only — it is **not** external validation and never clears a
|
||||
high-stakes desirability assumption. Use it to decide whether real research is worth doing.
|
||||
|
||||
### The bar for "externally validated"
|
||||
No fixed floor — case by case. The invariant is the *posture*, not the count: **go looking
|
||||
for disproving evidence, not reinforcing evidence.** A problem survives discovery when you
|
||||
tried to kill it with real external input and couldn't — not when N people nodded along.
|
||||
(Same disease as a faked gate — see [[stage-gate-gate-killers]].)
|
||||
|
||||
### Tell for solution smuggling
|
||||
The solution is described **crisply and confidently**, but the moment you ask *whose* problem
|
||||
and *how do you know*, the answer goes **fuzzy** — the need is vague, the validation is
|
||||
hand-wavy. Crisp solution + fuzzy problem = reverse-engineered justification. Stop and reframe.
|
||||
|
||||
### War-story patterns (de-identified)
|
||||
- **Sized big, fizzled in reality.** A problem that scored a large TAP/TAM but never
|
||||
converted to sustained real-world usage. Lesson: **problem size ≠ adoption.** A big
|
||||
addressable problem measures willingness to *care*, not willingness to *change behavior*.
|
||||
Add a "would they actually switch/use it repeatedly?" test before trusting a large size.
|
||||
- **Tabled/iceboxed a valid problem others then won.** A real problem killed or parked on
|
||||
weak conviction or bad timing, which competitors later executed well. Lesson: **the kill
|
||||
is not free.** Killing protects against sunk cost, but a wrong table is also a cost —
|
||||
record *why* you tabled and a signal that would reopen it, so a right problem killed for
|
||||
the wrong reason can come back.
|
||||
|
||||
> Named instances of both war stories are client-tagged and held out of this public skill
|
||||
> pending client-store decision. The transferable lesson lives here; the wrapper stays out.
|
||||
|
||||
## Escalation
|
||||
|
||||
Advisory. Produces a problem brief; commits to nothing.
|
||||
|
||||
Stop and hand back when: the evidence needed to size a problem requires talking to
|
||||
customers you cannot reach. Sizing a problem from assumptions and presenting it as
|
||||
discovery is worse than saying the number is unknown — it launders a guess into a brief
|
||||
that later decisions will cite.
|
||||
@@ -0,0 +1,171 @@
|
||||
---
|
||||
name: dream
|
||||
surfaces: [claude-code, library, chat]
|
||||
summary: "Reflective consolidation pass over an agent's memory directory"
|
||||
use_when: "Pruning/merging memory files, rebuilding a memory index"
|
||||
description: >
|
||||
Run a "dream" — a reflective memory consolidation pass over an agent's memory
|
||||
directory. Use this skill whenever the user says "dream", "run a dream", "consolidate
|
||||
my memory files", "clean up my MEMORY.md", or asks Claude to do a memory maintenance
|
||||
pass, prune stale notes, or reorganize topic files. Also trigger when the user wants
|
||||
to rebuild a memory index, merge duplicate facts, or convert relative dates in notes
|
||||
to absolute ones. This is an agentic, multi-phase workflow — always use this skill
|
||||
rather than improvising the steps.
|
||||
---
|
||||
|
||||
# Dream — Memory Consolidation Skill
|
||||
|
||||
You are performing a **dream**: a reflective, agentic pass over a memory directory.
|
||||
Your goal is to synthesize recent signal into durable, well-organized memory so that
|
||||
future sessions can orient quickly.
|
||||
|
||||
---
|
||||
|
||||
## Pre-flight
|
||||
|
||||
Before starting, confirm:
|
||||
1. **Where is the memory directory?** Ask the user if not obvious from context.
|
||||
Common locations: `~/memory/`, `~/.agent/memory/`, `./memory/`, a path in an env var like `$MEMORY_DIR`.
|
||||
2. **Are there transcripts or daily logs to scan?** Ask if not obvious.
|
||||
3. **Any topics to skip or treat as sensitive?**
|
||||
|
||||
Once confirmed, proceed through the four phases in order. Narrate each phase briefly as you go.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Orient
|
||||
|
||||
**Goal**: Get a map of what exists before touching anything.
|
||||
|
||||
```bash
|
||||
ls -la <memory_dir>/
|
||||
cat <memory_dir>/MEMORY.md
|
||||
```
|
||||
|
||||
For each file listed (excluding MEMORY.md):
|
||||
- Read or skim it (first 40–60 lines is usually enough unless it's small).
|
||||
- Note: topic, approximate recency, any obvious staleness or duplication.
|
||||
|
||||
Build a mental inventory:
|
||||
- Files present, rough line counts
|
||||
- Topics covered
|
||||
- Any files that look abandoned, mislabeled, or overlapping
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Gather Recent Signal
|
||||
|
||||
**Goal**: Find new facts, corrections, and drift since the last dream.
|
||||
|
||||
Check in this order:
|
||||
|
||||
1. **Daily logs** — read recent entries (last 7–14 days).
|
||||
Look for: new decisions, changed preferences, completed projects, new relationships/tools.
|
||||
|
||||
2. **Drifted facts** — scan existing topic files for statements that may now be false.
|
||||
Examples: "currently evaluating X" (did they pick one?), "planning to do Y" (done or dropped?), relative dates like "last week" or "recently".
|
||||
|
||||
3. **Transcripts** — only grep narrowly if there's a specific gap.
|
||||
Avoid bulk-reading transcripts; it's slow and noisy. Use targeted patterns:
|
||||
```bash
|
||||
grep -r "decided\|switched to\|no longer\|now using\|moved to" <transcripts_dir>/ | tail -40
|
||||
```
|
||||
|
||||
Collect a list of **updates to make**: new facts, corrections, removals.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Consolidate
|
||||
|
||||
**Goal**: Apply the updates. Leave memory files cleaner and more accurate than you found them.
|
||||
|
||||
For each topic file:
|
||||
|
||||
- **Merge duplicates**: if the same fact appears in two files, keep it in the more specific one and remove from the general one.
|
||||
- **Convert relative dates**: replace "last week", "recently", "a few months ago" with an absolute date (use the current date as reference; estimate if necessary and note the uncertainty).
|
||||
- **Delete contradicted facts**: if a new fact supersedes an old one, remove the old one outright — don't leave both.
|
||||
- **Tighten language**: convert vague hedges ("probably uses", "might be") to definite statements where the evidence supports it, or remove if genuinely unknown.
|
||||
- **Add new facts** from Phase 2 to the appropriate topic file. Create a new topic file if no good home exists.
|
||||
|
||||
After editing files, do a final pass:
|
||||
```bash
|
||||
grep -n "last week\|recently\|a few months\|soon\|currently planning" <memory_dir>/*.md
|
||||
```
|
||||
Clean up any remaining relative time references.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Prune and Index
|
||||
|
||||
**Goal**: Rebuild MEMORY.md as a clean, navigable index under 200 lines.
|
||||
|
||||
**MEMORY.md structure**:
|
||||
```markdown
|
||||
# Memory Index
|
||||
_Last updated: YYYY-MM-DD_
|
||||
|
||||
## Overview
|
||||
One short paragraph: who this agent is, primary context, most important standing facts.
|
||||
|
||||
## Topic Files
|
||||
| File | Contents | Last updated |
|
||||
|------|----------|-------------|
|
||||
| person.md | Identity, preferences, background | YYYY-MM-DD |
|
||||
| projects.md | Active and recent projects | YYYY-MM-DD |
|
||||
| tools.md | Stack, infra, dev environment | YYYY-MM-DD |
|
||||
| ... | ... | ... |
|
||||
|
||||
## Quick Facts
|
||||
- Bullet list of the 10–15 most frequently-needed facts (role, location, key tools, etc.)
|
||||
|
||||
## Recent Changes
|
||||
- Bullet list of what changed in this dream (so the next session knows what's fresh)
|
||||
```
|
||||
|
||||
Rules:
|
||||
- Remove any pointers to files that no longer exist.
|
||||
- Add pointers for any new files created in Phase 3.
|
||||
- Keep Quick Facts ≤ 15 bullets — this is for speed, not completeness.
|
||||
- Recent Changes section replaces itself each dream (don't accumulate).
|
||||
- Total MEMORY.md length: **200 lines max**.
|
||||
|
||||
---
|
||||
|
||||
## Output
|
||||
|
||||
After completing all four phases, return a **dream summary** to the user:
|
||||
|
||||
```
|
||||
## Dream complete — YYYY-MM-DD
|
||||
|
||||
### What changed
|
||||
- [file]: [what was updated]
|
||||
- MEMORY.md: rebuilt index, N topic files indexed
|
||||
|
||||
### Facts added
|
||||
- ...
|
||||
|
||||
### Facts removed / corrected
|
||||
- ...
|
||||
|
||||
### Files created
|
||||
- ...
|
||||
|
||||
### Files deleted or merged
|
||||
- ...
|
||||
|
||||
### Still uncertain / needs follow-up
|
||||
- ...
|
||||
```
|
||||
|
||||
Keep it concise — a few bullets per section, not exhaustive diffs. The goal is for the user to quickly confirm the dream went well and catch any mistakes.
|
||||
|
||||
---
|
||||
|
||||
## Tips and Edge Cases
|
||||
|
||||
- **No MEMORY.md exists yet**: create one from scratch using the structure above. Treat all existing files as "first time indexed".
|
||||
- **Memory dir is empty**: create MEMORY.md and a starter `scratch.md` noting the date and that the memory system is new.
|
||||
- **Conflicting facts with no clear resolution**: note both in the file with a date stamp and flag in "Still uncertain" section of the summary.
|
||||
- **Large transcript dumps**: resist reading them in full. Grep is your friend. If you must read, read the last N lines only.
|
||||
- **Files with sensitive content**: if the user flagged topics to skip, skip them entirely — don't even open them.
|
||||
@@ -0,0 +1,195 @@
|
||||
---
|
||||
name: experiment-spec
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Rigorous experiment spec — falsifiable hypothesis, quantitative acceptance, null-result protocol"
|
||||
use_when: "Scoping a research/ML phase instead of a feature"
|
||||
description: Write a rigorous experiment spec for a research phase before any code or training runs. Use instead of feature-spec for scientific/ML research projects. Enforces falsifiable hypothesis, quantitative acceptance criteria, baseline comparison, and null-result protocol.
|
||||
---
|
||||
|
||||
# Experiment Spec
|
||||
|
||||
## Overview
|
||||
|
||||
An experiment spec is the scientific contract for one research phase or experiment, written before any implementation or training begins. It is the research analogue of `feature-spec` — same discipline, different vocabulary.
|
||||
|
||||
**Core principle:** If you cannot write a falsifiable hypothesis with a quantitative acceptance criterion, you do not understand the experiment well enough to run it.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Starting a new research phase (Phase 0, Phase 1, etc.)
|
||||
- Running any experiment that will produce metrics used to make a go/no-go decision
|
||||
- Any time the question is "does X work?" rather than "build X"
|
||||
- Before touching training code, data, or hyperparameters for a new question
|
||||
|
||||
**When NOT to use:**
|
||||
- Implementing a specific component whose behaviour is already defined by a phase spec (use `feature-spec` instead)
|
||||
- Exploratory data analysis with no hypothesis (use a notebook; note it as EDA)
|
||||
- Bug fixes or refactors
|
||||
|
||||
## Iron Laws
|
||||
|
||||
1. **The hypothesis must be falsifiable.** "JEPA is promising" is not a hypothesis. "JEPA embeddings will achieve silhouette > 0.35 on held-out data" is. If you cannot state conditions under which the hypothesis is false, it is not a hypothesis.
|
||||
2. **Acceptance criteria must be quantitative and pre-registered.** Write the number before you run the experiment. Moving the goalposts after seeing results is p-hacking.
|
||||
3. **A baseline is mandatory.** Every experiment must compare against at least one simpler baseline. "Better than nothing" is not a baseline.
|
||||
4. **A null-result protocol is mandatory.** State what you will conclude and do if the hypothesis is rejected. "Try harder" is not a protocol.
|
||||
5. **The training cutoff is sacred.** No post-cutoff data informs any decision in the spec or implementation.
|
||||
|
||||
## Spec Template
|
||||
|
||||
```markdown
|
||||
# Experiment Spec: [Phase N — Short Name]
|
||||
|
||||
## Hypothesis
|
||||
|
||||
> "[Falsifiable claim]: We believe [X] will produce [Y], measurable by [Z]."
|
||||
|
||||
State conditions under which this hypothesis is FALSE.
|
||||
|
||||
## Background
|
||||
|
||||
Why this experiment? What does it build on? What prior result or decision motivates it?
|
||||
(2–4 sentences. Reference DECISIONS.md or brain wing entries where relevant.)
|
||||
|
||||
## Design
|
||||
|
||||
### Data
|
||||
- Source, date range, pairs/assets, features used
|
||||
- Train / validation / test split (respect training cutoff)
|
||||
|
||||
### Model / method
|
||||
- Architecture, configuration, key hyperparameters
|
||||
- What is being varied vs. held fixed
|
||||
|
||||
### Baseline
|
||||
- What simpler method is being compared against?
|
||||
- Why is this the right baseline?
|
||||
|
||||
### Ablations (if any)
|
||||
- What variants will be run to isolate the effect being studied?
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] [Primary criterion — quantitative threshold on primary metric]
|
||||
- [ ] [Baseline comparison — e.g. "exceeds baseline by >X%"]
|
||||
- [ ] [Reproducibility — reruns within ±Y% of reported metric]
|
||||
- [ ] [Collapse/sanity check — e.g. "PC1/rolling-HV correlation < 0.85"]
|
||||
|
||||
## Out of Scope
|
||||
|
||||
What this experiment explicitly does NOT answer, even if related.
|
||||
Anything plausibly in scope that is deferred goes here.
|
||||
|
||||
## Null Result Protocol
|
||||
|
||||
If the primary acceptance criterion is NOT met:
|
||||
- What do we conclude?
|
||||
- What is the next step? (Investigate X, pivot to Y, terminate programme)
|
||||
- What gets written to the brain and results/summaries/?
|
||||
|
||||
## Risks
|
||||
|
||||
What could go wrong, and how would it be detected?
|
||||
At least one risk must be listed.
|
||||
```
|
||||
|
||||
## Worked Example
|
||||
|
||||
```markdown
|
||||
# Experiment Spec: Phase 0 — SSL Feasibility Gate
|
||||
|
||||
## Hypothesis
|
||||
|
||||
> We believe that a masked autoencoder (MAE) trained on FX hourly data will produce
|
||||
> latent embeddings that show structural separability by volatility regime without
|
||||
> explicit regime labels, measurable by silhouette score > 0.20 on held-out 2023 data.
|
||||
|
||||
This hypothesis is FALSE if silhouette score ≤ 0.20 on the held-out evaluation.
|
||||
|
||||
## Background
|
||||
|
||||
Before investing in JEPA-specific machinery, we need to confirm that SSL-based
|
||||
representation learning can find regime structure in FX time-series at all. MAE is
|
||||
the simplest SSL baseline — if it cannot find structure, JEPA will not either.
|
||||
Added post Full Grill (2026-05-27). See DECISIONS.md: "Phase 0: SSL feasibility gate".
|
||||
|
||||
## Design
|
||||
|
||||
### Data
|
||||
- Source: DUKASCopy, EUR/USD hourly, 2008–2022 (train), 2023 (held-out test)
|
||||
- Features: log-return, rolling 20-period HV, VIX (daily interpolated to hourly)
|
||||
- Regime label (for evaluation only, not training): rolling 30-day HV percentile,
|
||||
binary high/low threshold at 50th percentile
|
||||
|
||||
### Model
|
||||
- Masked Autoencoder: 1D temporal masking (mask contiguous 24h window)
|
||||
- Encoder: 3-layer 1D CNN + positional encoding
|
||||
- Decoder: 2-layer MLP reconstructing masked segment
|
||||
- Context window: 120 hours (5 days)
|
||||
|
||||
### Baseline
|
||||
- PCA on raw feature vectors (same window) — tests whether any dimensionality
|
||||
reduction shows regime structure, not just SSL
|
||||
|
||||
### Ablations
|
||||
- Masking horizon: K ∈ {8h, 24h, 72h} — does horizon affect embedding quality?
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Silhouette score > 0.20 on held-out 2023 data (k-means, k=3, vs. HV regime label)
|
||||
- [ ] MAE silhouette exceeds PCA baseline silhouette
|
||||
- [ ] Rerun within ±10% of reported silhouette
|
||||
- [ ] PC1 / rolling-HV correlation < 0.95 (not purely encoding volatility level)
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- JEPA implementation (Phase 1)
|
||||
- Multi-pair training (Phase 1+)
|
||||
- VaR or ES computation
|
||||
- Any use of post-2023 data
|
||||
|
||||
## Null Result Protocol
|
||||
|
||||
If silhouette ≤ 0.20:
|
||||
- Conclude: SSL cannot reliably find regime structure in EUR/USD hourly data with
|
||||
these features at this resolution
|
||||
- Next step: investigate whether (a) hourly resolution is too noisy (try daily),
|
||||
(b) 3 features are insufficient, or (c) regime label definition is too coarse
|
||||
- Record result in results/summaries/phase-0-null.md and brain wing jepa-fx/failures/
|
||||
|
||||
## Risks
|
||||
|
||||
- Encoder collapses to near-constant output: detect via reconstruction loss plateau
|
||||
in first 10 epochs; mitigation: add batch norm, reduce learning rate
|
||||
- Regime label too coarse (binary HV): silhouette may be low even with good structure;
|
||||
mitigation: also evaluate with 4-class label (HV quartiles)
|
||||
```
|
||||
|
||||
## Common Failure Modes
|
||||
|
||||
| Failure mode | What it looks like | Fix |
|
||||
|---|---|---|
|
||||
| Non-falsifiable hypothesis | "JEPA shows promise" | Rewrite with a number |
|
||||
| Post-hoc criteria | Threshold chosen after seeing results | Write the number first, commit the spec |
|
||||
| No baseline | Silhouette of 0.30 sounds good until PCA achieves 0.35 | Always include a dumber method |
|
||||
| Missing null protocol | "We'll figure it out if it fails" | Write it now — it forces clarity about what you're actually betting on |
|
||||
| Cutoff violation | Architecture choice informed by 2024 data patterns | Never open the test set during development |
|
||||
|
||||
## Brain MCP Integration
|
||||
|
||||
**At spec start:**
|
||||
- `brain_query wing=jepa-fx hall=decisions` — load current architectural decisions
|
||||
- `brain_query wing=jepa-fx hall=failures` — load known failure modes; address them in Risks section
|
||||
|
||||
**After spec is approved:**
|
||||
- `brain_write` to `jepa-fx/hypotheses/` with the hypothesis and acceptance criteria
|
||||
|
||||
**After experiment concludes:**
|
||||
- `brain_write` to `jepa-fx/failures/` with any new failure modes discovered
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "experiment-spec", phase: "conclude", final_status: "pass" | "fail" | "skip", message: "<one-line outcome>"}`
|
||||
|
||||
## Cross-References
|
||||
|
||||
- Use `feature-spec` for implementing a specific component within an already-specced phase
|
||||
- Use `grill-me` on the spec before running the experiment if the hypothesis feels shaky
|
||||
- Use `tdd` once the spec is approved — each acceptance criterion maps to a test
|
||||
- Use `session-retrospective` after the experiment concludes
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: feature-spec
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Implementation-level feature spec (tighter than spec-driven-dev)"
|
||||
use_when: "Scoping one feature inside an already-specced project"
|
||||
description: Write a tight implementation-level spec for a single feature or component before coding it. Use after a project-level spec exists (see spec-driven-dev) and you need to nail down one feature inside it.
|
||||
---
|
||||
|
||||
@@ -29,6 +32,90 @@ A feature spec is the implementation-level contract for one feature or component
|
||||
2. **An "Out of scope" section is mandatory.** If you do not draw the boundary, the implementer (you, future-you, or another agent) will guess wrong.
|
||||
3. **Every technical decision in "Technical approach" must have a rationale.** A decision is any choice where a reasonable alternative existed and was not taken. "Use Postgres" is not a decision; "use Postgres because the rest of the stack uses it and we need transactions across user + invoice" is.
|
||||
|
||||
## EARS-lite acceptance criteria
|
||||
|
||||
Measurable criteria answer "is it done?". They do not always answer "what should it do
|
||||
when X happens?" — and behavioural requirements written as prose are where ambiguity
|
||||
survives review. For any criterion that is conditional or event-driven, use EARS-lite
|
||||
instead of prose:
|
||||
|
||||
```
|
||||
WHEN <trigger> THE SYSTEM SHALL <observable response>
|
||||
WHILE <state> THE SYSTEM SHALL <observable response>
|
||||
IF <unwanted condition> THEN THE SYSTEM SHALL <observable response>
|
||||
```
|
||||
|
||||
There is a fourth, unconditional form. Use it for invariants — the properties that must
|
||||
hold with no trigger at all, which are usually the ones that matter most:
|
||||
|
||||
```
|
||||
THE SYSTEM SHALL <observable response>
|
||||
```
|
||||
|
||||
Worked, deliberately from a domain unlike whatever you are specifying:
|
||||
|
||||
```
|
||||
THE SYSTEM SHALL reject a firmware image whose signature does not verify
|
||||
WHEN a sensor reports a temperature above the shutdown limit
|
||||
THE SYSTEM SHALL open the contactor within 200ms
|
||||
WHILE the contactor is open
|
||||
THE SYSTEM SHALL refuse every start command
|
||||
IF a sensor reading is missing or stale by more than one interval
|
||||
THEN THE SYSTEM SHALL treat it as above the limit
|
||||
```
|
||||
|
||||
The example is off-domain on purpose. An on-domain example gets copied: a spec written
|
||||
against an invoice-flavoured example inherited a requirement about extraction confidence
|
||||
that its feature request never mentioned, and the author only noticed on review. Read
|
||||
the shapes, not the content.
|
||||
|
||||
Each conditional line names a trigger and one observable response, which usually maps
|
||||
onto a single test. The `WHILE` and unconditional forms are universally quantified —
|
||||
"every start command", "a firmware image" — so they map onto a property or a set of
|
||||
cases, not one assertion. That is still worth writing: it closes the requirements half
|
||||
of the audit trail, which is otherwise issue-body prose.
|
||||
|
||||
**This is an option, not a replacement.** Threshold criteria ("p99 < 200ms under 100
|
||||
RPS") stay as they are — EARS phrasing adds nothing to a number. Use it for conditional
|
||||
behaviour, error handling, and state-dependent rules.
|
||||
|
||||
## Context snapshot
|
||||
|
||||
The executor of this spec will not see the conversation that produced it, and often
|
||||
cannot see the architecture document either — a different agent, a fresh session, a
|
||||
different machine. A spec that says "see the architecture doc" hands them a lookup they
|
||||
may not be able to perform.
|
||||
|
||||
So inline the specific facts this spec depends on, not the whole document:
|
||||
|
||||
```markdown
|
||||
## Context snapshot
|
||||
Taken from <source> @ <commit-or-date>. Re-check before implementing if stale.
|
||||
|
||||
- The mailbox poller writes rows to `invoices` with `state = 'received'`.
|
||||
- The payment-file writer reads `invoices` and emits one file per batch.
|
||||
- Money is int64 minor units plus an ISO-4217 code; float is banned repo-wide.
|
||||
```
|
||||
|
||||
Three rules keep this from becoming a second source of truth, which is the real
|
||||
objection to inlining and a good one:
|
||||
|
||||
1. **Snapshot what the implementer cannot look up and cannot proceed without.** That is
|
||||
wider than "facts this spec's decisions rest on" — a table name may underpin no
|
||||
decision here and still be the thing that blocks writing the migration. It is still
|
||||
narrower than the whole document: if a fact changes nothing and blocks nothing, leave
|
||||
it out, and say what you left out so the omission reads as deliberate.
|
||||
2. **Always cite source and version.** A snapshot without provenance cannot be
|
||||
revalidated, and an unrevalidatable copy is exactly the drift everyone fears.
|
||||
3. **If you could not read the source either, say so in those words.** Writing a spec
|
||||
against a document you cannot open is common and is not a reason to skip the section
|
||||
— it is a reason to mark the whole block `UNVERIFIED — reconstructed, not read`, and
|
||||
to make confirming it the implementer's first task, before the first failing test.
|
||||
An unmarked guess is the only genuinely dangerous version.
|
||||
4. **The snapshot is evidence, not authority.** Open the section with one line to that
|
||||
effect — "where this disagrees with the source, the source wins and this spec is
|
||||
stale" — rather than annotating each fact.
|
||||
|
||||
## Spec Template
|
||||
|
||||
```markdown
|
||||
@@ -39,12 +126,21 @@ A feature spec is the implementation-level contract for one feature or component
|
||||
What problem does this feature solve? For whom? Why now?
|
||||
(2-4 sentences. If you cannot answer "why now," ask before writing the rest.)
|
||||
|
||||
## Context snapshot
|
||||
[Facts the implementer cannot look up, with source and version. See "Context snapshot" above.]
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- [ ] Criterion 1 — measurable and verifiable
|
||||
- [ ] Criterion 2 — measurable and verifiable
|
||||
- [ ] Criterion 3 — measurable and verifiable
|
||||
|
||||
### Behavioural criteria (EARS-lite)
|
||||
|
||||
[Conditional and event-driven behaviour, one trigger and one observable response per
|
||||
line. Not checkboxes — these are properties, and several need more than one test each.
|
||||
Omit the subsection entirely if the feature has no conditional behaviour.]
|
||||
|
||||
## Constraints
|
||||
|
||||
Non-negotiable requirements the solution must satisfy.
|
||||
@@ -149,7 +245,7 @@ Pass-rate is computed downstream by the `/pass-rate` HTTP endpoint, which
|
||||
treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
|
||||
**At end of each phase:**
|
||||
- `session_log` with `{skill: "feature-spec", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", duration_ms: <wall-clock>, project_root: "<absolute path>"}`
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "feature-spec", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", project_root: "<absolute path>"}`
|
||||
|
||||
**Phases for this skill:** draft
|
||||
|
||||
@@ -158,11 +254,7 @@ treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
- `fail` — the phase's intended outcome was NOT reached (spec rejected, blocked on unresolved questions).
|
||||
- `skip` — phase was skipped intentionally.
|
||||
|
||||
**Why this matters:** the routing pod (Plan 6) reads pass-rate to decide whether to route a future call to a local model. If your skill never logs, the routing pod sees no data.
|
||||
|
||||
## Mode 2 Routing Note
|
||||
|
||||
Spec writing requires interpretation of intent and tradeoff reasoning — work where Claude generally outperforms a 9-13B local model. This skill is intentionally **not** a Mode 2 routing candidate. In Mode 2, the routing layer should leave `feature-spec` calls on Claude.
|
||||
**Why this matters:** pass-rate is what a future routing decision would be based on — whether a given call can be served by a local model instead of a cloud one. A skill that never logs contributes no evidence either way.
|
||||
|
||||
## Cross-References
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
---
|
||||
name: gitea-ci
|
||||
description: End-to-end Gitea CI/CD setup with self-hosted act_runner, quality gate pipeline, buildah image build, k3s deploy, and GitHub mirror. Covers act_runner-specific gotchas that are not documented anywhere.
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Gitea CI/CD pipeline with act_runner, buildah, k3s, GitHub mirror"
|
||||
use_when: "Setting up or debugging CI on this infra"
|
||||
description: End-to-end Gitea CI/CD setup with self-hosted act_runner, quality gate pipeline, shared buildctl image-build script, k3s deploy, and GitHub mirror. Covers act_runner-specific gotchas that are not documented anywhere.
|
||||
---
|
||||
|
||||
# Gitea CI/CD Pipeline Setup
|
||||
@@ -31,7 +34,7 @@ Before writing any YAML, collect the following. Use AskUserQuestion for anything
|
||||
| Container registry | Ask or check existing config | `localhost:5000` on koala, or external |
|
||||
| k3s namespace | k8s/ manifests or ask | Deploy target |
|
||||
| GitHub mirror repo | Ask | Target for the mirror job |
|
||||
| Image name | Ask or derive from repo name | Used in buildah + k3s steps |
|
||||
| Image name | Ask or derive from repo name | Used in buildctl + k3s steps |
|
||||
|
||||
Check the project's `CLAUDE.md` for infra notes first — often this answers most questions without needing to ask.
|
||||
|
||||
@@ -133,35 +136,46 @@ jobs:
|
||||
echo "version-tag=${REF#refs/tags/}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# infra#309: do NOT paste a build implementation here. The estate has
|
||||
# exactly one, mathias/infra's ci-templates/build-image.sh, and each
|
||||
# repo carries a byte-identical copy at .gitea/build-image.sh that a
|
||||
# drift gate keeps current.
|
||||
#
|
||||
# Copying the implementation is what made the buildah->buildctl
|
||||
# migration (infra#241) an eleven-repo sprint, and what left this very
|
||||
# skill handing out the broken version for weeks after the app repos
|
||||
# were fixed. Per-repo differences are INPUTS, not edits to the copy.
|
||||
#
|
||||
# To adopt in a new repo:
|
||||
# 1. add the repo to mathias/infra ci-templates/adopters.txt
|
||||
# 2. run `task ci:sync` in mathias/infra -- it writes the copy
|
||||
# 3. commit .gitea/build-image.sh in your repo
|
||||
# 4. call it as below
|
||||
#
|
||||
# Skipping step 1 leaves the copy unmanaged: it works today and falls
|
||||
# silently behind the next time the canonical file changes.
|
||||
#
|
||||
# Inputs: IMAGE (required, usually the workflow-level env), SHA_TAG,
|
||||
# VERSION_TAG, GIT_SHA, IMAGE_SOURCE, BUILD_ARGS, EXTRA_LABELS,
|
||||
# CONTEXT, DOCKERFILE_DIR, DOCKERFILE_NAME, PUSH_LATEST. Read the
|
||||
# canonical file's header for the full list.
|
||||
#
|
||||
# `bash <script>`, not a direct exec: a file written through the Gitea
|
||||
# API lands 0644, and CI that depends on a file mode is a trap.
|
||||
- name: Build and push to local registry
|
||||
run: |
|
||||
REGISTRY="localhost:5000"
|
||||
REF="${REGISTRY}/${{ env.IMAGE }}:${{ steps.meta.outputs.sha-tag }}"
|
||||
buildah build \
|
||||
--label "org.opencontainers.image.revision=${{ github.sha }}" \
|
||||
--label "org.opencontainers.image.source=${{ github.repositoryUrl }}" \
|
||||
-t ${REF} \
|
||||
-t ${REGISTRY}/${{ env.IMAGE }}:latest \
|
||||
.
|
||||
buildah push --tls-verify=false ${REF}
|
||||
buildah push --tls-verify=false ${REGISTRY}/${{ env.IMAGE }}:latest
|
||||
[[ -n "${{ steps.meta.outputs.version-tag }}" ]] && \
|
||||
buildah push --tls-verify=false \
|
||||
${REF} \
|
||||
${REGISTRY}/${{ env.IMAGE }}:${{ steps.meta.outputs.version-tag }} || true
|
||||
echo "✓ Image pushed to ${REF}"
|
||||
env:
|
||||
SHA_TAG: ${{ steps.meta.outputs.sha-tag }}
|
||||
VERSION_TAG: ${{ steps.meta.outputs.version-tag }}
|
||||
GIT_SHA: ${{ github.sha }}
|
||||
IMAGE_SOURCE: ${{ github.repositoryUrl }}
|
||||
run: bash .gitea/build-image.sh
|
||||
|
||||
- name: Smoke test
|
||||
run: |
|
||||
REGISTRY="localhost:5000"
|
||||
REF="${REGISTRY}/${{ env.IMAGE }}:${{ steps.meta.outputs.sha-tag }}"
|
||||
CNAME="smoke-${{ steps.meta.outputs.sha-tag }}"
|
||||
sudo k3s ctr images pull --plain-http ${REF}
|
||||
OUTPUT=$(timeout 5 sudo k3s ctr run --rm ${REF} ${CNAME} /<binary-name> 2>&1 || true)
|
||||
sudo k3s ctr containers delete ${CNAME} 2>/dev/null || true
|
||||
echo "$OUTPUT" | grep -q "<project-name>" \
|
||||
&& echo "✓ Smoke test passed" \
|
||||
|| echo "⚠ Smoke test inconclusive: $OUTPUT"
|
||||
# No smoke test step. The one this skill used to recommend ran
|
||||
# `sudo k3s ctr run` against the host's containerd -- that worked when
|
||||
# the runner was the Arch host, and is impossible now that it is a pod:
|
||||
# no sudo, no ctr, no containerd socket (`sudo: command not found`).
|
||||
# The deploy job's `Verify rollout` + `Confirm pod running new image`
|
||||
# below assert the same property against the real workload.
|
||||
|
||||
# ── 3. Deploy to k3s ────────────────────────────────────────────────────────
|
||||
deploy:
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: grill-me
|
||||
surfaces: [claude-code, library, chat]
|
||||
summary: "Structured plan interrogation — Quick Poke, Full Grill, Pre-mortem"
|
||||
use_when: "Stress-testing a plan before committing; end of Diamond 1; before promoting to pre-prod"
|
||||
description: Critically interrogates plans, ideas, and proposals to make them sharper, more robust, and better grounded — with the explicit goal of producing a meaningfully better plan by the end. Use this skill whenever the user wants to stress-test a plan, prepare for hard questions, check if an idea is ready to act on, validate a hypothesis, or explicitly asks to be challenged, questioned, or grilled. Also trigger when a conversation has been exploring an idea for a while and it's time to converge — use this skill to check if the idea is actually ready. Trigger phrases include "grill me", "challenge this", "poke holes", "am I missing something", "is this ready", "stress-test this", "devil's advocate", "what am I not seeing".
|
||||
---
|
||||
|
||||
@@ -145,3 +148,12 @@ This skill maps to the **convergence moments** in the Double Diamond workflow:
|
||||
- **Mid-Diamond 2 (Develop):** Use Quick Poke when an agent's experiment result is ambiguous and you're deciding whether to continue or pivot.
|
||||
|
||||
The skill does NOT replace human judgment at convergence points — it sharpens the plan so that judgment is better informed.
|
||||
|
||||
## Escalation
|
||||
|
||||
Advisory. Produces sharper questions and a better plan; decides nothing.
|
||||
|
||||
Stop and hand back when: the plan's weak point is a decision that is the operator's to
|
||||
make rather than a gap in reasoning — surface it as a question with options and a
|
||||
recommendation, and do not grill past it. Also stop when a round produces no new
|
||||
objection: interrogation past that point manufactures doubt rather than finding it.
|
||||
@@ -0,0 +1,163 @@
|
||||
---
|
||||
name: lineage
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Backward decision archaeology — was this tried before, and does the reason it failed still hold"
|
||||
use_when: "Before proposing something that feels new; when an idea keeps resurfacing; when you inherit code whose reason is gone"
|
||||
description: Backward decision archaeology. Find out whether an idea was already tried here, why it was dropped, and whether that reason still applies — using git history, decision records and the issue tracker rather than asking whoever is still around. Use before proposing a change that feels novel, when inheriting unexplained code, or when the same idea keeps being re-litigated.
|
||||
---
|
||||
|
||||
# Lineage
|
||||
|
||||
## Overview
|
||||
|
||||
Most "new" ideas in an established codebase are revivals. The valuable question is never
|
||||
"is this a good idea" in the abstract — it is **"was this tried, what killed it, and is
|
||||
the killer still alive?"**
|
||||
|
||||
A past failure is not evidence against trying again. It is context for trying again
|
||||
differently, and the difference between those two readings is usually one commit message.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Before proposing something that feels new in a codebase older than you
|
||||
- When an idea keeps resurfacing and being re-argued from scratch
|
||||
- When you inherit code and cannot tell whether a constraint is load-bearing or vestigial
|
||||
- Before writing an ADR — the reason a thing was dropped belongs in your Context section
|
||||
|
||||
**Do not use for:** code you wrote this week, or a question the current code answers.
|
||||
Archaeology on a live construction site is just reading.
|
||||
|
||||
## The tool
|
||||
|
||||
```sh
|
||||
skills/lineage/lineage.sh <term> [repo-path]
|
||||
```
|
||||
|
||||
Runs the searches people skip because they are fiddly to type. In particular
|
||||
`git log -S<term>`, which finds commits where the term's **occurrence count changed** —
|
||||
so it surfaces the *removal* as well as the introduction. A plain `--grep` never finds a
|
||||
deletion, and the deletion is the whole point.
|
||||
|
||||
It also lists files that once carried the term and no longer exist, and names the two
|
||||
sources it cannot search for you.
|
||||
|
||||
**A no-match is not a finding.** The first version of this tool said a null meant "this is
|
||||
new here"; a pressure test caught it asserting exactly that about the most-discussed
|
||||
removed feature in this repo — the search term merely had a space in it. One string
|
||||
against one repo proves nothing. Try at least three variants (the identifier name, a
|
||||
one-word form, the name it would have had) and the brain and tracker searches before
|
||||
telling anyone an idea is novel. This is the same rule as the anti-patterns table below,
|
||||
and it is there because the tool broke it.
|
||||
|
||||
Note also that `--grep` takes a regex and `-S` takes a literal string, so a term
|
||||
containing `.`, `[`, `*` or `+` matches differently in the two halves of the output.
|
||||
|
||||
## The sequence
|
||||
|
||||
**1. Search on the identifier, not the concept.** If the thing had a name in the code —
|
||||
a function, a flag, a config key — `git log --all -S<name>` typically returns exactly two
|
||||
commits, its birth and its death, on one screen. That is the fastest path to the answer in
|
||||
this whole sequence.
|
||||
|
||||
Path-scoped log (`git log --all -- <file>`) is the weaker move and it is the one people
|
||||
reach for: a function deleted from a file that still exists is the *dominant* removal
|
||||
shape, and the path search buries it under every other commit that touched the file.
|
||||
|
||||
Concept words are the fallback, and they are lossy — a term with a space in it will miss
|
||||
the record entirely. Try several spellings before you conclude anything.
|
||||
|
||||
**2. Read the removal commit's full body, not its subject.**
|
||||
|
||||
```sh
|
||||
git log -1 --format=%B <sha>
|
||||
git show --stat <sha>
|
||||
```
|
||||
|
||||
This is where the answer almost always is. A subject line says *what*; the body says
|
||||
*why*, and the why is what you came for. Read the diff too — what was removed alongside
|
||||
it tells you how load-bearing it was.
|
||||
|
||||
**3. Search outside git — that is where this estate keeps its reasoning.** Two sources,
|
||||
both routinely decisive, neither reachable from a commit log:
|
||||
|
||||
- **The brain** (`brain_query`). Postmortems and generalized rules live there. In the run
|
||||
that shaped this skill, the single best artifact — the rule abstracted from the incident,
|
||||
with detection one-liners — came from the brain and from nowhere else.
|
||||
- **The issue tracker, including comments.** The commit records *that* something was
|
||||
removed; the argument for it is usually in a comment. Search closed issues especially —
|
||||
a closed issue is where a decision usually is.
|
||||
|
||||
A git-only search finds the what and misses the why.
|
||||
|
||||
**4. Test whether the failure conditions still hold — empirically, not from the record.**
|
||||
This is the step that makes the whole exercise worth doing, and it is the one that gets
|
||||
hand-waved. Write the conditions down as separate claims, then **run a command per claim**:
|
||||
|
||||
| Claim from the record | How you check it today |
|
||||
|---|---|
|
||||
| "absolute links break across two path roots" | `readlink` one, `test -e` it on this host |
|
||||
| "it is gitignored, so nobody sees the rot" | `grep` the ignore file |
|
||||
| "the detector does not cover it" | `grep` the detector for the path it scans |
|
||||
|
||||
Twenty seconds each, and it converts *"the record claims X"* into *"X is true right now"* —
|
||||
which is the only form of the answer worth giving. A constraint that has since been
|
||||
removed turns a dead idea live; one that is still true kills a revival on the spot.
|
||||
|
||||
**5. Separate the mechanism from the goal.** A revival proposal usually bundles both, and
|
||||
they can have opposite verdicts: the goal is still worth wanting, the mechanism is the one
|
||||
that failed. Splitting them is often the whole finding — you end up agreeing with the
|
||||
proposer and rejecting their implementation, which is a far more useful answer than yes
|
||||
or no.
|
||||
|
||||
## What "it was tried and failed" can mean
|
||||
|
||||
| Reading | Tell | What to do |
|
||||
|---|---|---|
|
||||
| **Structurally impossible** | The removal commit says *why* it cannot work, not that it broke | Believe it. Look for a different mechanism for the same goal |
|
||||
| **Failed under conditions that changed** | The blocker names a version, a host, a tool that has since moved | Re-open it, citing what changed |
|
||||
| **Failed on execution** | It broke, was reverted, nobody diagnosed it | Genuinely undecided. The revival is legitimate; budget for the diagnosis |
|
||||
| **Never actually tried** | Discussed, an issue exists, no commit | There is no evidence either way. Say so rather than inheriting someone's pessimism |
|
||||
| **Still there, in a different shape** | The idea returned under another name | The most missable one — check before you build it twice |
|
||||
|
||||
## Output
|
||||
|
||||
Answer the question that was asked, then show your work:
|
||||
|
||||
- **Verdict** — tried / not tried / tried and later restored differently
|
||||
- **The decisive artifact** — commit sha, issue number, or ADR, so the reader can check
|
||||
- **What killed it**, quoted from the source rather than paraphrased
|
||||
- **Whether that still applies**, per condition, not as a single yes or no
|
||||
|
||||
If the decisive evidence is one commit message, quote it. A conclusion that makes the
|
||||
reader re-run your search has not saved them anything.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
| Anti-pattern | Why it fails |
|
||||
|---|---|
|
||||
| `--grep` only | Finds discussion, misses deletions. The deletion is the evidence |
|
||||
| Reading the commit subject and stopping | Subjects say what; you need why |
|
||||
| Treating a past failure as a verdict | Conditions change. That is the entire question |
|
||||
| Git-only search | The argument is usually in the issue tracker |
|
||||
| "It was tried and it failed" with no sha | Unverifiable, and it will be re-litigated next quarter |
|
||||
| Assuming absence means it was never considered | It may have been rejected in a conversation. Say what you searched |
|
||||
|
||||
## Escalation
|
||||
|
||||
Read-only. Reports what the record says; changes nothing and revives nothing.
|
||||
|
||||
Stop and hand back when: the record is genuinely silent — no commit, no issue, no ADR.
|
||||
State what you searched and that nothing exists, rather than inferring intent from
|
||||
absence. Someone deciding not to build a thing and nobody ever considering it look
|
||||
identical in git, and only one of them is an argument.
|
||||
|
||||
Also stop when the answer turns on why a *person* did something and the record does not
|
||||
say. Ask them. Reconstructing a colleague's reasoning from a diff is how a guess acquires
|
||||
a citation.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- `adr` — what you find here belongs in the Context section of the ADR you are about to
|
||||
write. If the thing was decided before, your ADR supersedes that one; say so.
|
||||
- `debug` — the same discipline aimed at a failure rather than a decision: evidence
|
||||
before hypothesis, and the removal commit is evidence.
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!/bin/sh
|
||||
# lineage.sh — decision archaeology for one term.
|
||||
#
|
||||
# Answers "why does X exist, was it tried before, and is this 'new' idea a
|
||||
# revival?"
|
||||
#
|
||||
# Its real value is that it makes you run `git log -S` at all — that is a nudge,
|
||||
# not a capability. -S finds commits where the term's occurrence COUNT changed,
|
||||
# so it surfaces a removal; --grep only finds people talking about one. On an
|
||||
# identifier name (`wire_claude_repo`) -S typically returns exactly two commits,
|
||||
# birth and death, which is the fastest path to the answer in this whole file.
|
||||
#
|
||||
# Note the two searches do not match the same way: --grep takes a regex, -S takes
|
||||
# a literal string. A term containing . [ * + behaves differently in each.
|
||||
#
|
||||
# Usage: lineage.sh <term> [repo-path]
|
||||
#
|
||||
# Read-only: nothing here writes, and it never touches the index or worktree.
|
||||
|
||||
set -u
|
||||
|
||||
[ $# -ge 1 ] || { echo "usage: lineage.sh <term> [repo-path]" >&2; exit 2; }
|
||||
TERM_=$1
|
||||
REPO=${2:-.}
|
||||
|
||||
git -C "$REPO" rev-parse --git-dir >/dev/null 2>&1 || {
|
||||
echo "lineage: $REPO is not a git repository" >&2; exit 2; }
|
||||
|
||||
# Say which repo, always. The default is the cwd, and in a worktree-heavy setup
|
||||
# that is routinely not the repo the caller means — a confident null against the
|
||||
# wrong tree is the worst thing this tool can produce.
|
||||
TOPLEVEL=$(git -C "$REPO" rev-parse --show-toplevel 2>/dev/null || printf '%s' "$REPO")
|
||||
printf 'searching: %s term: "%s"\n' "$TOPLEVEL" "$TERM_"
|
||||
|
||||
FMT='%h %ad %an %s'
|
||||
DATE='--date=short'
|
||||
found=0
|
||||
|
||||
section() { printf '\n== %s ==\n' "$1"; }
|
||||
|
||||
# 1. Commits whose MESSAGE mentions it — the stated reasoning.
|
||||
msgs=$(git -C "$REPO" log --all -i --grep="$TERM_" --format="$FMT" $DATE 2>/dev/null || true)
|
||||
if [ -n "$msgs" ]; then
|
||||
found=1
|
||||
section "Commits that talk about it (message)"
|
||||
printf '%s\n' "$msgs"
|
||||
fi
|
||||
|
||||
# 2. Commits where the term was ADDED or REMOVED — the actual history.
|
||||
# -S counts occurrences, so a deletion shows up here and nowhere else.
|
||||
picks=$(git -C "$REPO" log --all -S"$TERM_" --format="$FMT" $DATE 2>/dev/null || true)
|
||||
if [ -n "$picks" ]; then
|
||||
found=1
|
||||
section "Commits where it appeared or disappeared (-S)"
|
||||
printf '%s\n' "$picks"
|
||||
printf '\n Oldest is the introduction. Anything after it that removed the term is\n'
|
||||
printf ' the interesting one: read that commit before proposing this again.\n'
|
||||
fi
|
||||
|
||||
# 3. Files that once contained it and no longer exist.
|
||||
deleted=$(git -C "$REPO" log --all --diff-filter=D --name-only --format='%h' -S"$TERM_" 2>/dev/null \
|
||||
| grep -v '^[0-9a-f]\{7,\}$' | grep -v '^$' | sort -u || true)
|
||||
if [ -n "$deleted" ]; then
|
||||
found=1
|
||||
section "Files deleted that carried it"
|
||||
printf '%s\n' "$deleted"
|
||||
printf '\n Recover one with: git -C %s show <sha>^:<path>\n' "$REPO"
|
||||
fi
|
||||
|
||||
# 4. Decision records naming it.
|
||||
docs=$(git -C "$REPO" grep -l -i "$TERM_" -- 'docs/adr/*' 'docs/decisions/*' 'docs/*.md' 'ADR*' 2>/dev/null || true)
|
||||
if [ -n "$docs" ]; then
|
||||
found=1
|
||||
section "Decision records naming it"
|
||||
printf '%s\n' "$docs"
|
||||
fi
|
||||
|
||||
# This estate keeps most of its reasoning OUTSIDE the repo, so the two searches
|
||||
# this tool cannot run are usually the decisive ones. Say so every time rather
|
||||
# than letting their absence read as a null result.
|
||||
section "Not searched here — do these by hand"
|
||||
printf 'brain: brain_query "%s" — decisions and postmortems live there, not in docs/\n' "$TERM_"
|
||||
printf 'gitea: closed issues and their COMMENTS. The argument for a removal is\n'
|
||||
printf ' usually in a comment; the commit only records that it happened.\n'
|
||||
|
||||
if [ "$found" -eq 0 ]; then
|
||||
printf '\nno match for the exact string "%s" in %s.\n' "$TERM_" "$TOPLEVEL"
|
||||
printf 'This is NOT evidence the idea is new. It is one string against one repo.\n'
|
||||
printf 'Before concluding anything, try: the identifier or function name; a\n'
|
||||
printf 'one-word variant (spaces and punctuation break the match); the name it\n'
|
||||
printf 'would have had; and the brain and issue searches above.\n'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
printf '\n-- what this cannot tell you --------------------------------------------\n'
|
||||
printf 'Why it was removed, if it was. The commit subject is a summary; read the\n'
|
||||
printf 'body, the PR, and the issue it closed. A past failure under conditions that\n'
|
||||
printf 'no longer hold is not evidence against trying again — it is context for\n'
|
||||
printf 'trying again differently.\n'
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
name: own-the-task
|
||||
surfaces: [claude-code, library, chat]
|
||||
summary: "Delegation ownership — Intake → Brief → Plan → Execute"
|
||||
use_when: "A task is handed over open-ended; \"take this off my plate\"; before a plan exists"
|
||||
description: Take ownership of a delegated task like a hired employee — interview first, write a handover brief, propose a plan, then execute. Use whenever the user says "take this off my plate", "own this", "act as my AI employee", "interview me first", "ask me questions before you start", or delegates anything open-ended where the real goal, the why, and the definition of done are not yet on the table. Trigger even when "interview" is never said — any delegation where getting the intent wrong would waste the whole effort belongs here.
|
||||
---
|
||||
|
||||
# Own the task
|
||||
|
||||
The user is delegating, not dictating. Value comes from the questions that change the shape of the work, not from a fast answer to the surface request.
|
||||
|
||||
**Intake → Brief → Plan → Execute.** Don't skip ahead. A task looking obvious usually means the real goal hasn't surfaced yet.
|
||||
|
||||
## 1. Intake
|
||||
|
||||
Ask the 5 highest-signal questions — the ones whose answers would most change your approach. **One per turn, wait for the answer.** Skip anything you could infer or look up. Follow up on any gap, contradiction, or opportunity; follow-ups don't count against the five.
|
||||
|
||||
Cover:
|
||||
|
||||
1. **Real goal** — the outcome underneath the stated deliverable.
|
||||
2. **Why** it matters to them.
|
||||
3. **Attention budget** — what they want to be *asked* about vs *told* about afterwards, plus hard constraints (time, money, people, politics, tooling, taste). This work fails by pulling them back in, not by missing a spec.
|
||||
4. **Definition of done** — observable. Then always follow up: *what changes for you once that's true?* Cold, that question gets a shrug; after the observable answer, it surfaces criteria they can't state directly.
|
||||
5. **Failure modes** — what bad looks like, or what previous attempts got wrong. Success criteria are rehearsed; being burned isn't.
|
||||
|
||||
Weak → strong:
|
||||
- "What's your deadline?" → "If this were half-finished on the deadline, what's the half you'd want done?"
|
||||
- "How involved do you want to be?" → "What would you be annoyed to be asked about — and what would you be annoyed to find out afterwards?"
|
||||
- "Any constraints?" → "What's been tried here before, and what made it not stick?"
|
||||
|
||||
If they answer thinly or say "you decide", take the decision, state the assumption, move on.
|
||||
|
||||
## 2. Handover brief
|
||||
|
||||
Write it as if you had amnesia and were briefing your future self — a stranger should be able to pick the task up cold.
|
||||
|
||||
```
|
||||
**Task:** / **Real goal:** / **Why:**
|
||||
**Constraints:** [hard vs soft, marked]
|
||||
**Attention budget:** [what comes back to them, what doesn't]
|
||||
**Definition of done:** / **What a win feels like:**
|
||||
**Failure modes to avoid:**
|
||||
**Open assumptions:** [what you decided for them, so they can correct it]
|
||||
```
|
||||
|
||||
## 3. Plan
|
||||
|
||||
Short: numbered steps with what each produces, the first checkpoint, and what you'll decide yourself (drawn from the attention budget, not guessed). Then ask for a go-ahead — one question, not a menu.
|
||||
|
||||
## 4. Execute
|
||||
|
||||
Decide the small things. Surface only what changes the outcome. If reality contradicts the brief, re-propose early rather than quietly bending the work. Deliver against the definition of done and say plainly where you fell short.
|
||||
|
||||
## Skip this
|
||||
|
||||
For small, well-specified, or factual requests. If the task is nearly specified, ask one or two questions and say why you're going short.
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: planning
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Planning and task breakdown"
|
||||
use_when: "Sprint planning, task decomposition"
|
||||
description: Decompose work into small, verifiable, ordered tasks. Use when you have a spec or clear requirements and need to break work into implementable units.
|
||||
---
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: playwright
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Playwright E2E testing — setup, HTMX patterns, SSE streams, CI wiring"
|
||||
use_when: "Adding browser tests to any project with a web UI"
|
||||
description: Add and run Playwright E2E tests for any project with a web UI — covers setup, HTMX-specific patterns, SSE/streaming, Taskfile integration, and CI wiring.
|
||||
---
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: problem-analysis
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Deep problem understanding before coding"
|
||||
use_when: "Starting any non-trivial task"
|
||||
description: Deeply understand a problem before coding begins. Identify the real problem, stakeholders, constraints, and success criteria. Use before starting any non-trivial feature.
|
||||
---
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: refactoring
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Systematic refactoring methodology (Fowler)"
|
||||
use_when: "When improving existing code"
|
||||
description: Systematic refactoring methodology based on Martin Fowler's catalog. Apply during the REFACTOR phase of TDD, never while making code changes that modify behavior.
|
||||
---
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
---
|
||||
name: regulatory-risk-assessment
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Structured risk register for regulated-industry features"
|
||||
use_when: "Filing a CAD issue (needs Risk: level); features touching payments, auth, external APIs, user data"
|
||||
description: Produce a structured regulatory risk assessment / risk-register entry for regulated-industry features (banking, payments, PSD2/PSR, DORA, AML). Use when filing a CAD issue that needs a Risk:LOW/MEDIUM/HIGH level, or designing features touching payments, auth, data storage, or external APIs ("what are the risks?", "compliance gate", "risk register").
|
||||
---
|
||||
|
||||
# regulatory-risk-assessment
|
||||
|
||||
Produce a structured regulatory risk assessment for a feature, component,
|
||||
or integration — generating a risk register entry that satisfies the
|
||||
audit requirements of regulated-industry clients (banking, finance,
|
||||
insurance, PSD2/PSR, DORA, AML/KYC contexts).
|
||||
|
||||
**Use when:**
|
||||
- Filing a Gitea issue dispatched via CAD (needs Risk: LOW/MEDIUM/HIGH)
|
||||
- Designing a feature touching payments, auth, data storage, external APIs
|
||||
- Preparing a client deliverable in a regulated industry
|
||||
- "what are the risks?" / "compliance gate" / "risk register" in session
|
||||
|
||||
**Do not use for:** routine refactoring, docs-only changes, internal
|
||||
tooling with no external data or user impact.
|
||||
|
||||
## What this skill produces
|
||||
|
||||
A docs/risk-register.md section with this schema:
|
||||
|
||||
### R-[DOMAIN]-[NN] — [Short risk title]
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Risk | What could go wrong (concrete, specific) |
|
||||
| Regulatory reference | Which obligation/regulation, if any |
|
||||
| Likelihood | H / M / L |
|
||||
| Impact | H / M / L |
|
||||
| Overall | H / M / L (highest of likelihood x impact) |
|
||||
| Mitigation | What we are doing about it |
|
||||
| Validation | Test name or Gitea issue number |
|
||||
| Status | open / mitigated / accepted |
|
||||
|
||||
Risk ID namespace:
|
||||
R-AUTH-NN authentication and authorization
|
||||
R-DATA-NN data storage, retention, privacy
|
||||
R-API-NN external API integration
|
||||
R-PAY-NN payment and financial transactions
|
||||
R-INFRA-NN infrastructure and availability
|
||||
R-AGENT-NN agentic / AI execution
|
||||
R-COMP-NN compliance and regulatory obligation
|
||||
|
||||
## Mechanics
|
||||
|
||||
Step 1 — Scope the assessment
|
||||
1. What external systems does this touch?
|
||||
2. What user data does it read, write, or transmit?
|
||||
3. What happens on silent failure? Loud failure?
|
||||
4. What is the blast radius of a worst-case bug?
|
||||
5. Is a regulation implicated?
|
||||
|
||||
Step 2 — Enumerate risks (common examples)
|
||||
Auth/OAuth: token theft, refresh failure, insufficient scope
|
||||
Email/Gmail: misclassification archives HUMAN thread, PII in logs
|
||||
Payment/PAIN.001: wrong amount, duplicate submission, missing field
|
||||
Agentic: irreversible action without approval, prompt injection, spirals
|
||||
Infra: single point of failure, secret in logs
|
||||
|
||||
Step 3 — Declare overall risk level
|
||||
Highest individual risk = feature overall level (LOW/MEDIUM/HIGH).
|
||||
This is the **Risk:** declaration in the CAD agent-ready issue contract.
|
||||
|
||||
Step 4 — Write validations
|
||||
Every mitigation needs a validation:
|
||||
- Specific test name (TestXxx)
|
||||
- Gitea issue number
|
||||
- Manual verification step with acceptance criteria
|
||||
Not acceptable: "will test later", "review manually"
|
||||
|
||||
Step 5 — Update docs/risk-register.md
|
||||
Append entries. Create if absent:
|
||||
|
||||
# Risk Register
|
||||
All entries follow R-[DOMAIN]-[NN] schema.
|
||||
See skills/regulatory-risk-assessment/SKILL.md for conventions.
|
||||
Last updated: [date]
|
||||
|
||||
## Integration with assessor-loop
|
||||
|
||||
For complex regulated-industry features (PSD2/PSR, DORA, AML), route to
|
||||
mathias/assessor-loop for deep obligation decomposition first.
|
||||
Use this skill standalone for internal tooling or general engineering risk.
|
||||
|
||||
## Integration with CAD
|
||||
|
||||
Every CAD-dispatched issue must include:
|
||||
**Risk:** LOW | MEDIUM | HIGH
|
||||
|
||||
CAD pre-flight (agentsquad#29) rejects issues without it.
|
||||
If genuinely no risks: declare LOW and note why.
|
||||
|
||||
## Example entry
|
||||
|
||||
### R-DATA-01 — Email misclassification archives a HUMAN thread
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Risk | LLM labels a real person's email as NOISE, causing auto-archive |
|
||||
| Regulatory reference | None (internal) |
|
||||
| Likelihood | M |
|
||||
| Impact | H |
|
||||
| Overall | H |
|
||||
| Mitigation | Phase 1 read-only; HUMAN class never auto-archived in any phase |
|
||||
| Validation | TestClassifier_HumanThreadNeverArchived; 1-week Phase 1 review |
|
||||
| Status | open |
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
name: secret-hygiene
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Stop credentials rendering into the session transcript; safe rotation chain when one leaks"
|
||||
use_when: "Before any kubectl/SOPS/token command; after a confirmed leak"
|
||||
description: Prevent agent sessions from rendering credentials into the transcript, and recover safely when one leaks. Load BEFORE any command that touches credentials - kubectl exec/env/describe, kubectl get secret, whole-file SOPS decryption, token generation or rotation, envFrom inspection, or edits to encrypted config. Also load when a credential has already been exposed and a rotation chain is needed. Triggers - "rotate this token", "decrypt the config", "check the env var", "leaked credential", "did that print a secret", "why is this secret wrong".
|
||||
---
|
||||
|
||||
# Secret hygiene for agent sessions
|
||||
|
||||
Goal: stop the recurring leak pattern where a diagnostic command renders a
|
||||
SOPS-encrypted value or a Kubernetes Secret value into the session
|
||||
transcript, forcing a rotation.
|
||||
|
||||
**Confirmed past leaks** (see `mathias/infra#39` rotation umbrella):
|
||||
- `POSTGRES_PASSWORD` — `kubectl exec ... env` rendered envFrom value
|
||||
- `INFRA_MCP_TOKEN` — `sops -d ingress.enc.yaml` rendered the bearer in the configuration-snippet
|
||||
- `brain_app` postgres DSN — pre-fix ingestion pod log (hyperguild#20)
|
||||
|
||||
Three are pattern, not bug.
|
||||
|
||||
## Rules — never do these
|
||||
|
||||
| Forbidden | Why | Use instead |
|
||||
|---|---|---|
|
||||
| `kubectl exec <pod> -- env` (or `printenv`) | Renders every envFrom + valueFrom.secretKeyRef plaintext | `kubectl describe pod <pod>` — k8s redacts secretKeyRef in describe |
|
||||
| `sops -d <file>` to inspect | Whole-file decrypt dumps everything | `sops --extract '["key"]' <file>` for pinpoint reads |
|
||||
| `kubectl get secret ... -o jsonpath='{.data}'` (whole map) | Returns base64 of every key; trivial to b64-decode the lot | `... -o jsonpath='{.data.SPECIFIC_KEY}'` for the one key needed |
|
||||
| Echoing a generated token to verify length / content | Renders the new token into transcript, defeating the rotation | Verify functionally: `curl ... -H "Authorization: Bearer $(cat /tmp/tokfile)"` — never echo `$NEW_TOK` |
|
||||
| Storing a token in a shell variable then running `echo` / `set` / `env` | Same as above | Pipe through file (mode 600) or stdin to the next consumer |
|
||||
|
||||
## Rules — do these instead
|
||||
|
||||
- **Verify by side-effect, not by value.** If a token rotation should make
|
||||
the old token return 401 and the new one return 200, test those two
|
||||
HTTP responses. Never check `$OLD == $LEAKED` by printing it.
|
||||
- **Pinpoint SOPS reads.** When you need ONE key from a SOPS file, always
|
||||
`sops --extract '["..."]'`. The shape of the key path is safe to log;
|
||||
the value isn't.
|
||||
- **Stash tokens in `/dev/shm/<unique>` mode 600** and pass via filename,
|
||||
not env. `shred -u` after use. Avoid `/tmp` if the system has `/dev/shm`.
|
||||
- **If you must dump a secret to confirm wiring**, immediately rotate it
|
||||
in the same commit train. Treat the dump as "this is now compromised".
|
||||
|
||||
## Rotation chain pattern when a token is already exposed
|
||||
|
||||
If a token was leaked in a prior step of the same session, chain two
|
||||
rotations:
|
||||
|
||||
1. **T1**: replace the leaked value with a new one. The verification step
|
||||
may also leak T1 (acceptable risk).
|
||||
2. **T2**: replace T1 with a fresh value. Run this without any decrypt
|
||||
step that emits to stdout. The new value lives only in the encrypted
|
||||
file + the consumer's secret store (`~/.llmkeys`, the k8s Secret).
|
||||
|
||||
Example T2 path (Python, never decrypts to stdout):
|
||||
|
||||
```python
|
||||
new_t2 = subprocess.check_output(["openssl","rand","-hex","32"]).decode().strip()
|
||||
plaintext = subprocess.check_output(["sops","-d", path]).decode() # in-memory only
|
||||
patched = re.sub(r'Bearer [a-f0-9]+(?=")', f"Bearer {new_t2}", plaintext)
|
||||
# write patched via /dev/shm tmp + sops -e → write back
|
||||
# DO NOT print(patched), DO NOT print(new_t2)
|
||||
```
|
||||
|
||||
After T2 lands via GitOps + Flux, update consumers from the file stash
|
||||
without echoing.
|
||||
|
||||
## Detection ideas (not blocking — telemetry)
|
||||
|
||||
- Add a `bash` pre-hook in Claude harness that refuses obvious patterns
|
||||
(`kubectl exec * env*`, `sops -d *.enc.yaml`). Filed as a follow-up.
|
||||
- Run a periodic grep over `~/.claude/projects/*/sessions/*.jsonl` for
|
||||
high-entropy strings matching `[a-f0-9]{32,}` to catch new leak surface.
|
||||
|
||||
## Reference
|
||||
|
||||
- `gitea.d-ma.be/mathias/infra#39` — umbrella credential rotation issue with confirmed-leak roster.
|
||||
- `gitea.d-ma.be/mathias/infra#44` — POSTGRES_PASSWORD rotation procedure (template for future incidents).
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: session-retrospective
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Surface non-obvious learnings from a session log"
|
||||
use_when: "After a coding session ends, before context is lost"
|
||||
description: Review a completed coding session (from brain/sessions/*.jsonl) and surface non-obvious learnings worth preserving. Use after a session ends, before context is lost.
|
||||
---
|
||||
|
||||
@@ -113,7 +116,7 @@ Pass-rate is computed downstream by the `/pass-rate` HTTP endpoint, which
|
||||
treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
|
||||
**At end of each phase:**
|
||||
- `session_log` with `{skill: "session-retrospective", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", duration_ms: <wall-clock>, project_root: "<absolute path>"}`
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "session-retrospective", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", project_root: "<absolute path>"}`
|
||||
|
||||
**Phases for this skill:** surfaced
|
||||
|
||||
@@ -122,11 +125,7 @@ treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
- `fail` — the phase's intended outcome was NOT reached (retrospective could not produce coherent candidates).
|
||||
- `skip` — phase was skipped intentionally (no novel learnings worth surfacing).
|
||||
|
||||
**Why this matters:** the routing pod (Plan 6) reads pass-rate to decide whether to route a future call to a local model. If your skill never logs, the routing pod sees no data.
|
||||
|
||||
## Mode 2 Routing Note
|
||||
|
||||
Reading long session logs and pulling themes is high-volume, mechanical pattern-recognition work — a strong Mode 2 routing candidate. Until Plan 6 ships the routing pod, treat as Mode 1 only.
|
||||
**Why this matters:** pass-rate is what a future routing decision would be based on — whether a given call can be served by a local model instead of a cloud one. A skill that never logs contributes no evidence either way.
|
||||
|
||||
## Cross-References
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: solid
|
||||
surfaces: [claude-code, library]
|
||||
summary: "SOLID principles with Go examples"
|
||||
use_when: "Design review, architecture decisions"
|
||||
description: Apply SOLID design principles in Go. Use during architecture decisions, design reviews, and when adding new abstractions.
|
||||
---
|
||||
|
||||
@@ -255,5 +258,15 @@ Domain types know nothing about HTTP, SQL, or external APIs.
|
||||
|
||||
- `references/solid-principles.md` — canonical SOLID reference with TypeScript examples
|
||||
- `references/go-adaptation.md` — this workspace's Go-specific rewrite of each principle
|
||||
- `references/python-adaptation.md` — the Python rewrite: Protocol over ABC, and what does not carry over from Go
|
||||
- Load `clean-code` skill for naming and structure
|
||||
- Load `code-review` skill for detecting violations during review
|
||||
|
||||
## Escalation
|
||||
|
||||
Advisory. Names principle violations and suggests structure; writes no code.
|
||||
|
||||
Stop and hand back when: applying a principle would require a change larger than the one
|
||||
under discussion. "This wants dependency inversion" on a two-line fix is a design
|
||||
conversation, not a review comment, and forcing it through as one is how a small change
|
||||
acquires an architecture.
|
||||
@@ -0,0 +1,104 @@
|
||||
# SOLID Principles: Python Adaptation
|
||||
|
||||
`references/go-adaptation.md` rewrites each principle for Go. This file does the same
|
||||
for Python, and marks the places where the Go rewrite's advice does *not* carry over.
|
||||
|
||||
The canonical Python stack lives in `~/dev/.context/AGENT.md`; it is not restated here.
|
||||
|
||||
## The one idea that changes everything: `Protocol`
|
||||
|
||||
Go's interfaces are structural — a type satisfies one by having the methods, with no
|
||||
declaration. Python has the same thing since 3.8, and it is the right default:
|
||||
|
||||
```python
|
||||
from typing import Protocol
|
||||
|
||||
class InvoiceStore(Protocol):
|
||||
def get(self, invoice_id: InvoiceId) -> Invoice: ...
|
||||
def save(self, invoice: Invoice) -> None: ...
|
||||
```
|
||||
|
||||
- **Define the Protocol where it is *consumed*, not where it is implemented.** This is
|
||||
Go's "accept interfaces, return structs" and it is what makes DIP real: the high-level
|
||||
module owns the abstraction, and the adapter depends on it rather than the reverse.
|
||||
- **Prefer `Protocol` to `ABC`.** An ABC forces implementers to inherit, which couples
|
||||
them to your package and makes a third-party class impossible to adapt without a
|
||||
wrapper. Use an ABC only when you genuinely need shared implementation, not just a
|
||||
contract.
|
||||
- Add `@runtime_checkable` only if you actually call `isinstance` — and if you are
|
||||
calling `isinstance` against a Protocol, check whether the real problem is a missing
|
||||
polymorphic method (an LSP smell).
|
||||
|
||||
## S — Single Responsibility
|
||||
|
||||
Same as Go: the unit is the module, not just the class. `utils.py` is the Python god
|
||||
package — it cannot have one reason to change because it has no subject.
|
||||
|
||||
Python-specific tell: a class whose `__init__` stores arguments and whose only other
|
||||
method is `run()` or `execute()`. That is a function with ceremony. Write the function.
|
||||
|
||||
## O — Open/Closed
|
||||
|
||||
Extension in Python usually means **passing behaviour in**, not subclassing:
|
||||
|
||||
```python
|
||||
# Closed for modification: adding a rule does not touch this function
|
||||
def apply_rules(invoice: Invoice, rules: Sequence[Rule]) -> Invoice: ...
|
||||
```
|
||||
|
||||
`functools.singledispatch` is the idiomatic open extension point when dispatch is on
|
||||
type and the set of types grows outside your module. Beware the alternative that looks
|
||||
Pythonic and is not: monkey-patching is modification pretending to be extension, and it
|
||||
is invisible at the call site.
|
||||
|
||||
## L — Liskov
|
||||
|
||||
The Python-specific violation is **signature widening/narrowing that the type checker
|
||||
would catch if you let it**. Under `mypy --strict`, an override that narrows a parameter
|
||||
type or widens a return type is an error — which means most LSP violations in Python are
|
||||
type errors you chose not to see. This is the strongest argument for `--strict` in a
|
||||
design document rather than a style one.
|
||||
|
||||
Raising a *new* exception type in an override is the violation `mypy` will not catch:
|
||||
callers wrote `except StoreError`, and your subclass raises `TimeoutError`. Exceptions
|
||||
are part of the contract; Python just will not check them for you.
|
||||
|
||||
## I — Interface Segregation
|
||||
|
||||
Protocols make this cheap: define the narrow one you need at the call site.
|
||||
|
||||
```python
|
||||
class InvoiceReader(Protocol):
|
||||
def get(self, invoice_id: InvoiceId) -> Invoice: ...
|
||||
```
|
||||
|
||||
A function that only reads should accept `InvoiceReader`, not the full `InvoiceStore`.
|
||||
The test double then implements one method instead of eight, which is the practical
|
||||
payoff and the reason this principle survives contact with real code.
|
||||
|
||||
## D — Dependency Inversion
|
||||
|
||||
Constructor injection, exactly as in Go. Two Python-specific hazards:
|
||||
|
||||
- **Import-time side effects are hidden dependencies.** A module that opens a database
|
||||
connection or reads an env var at import has a dependency nothing can inject and no
|
||||
test can replace. Configuration belongs in `pydantic-settings` objects passed in.
|
||||
- **Default arguments are compile-time bindings.** `def send(client: Client = Client())`
|
||||
constructs the default once, at definition, and welds it to every caller. Default to
|
||||
`None` and construct inside, or require it.
|
||||
|
||||
## What does not carry over from the Go rewrite
|
||||
|
||||
- **"Return structs, accept interfaces"** — the returning half is about Go's zero values
|
||||
and nil interfaces. In Python, returning a Protocol type is fine and often better.
|
||||
- **Small interfaces because of embedding** — Python has no embedding; composition is
|
||||
explicit delegation, which is more verbose but reads honestly.
|
||||
- **Package-level responsibility as the unit of deployment** — Python packaging is much
|
||||
looser. The module boundary is still the right unit for *reasoning*, but do not expect
|
||||
it to be enforced.
|
||||
|
||||
## See also
|
||||
|
||||
- `references/solid-principles.md` — the canonical, language-neutral reference
|
||||
- `references/go-adaptation.md` — the Go rewrite; contrast is instructive
|
||||
- `clean-code/references/python-adaptation.md` — style-level Python conventions
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: spec-driven-dev
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Spec-driven development for PMs"
|
||||
use_when: "Writing specs and requirements"
|
||||
description: Write a structured specification before writing any code. Use when starting a new project, feature, or significant change. Adapted for a PM-first workflow where why comes before how.
|
||||
---
|
||||
|
||||
@@ -197,6 +200,56 @@ Dev: [full command]
|
||||
[Anything unresolved that needs input before implementation begins]
|
||||
```
|
||||
|
||||
## EARS-lite acceptance criteria
|
||||
|
||||
Measurable criteria answer "is it done?". They do not always answer "what should it do
|
||||
when X happens?" — and behavioural requirements written as prose are where ambiguity
|
||||
survives review. For any criterion that is conditional or event-driven, use EARS-lite
|
||||
instead of prose:
|
||||
|
||||
```
|
||||
WHEN <trigger> THE SYSTEM SHALL <observable response>
|
||||
WHILE <state> THE SYSTEM SHALL <observable response>
|
||||
IF <unwanted condition> THEN THE SYSTEM SHALL <observable response>
|
||||
```
|
||||
|
||||
There is a fourth, unconditional form. Use it for invariants — the properties that must
|
||||
hold with no trigger at all, which are usually the ones that matter most:
|
||||
|
||||
```
|
||||
THE SYSTEM SHALL <observable response>
|
||||
```
|
||||
|
||||
Worked, deliberately from a domain unlike whatever you are specifying:
|
||||
|
||||
```
|
||||
THE SYSTEM SHALL reject a firmware image whose signature does not verify
|
||||
WHEN a sensor reports a temperature above the shutdown limit
|
||||
THE SYSTEM SHALL open the contactor within 200ms
|
||||
WHILE the contactor is open
|
||||
THE SYSTEM SHALL refuse every start command
|
||||
IF a sensor reading is missing or stale by more than one interval
|
||||
THEN THE SYSTEM SHALL treat it as above the limit
|
||||
```
|
||||
|
||||
The example is off-domain on purpose. An on-domain example gets copied: a spec written
|
||||
against an invoice-flavoured example inherited a requirement about extraction confidence
|
||||
that its feature request never mentioned, and the author only noticed on review. Read
|
||||
the shapes, not the content.
|
||||
|
||||
Each conditional line names a trigger and one observable response, which usually maps
|
||||
onto a single test. The `WHILE` and unconditional forms are universally quantified —
|
||||
"every start command", "a firmware image" — so they map onto a property or a set of
|
||||
cases, not one assertion. That is still worth writing: it closes the requirements half
|
||||
of the audit trail, which is otherwise issue-body prose.
|
||||
|
||||
**This is an option, not a replacement.** Threshold criteria ("p99 < 200ms under 100
|
||||
RPS") stay as they are — EARS phrasing adds nothing to a number. Use it for conditional
|
||||
behaviour, error handling, and state-dependent rules.
|
||||
|
||||
For the executor-facing handoff, `feature-spec` also carries a **Context snapshot**
|
||||
section — inline the architecture facts the implementer cannot look up.
|
||||
|
||||
## Reframing Vague Requirements
|
||||
|
||||
When you receive a vague requirement, translate it into specific success criteria before writing any spec content:
|
||||
@@ -279,7 +332,7 @@ Pass-rate is computed downstream by the `/pass-rate` HTTP endpoint, which
|
||||
treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
|
||||
**At end of each phase:**
|
||||
- `session_log` with `{skill: "spec-driven-dev", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", duration_ms: <wall-clock>, project_root: "<absolute path>"}`
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "spec-driven-dev", phase: "<phase-name>", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", project_root: "<absolute path>"}`
|
||||
|
||||
**Phases for this skill:** specify, plan, tasks, implement
|
||||
|
||||
@@ -288,7 +341,7 @@ treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
- `fail` — the phase's intended outcome was NOT reached (gate blocked, rework required).
|
||||
- `skip` — phase was skipped intentionally.
|
||||
|
||||
**Why this matters:** the routing pod (Plan 6) reads pass-rate to decide whether to route a future call to a local model. If your skill never logs, the routing pod sees no data.
|
||||
**Why this matters:** pass-rate is what a future routing decision would be based on — whether a given call can be served by a local model instead of a cloud one. A skill that never logs contributes no evidence either way.
|
||||
|
||||
## Cross-References
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
name: stage-gate-review
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Stage-gate product governance (go/no-go council)"
|
||||
use_when: "Preparing a Product Council ask; building a go/no-go checklist; gate review"
|
||||
description: Run or prepare a stage-gate product governance review — the go/no-go checkpoint where a council approves an initiative to advance through fixed innovation stages (Frame → Concept → Prototype → Validate → Scale), each gate guarded by a per-discipline readiness checklist. Use when preparing a Product Council / steering-group ask, building a go/no-go checklist, designing an innovation governance process, or auditing whether an initiative is genuinely ready to advance vs faking the gate. Trigger phrases include "stage gate", "product council", "go/no-go", "advance to the next stage", "is this ready to progress", "gate review", "phase gate", "innovation governance".
|
||||
---
|
||||
|
||||
# Stage-Gate Review
|
||||
|
||||
A governance pattern for moving product/innovation initiatives through fixed stages
|
||||
under explicit go/no-go control. A standing council (or steering group) approves each
|
||||
advance; every gate is guarded by a **per-discipline readiness checklist**. The point
|
||||
is not bureaucracy — it is to kill weak bets early and fund strong ones with conviction.
|
||||
|
||||
This skill is the **transferable pattern**, stripped of any client instance. When a real
|
||||
engagement uses it, the client's council names, internal tooling, stage labels, and named
|
||||
contacts stay inside the client boundary (see *Client instances* below) — never bake them
|
||||
into this skill.
|
||||
|
||||
---
|
||||
|
||||
## The gate ladder
|
||||
|
||||
Five stages, escalating commitment. Each arrow is a council ask.
|
||||
|
||||
| Stage | Question it answers | Funding posture |
|
||||
|-------|---------------------|-----------------|
|
||||
| **Frame** | Is this opportunity worth exploring? | Cheap time only |
|
||||
| **Concept** | Is there a solution worth prototyping? | Small dedicated resource |
|
||||
| **Prototype** | Does the solution work and is the business case real? | Build budget |
|
||||
| **Validate** (market test) | Will a real customer pay / adopt? | Pilot budget + infra |
|
||||
| **Scale** (commercialize) | Should we invest to grow this? | Full commercial investment |
|
||||
|
||||
Key rule: **the earliest gate (Frame → Concept) is usually feedback-only**, not approval.
|
||||
You bring it to the council to sharpen thinking, not to pass judgment — killing ideas at
|
||||
Frame teaches teams to stop framing. Approval pressure starts at Concept.
|
||||
|
||||
The bar rises each gate: hypothesis → tested hypothesis → validated evidence + business
|
||||
case → signed pilot commitment → full commercial commitment.
|
||||
|
||||
---
|
||||
|
||||
## The discipline checklist
|
||||
|
||||
Every gate is a matrix: **the same disciplines, a higher bar each stage.** A gate ask is
|
||||
"ready" only when every applicable discipline clears its bar for that stage. Adapt the
|
||||
discipline set to the domain; this is the default spine.
|
||||
|
||||
| Discipline | What it guards | Rises from Frame → Scale |
|
||||
|------------|----------------|---------------------------|
|
||||
| **Ownership** | A named, committed product owner exists | identified → secured → full commitment to commercialize |
|
||||
| **Strategy fit** | Aligns with org strategy & objectives | alignment asserted → tie to portfolio confirmed |
|
||||
| **Economics** | Revenue + fully-loaded cost through the horizon | rough estimate → validated business case, approved |
|
||||
| **Customer/market evidence** | Real demand, tested with real people | hypotheses commissioned → tested → signed pilot partner |
|
||||
| **Experience / design** | Desirability and usability validated | design lead secured → evaluative testing + quality score |
|
||||
| **Technical feasibility** | Build assumptions reviewed by engineering | assumptions noted → reviewed → infra cost approved |
|
||||
| **Legal / risk / compliance** | Regulatory and contractual exposure surfaced | initial review → SME overviews → docs initiated |
|
||||
| **Go-to-market / region** | Launch market and support model identified | market aware → aligned → support & business model agreed |
|
||||
| **Timeline** | A credible plan to complete the next stage | — |
|
||||
| **System of record** | The initiative is tracked in the canonical tool | — |
|
||||
|
||||
A discipline that clearly doesn't apply gets **explicitly waived** ("no regulatory surface —
|
||||
legal waived"), never silently dropped. Silent omission is the most common way a gate rots.
|
||||
|
||||
---
|
||||
|
||||
## Running a gate review
|
||||
|
||||
**Preparing an ask (you are the team):**
|
||||
1. Identify the target gate and pull its column from the matrix.
|
||||
2. For each discipline, gather the evidence that clears *this stage's* bar — evidence, not
|
||||
intent. "We will test" does not clear a "tested" bar.
|
||||
3. Mark every discipline: cleared / waived (with reason) / gap.
|
||||
4. If any gap is on a discipline that gates the whole bet, **do not bring the ask** — close
|
||||
the gap or bring a feedback-only ask instead.
|
||||
5. Load `grill-me` (Full Grill) on the ask before bringing it. A council's hard questions are
|
||||
cheaper to answer in private first, and a gap found by grilling is a gap you close rather
|
||||
than one the gate reports.
|
||||
|
||||
**Chairing a review (you are the council):**
|
||||
1. Ask for the evidence behind each "cleared", not the claim. Claims are theatre.
|
||||
2. Probe the one discipline most likely to be faked for this stage (see anti-patterns).
|
||||
3. Decide: advance / hold (named gaps, re-ask) / kill. A council that never kills is a
|
||||
rubber stamp and the gate is worthless.
|
||||
|
||||
---
|
||||
|
||||
## Anti-patterns (gate theatre)
|
||||
|
||||
- **Checklist completion ≠ readiness.** Every box ticked, zero evidence. Demand artifacts.
|
||||
- **The pre-approved gate.** Decision made in the hallway; council ratifies. The gate adds
|
||||
cost and zero filtering.
|
||||
- **Evidence inflation.** "Validated" demand that is one friendly customer's enthusiasm.
|
||||
- **Skipping the kill.** Weak bets get "hold and re-ask" forever instead of a clean death.
|
||||
- **Frame-stage judgment.** Approving/rejecting at Frame teaches teams to stop exploring.
|
||||
- **Bar that never rises.** Same evidence accepted at Prototype as at Frame — the ladder
|
||||
collapses into one gate.
|
||||
|
||||
---
|
||||
|
||||
## Operator judgment (hard-won)
|
||||
|
||||
The matrix above is generic best practice. This section is the part that comes from running
|
||||
real reviews — apply it over the spine.
|
||||
|
||||
### Which gates to collapse, and when
|
||||
- **Low uncertainty + high strategic fit** (you already know the customer wants it): collapse
|
||||
**Prototype + Validate** — build the real thing *as* the pilot. The separate prototype gate
|
||||
buys nothing when desirability isn't the risk.
|
||||
- **Moonshot / high uncertainty**: never skip **Validate** — that's the whole bet. You can
|
||||
skip the formal **Concept** gate (run it feedback-only) but you cannot skip proving demand.
|
||||
|
||||
### Where the gate gets faked — tells by stage
|
||||
- **Concept:** "customer research" that's really 3 friendly stakeholder chats with no
|
||||
disconfirming evidence sought. Worse and more common: a Concept backed only by **selective
|
||||
external research carried over from Frame** — the team cherry-picks the framing-stage
|
||||
evidence that flatters the idea and runs no fresh test. Reused evidence is not validation.
|
||||
- **Validate:** a "signed" pilot that is actually a warm LOI — no money committed, no go-live
|
||||
date. Intent dressed as commitment.
|
||||
|
||||
### Minimum real evidence — calibrate to what the stage *can* know
|
||||
Don't demand certainty a stage can't yield. The honest question is "how much **can** we know
|
||||
at this point?" — and against that bar, **any genuine external signal beats internal
|
||||
conviction**. Often the highest-value move at an early gate is simply getting *the first real
|
||||
evidence at all*, where before there was only opinion. So:
|
||||
- Reject "cleared" that rests purely on internal belief or reused framing evidence.
|
||||
- Accept directional external evidence early; raise the bar to **committed** evidence (paid
|
||||
pilot, money down, a date) by Validate.
|
||||
- **Economics:** distrust a polished Year-3 revenue model. Trust fully-loaded cost plus one
|
||||
defensible near-term number over a confident long-horizon fiction.
|
||||
|
||||
### The two killers (what actually defeats a gate)
|
||||
- **Political pre-commitment.** Some bets management simply *wants*, regardless of evidence.
|
||||
A gate cannot kill what leadership has already decided. Name it when you see it — the gate
|
||||
is theatre on that bet, and pretending otherwise corrodes every other gate.
|
||||
- **Sunk-cost attachment.** You advance the wrong concept, then get too vested to kill it.
|
||||
The antidote is a **scientific mindset with no emotional attachment to the solution**. The
|
||||
disease is **solutions looking for problems to solve** — fall in love with the problem, stay
|
||||
ruthless about the solution. A gate's deepest job is to enforce exactly this detachment.
|
||||
|
||||
> Validated under fire — these belong in the brain as a standalone principle too, so they
|
||||
> outlive this one skill. See [[solution-looking-for-problem]], [[stage-gate-sunk-cost]].
|
||||
|
||||
---
|
||||
|
||||
## Client instances
|
||||
|
||||
When this pattern is instantiated for a named client, the instance is **confidential and
|
||||
stays in the client boundary**:
|
||||
- Council/forum names, internal stage labels, internal tooling, named contacts, strategy
|
||||
specifics, deal terms → client dir/org only, local models only, never the public brain.
|
||||
- This skill carries the **pattern**; the client carries the **wrapper**. Never merge them.
|
||||
|
||||
## Escalation
|
||||
|
||||
Advisory. Prepares or chairs a gate; the council decides, not this skill.
|
||||
|
||||
Stop and hand back when: a discipline's evidence is missing rather than weak. A gap on a
|
||||
gating discipline means do not bring the ask — bring a feedback-only ask instead. Marking
|
||||
it "cleared with a note" is precisely the gate theatre the anti-patterns section is
|
||||
about.
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
name: brainstorming
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Structured divergent brainstorming"
|
||||
use_when: "Generating or expanding a set of ideas"
|
||||
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.
|
||||
|
||||
<HARD-GATE>
|
||||
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.
|
||||
</HARD-GATE>
|
||||
|
||||
## 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-<topic>-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-<topic>-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 `<path>`. 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`
|
||||
@@ -0,0 +1,214 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Superpowers Brainstorming</title>
|
||||
<style>
|
||||
/*
|
||||
* BRAINSTORM COMPANION FRAME TEMPLATE
|
||||
*
|
||||
* This template provides a consistent frame with:
|
||||
* - OS-aware light/dark theming
|
||||
* - Fixed header and selection indicator bar
|
||||
* - Scrollable main content area
|
||||
* - CSS helpers for common UI patterns
|
||||
*
|
||||
* Content is injected via placeholder comment in #claude-content.
|
||||
*/
|
||||
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
html, body { height: 100%; overflow: hidden; }
|
||||
|
||||
/* ===== THEME VARIABLES ===== */
|
||||
:root {
|
||||
--bg-primary: #f5f5f7;
|
||||
--bg-secondary: #ffffff;
|
||||
--bg-tertiary: #e5e5e7;
|
||||
--border: #d1d1d6;
|
||||
--text-primary: #1d1d1f;
|
||||
--text-secondary: #86868b;
|
||||
--text-tertiary: #aeaeb2;
|
||||
--accent: #0071e3;
|
||||
--accent-hover: #0077ed;
|
||||
--success: #34c759;
|
||||
--warning: #ff9f0a;
|
||||
--error: #ff3b30;
|
||||
--selected-bg: #e8f4fd;
|
||||
--selected-border: #0071e3;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg-primary: #1d1d1f;
|
||||
--bg-secondary: #2d2d2f;
|
||||
--bg-tertiary: #3d3d3f;
|
||||
--border: #424245;
|
||||
--text-primary: #f5f5f7;
|
||||
--text-secondary: #86868b;
|
||||
--text-tertiary: #636366;
|
||||
--accent: #0a84ff;
|
||||
--accent-hover: #409cff;
|
||||
--selected-bg: rgba(10, 132, 255, 0.15);
|
||||
--selected-border: #0a84ff;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* ===== FRAME STRUCTURE ===== */
|
||||
.header {
|
||||
background: var(--bg-secondary);
|
||||
padding: 0.5rem 1.5rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.header h1 { font-size: 0.85rem; font-weight: 500; color: var(--text-secondary); }
|
||||
.header .status { font-size: 0.7rem; color: var(--success); display: flex; align-items: center; gap: 0.4rem; }
|
||||
.header .status::before { content: ''; width: 6px; height: 6px; background: var(--success); border-radius: 50%; }
|
||||
|
||||
.main { flex: 1; overflow-y: auto; }
|
||||
#claude-content { padding: 2rem; min-height: 100%; }
|
||||
|
||||
.indicator-bar {
|
||||
background: var(--bg-secondary);
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 0.5rem 1.5rem;
|
||||
flex-shrink: 0;
|
||||
text-align: center;
|
||||
}
|
||||
.indicator-bar span {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.indicator-bar .selected-text {
|
||||
color: var(--accent);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* ===== TYPOGRAPHY ===== */
|
||||
h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
|
||||
h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
|
||||
.subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
|
||||
.section { margin-bottom: 2rem; }
|
||||
.label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
|
||||
|
||||
/* ===== OPTIONS (for A/B/C choices) ===== */
|
||||
.options { display: flex; flex-direction: column; gap: 0.75rem; }
|
||||
.option {
|
||||
background: var(--bg-secondary);
|
||||
border: 2px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 1rem 1.25rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
}
|
||||
.option:hover { border-color: var(--accent); }
|
||||
.option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
|
||||
.option .letter {
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-secondary);
|
||||
width: 1.75rem; height: 1.75rem;
|
||||
border-radius: 6px;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
|
||||
}
|
||||
.option.selected .letter { background: var(--accent); color: white; }
|
||||
.option .content { flex: 1; }
|
||||
.option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
|
||||
.option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }
|
||||
|
||||
/* ===== CARDS (for showing designs/mockups) ===== */
|
||||
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
|
||||
.card {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
.card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
||||
.card.selected { border-color: var(--selected-border); border-width: 2px; }
|
||||
.card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
|
||||
.card-body { padding: 1rem; }
|
||||
.card-body h3 { margin-bottom: 0.25rem; }
|
||||
.card-body p { color: var(--text-secondary); font-size: 0.85rem; }
|
||||
|
||||
/* ===== MOCKUP CONTAINER ===== */
|
||||
.mockup {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.mockup-header {
|
||||
background: var(--bg-tertiary);
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.mockup-body { padding: 1.5rem; }
|
||||
|
||||
/* ===== SPLIT VIEW (side-by-side comparison) ===== */
|
||||
.split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
|
||||
@media (max-width: 700px) { .split { grid-template-columns: 1fr; } }
|
||||
|
||||
/* ===== PROS/CONS ===== */
|
||||
.pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
|
||||
.pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
|
||||
.pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
|
||||
.cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
|
||||
.pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
|
||||
.pros li, .cons li { margin-bottom: 0.25rem; }
|
||||
|
||||
/* ===== PLACEHOLDER (for mockup areas) ===== */
|
||||
.placeholder {
|
||||
background: var(--bg-tertiary);
|
||||
border: 2px dashed var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
/* ===== INLINE MOCKUP ELEMENTS ===== */
|
||||
.mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
|
||||
.mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
|
||||
.mock-content { padding: 1.5rem; flex: 1; }
|
||||
.mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
|
||||
.mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<h1><a href="https://github.com/obra/superpowers" style="color: inherit; text-decoration: none;">Superpowers Brainstorming</a></h1>
|
||||
<div class="status">Connected</div>
|
||||
</div>
|
||||
|
||||
<div class="main">
|
||||
<div id="claude-content">
|
||||
<!-- CONTENT -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="indicator-bar">
|
||||
<span id="indicator-text">Click an option above, then return to the terminal</span>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -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 = '<span class="selected-text">' + label + ' selected</span> — return to terminal to continue';
|
||||
} else {
|
||||
indicator.innerHTML = '<span class="selected-text">' + selected.length + ' selected</span> — 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();
|
||||
})();
|
||||
@@ -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 = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head><meta charset="utf-8"><title>Brainstorm Companion</title>
|
||||
<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
|
||||
h1 { color: #333; } p { color: #666; }</style>
|
||||
</head>
|
||||
<body><h1>Brainstorm Companion</h1>
|
||||
<p>Waiting for the agent to push a screen...</p></body></html>`;
|
||||
|
||||
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 = '<script>\n' + helperScript + '\n</script>';
|
||||
|
||||
// ========== Helper Functions ==========
|
||||
|
||||
function isFullDocument(html) {
|
||||
const trimmed = html.trimStart().toLowerCase();
|
||||
return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
|
||||
}
|
||||
|
||||
function wrapInFrame(content) {
|
||||
return frameTemplate.replace('<!-- CONTENT -->', 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('</body>')) {
|
||||
html = html.replace('</body>', helperInjection + '\n</body>');
|
||||
} 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 };
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start the brainstorm server and output connection info
|
||||
# Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-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 <path> Store session files under <path>/.superpowers/brainstorm/
|
||||
# instead of /tmp. Files persist after server stops.
|
||||
# --host <bind-host> Host/interface to bind (default: 127.0.0.1).
|
||||
# Use 0.0.0.0 in remote/containerized environments.
|
||||
# --url-host <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
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env bash
|
||||
# Stop the brainstorm server and clean up
|
||||
# Usage: stop-server.sh <session_dir>
|
||||
#
|
||||
# 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 <session_dir>"}'
|
||||
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
|
||||
@@ -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/
|
||||
|
||||
```
|
||||
Agent tool (`subagent_type: "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
|
||||
@@ -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 `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, selection indicator, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.
|
||||
|
||||
## Starting a Session
|
||||
|
||||
```bash
|
||||
# Start server with persistence (mockups saved to project)
|
||||
scripts/start-server.sh --project-dir /path/to/project
|
||||
|
||||
# Returns: {"type":"server-started","port":52341,"url":"http://localhost:52341",
|
||||
# "screen_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/content",
|
||||
# "state_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/state"}
|
||||
```
|
||||
|
||||
Save `screen_dir` and `state_dir` from the response. Tell user to open the URL.
|
||||
|
||||
**Finding connection info:** The server writes its startup JSON to `$STATE_DIR/server-info`. If you launched the server in the background and didn't capture stdout, read that file to get the URL and port. When using `--project-dir`, check `<project>/.superpowers/brainstorm/` for the session directory.
|
||||
|
||||
**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
|
||||
<!-- filename: waiting.html (or waiting-2.html, etc.) -->
|
||||
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
|
||||
<p class="subtitle">Continuing in terminal...</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
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
|
||||
<h2>Which layout works better?</h2>
|
||||
<p class="subtitle">Consider readability and visual hierarchy</p>
|
||||
|
||||
<div class="options">
|
||||
<div class="option" data-choice="a" onclick="toggleSelect(this)">
|
||||
<div class="letter">A</div>
|
||||
<div class="content">
|
||||
<h3>Single Column</h3>
|
||||
<p>Clean, focused reading experience</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="option" data-choice="b" onclick="toggleSelect(this)">
|
||||
<div class="letter">B</div>
|
||||
<div class="content">
|
||||
<h3>Two Column</h3>
|
||||
<p>Sidebar navigation with main content</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
That's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.
|
||||
|
||||
## CSS Classes Available
|
||||
|
||||
The frame template provides these CSS classes for your content:
|
||||
|
||||
### Options (A/B/C choices)
|
||||
|
||||
```html
|
||||
<div class="options">
|
||||
<div class="option" data-choice="a" onclick="toggleSelect(this)">
|
||||
<div class="letter">A</div>
|
||||
<div class="content">
|
||||
<h3>Title</h3>
|
||||
<p>Description</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item. The indicator bar shows the count.
|
||||
|
||||
```html
|
||||
<div class="options" data-multiselect>
|
||||
<!-- same option markup — users can select/deselect multiple -->
|
||||
</div>
|
||||
```
|
||||
|
||||
### Cards (visual designs)
|
||||
|
||||
```html
|
||||
<div class="cards">
|
||||
<div class="card" data-choice="design1" onclick="toggleSelect(this)">
|
||||
<div class="card-image"><!-- mockup content --></div>
|
||||
<div class="card-body">
|
||||
<h3>Name</h3>
|
||||
<p>Description</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Mockup container
|
||||
|
||||
```html
|
||||
<div class="mockup">
|
||||
<div class="mockup-header">Preview: Dashboard Layout</div>
|
||||
<div class="mockup-body"><!-- your mockup HTML --></div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Split view (side-by-side)
|
||||
|
||||
```html
|
||||
<div class="split">
|
||||
<div class="mockup"><!-- left --></div>
|
||||
<div class="mockup"><!-- right --></div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Pros/Cons
|
||||
|
||||
```html
|
||||
<div class="pros-cons">
|
||||
<div class="pros"><h4>Pros</h4><ul><li>Benefit</li></ul></div>
|
||||
<div class="cons"><h4>Cons</h4><ul><li>Drawback</li></ul></div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Mock elements (wireframe building blocks)
|
||||
|
||||
```html
|
||||
<div class="mock-nav">Logo | Home | About | Contact</div>
|
||||
<div style="display: flex;">
|
||||
<div class="mock-sidebar">Navigation</div>
|
||||
<div class="mock-content">Main content area</div>
|
||||
</div>
|
||||
<button class="mock-button">Action Button</button>
|
||||
<input class="mock-input" placeholder="Input field">
|
||||
<div class="placeholder">Placeholder area</div>
|
||||
```
|
||||
|
||||
### Typography and sections
|
||||
|
||||
- `h2` — page title
|
||||
- `h3` — section heading
|
||||
- `.subtitle` — secondary text below title
|
||||
- `.section` — content block with bottom margin
|
||||
- `.label` — small uppercase label text
|
||||
|
||||
## Browser Events Format
|
||||
|
||||
When the user clicks options in the browser, their interactions are recorded to `$STATE_DIR/events` (one JSON object per line). The file is cleared automatically when you push a new screen.
|
||||
|
||||
```jsonl
|
||||
{"type":"click","choice":"a","text":"Option A - Simple Layout","timestamp":1706000101}
|
||||
{"type":"click","choice":"c","text":"Option C - Complex Grid","timestamp":1706000108}
|
||||
{"type":"click","choice":"b","text":"Option B - Hybrid","timestamp":1706000115}
|
||||
```
|
||||
|
||||
The full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about.
|
||||
|
||||
If `$STATE_DIR/events` doesn't exist, the user didn't interact with the browser — use only their terminal text.
|
||||
|
||||
## Design Tips
|
||||
|
||||
- **Scale fidelity to the question** — wireframes for layout, polish for polish questions
|
||||
- **Explain the question on each page** — "Which layout feels more professional?" not just "Pick one"
|
||||
- **Iterate before advancing** — if feedback changes current screen, write a new version
|
||||
- **2-4 options max** per screen
|
||||
- **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.
|
||||
- **Keep mockups simple** — focus on layout and structure, not pixel-perfect design
|
||||
|
||||
## File Naming
|
||||
|
||||
- Use semantic names: `platform.html`, `visual-style.html`, `layout.html`
|
||||
- Never reuse filenames — each screen must be a new file
|
||||
- For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`
|
||||
- Server serves newest file by modification time
|
||||
|
||||
## Cleaning Up
|
||||
|
||||
```bash
|
||||
scripts/stop-server.sh $SESSION_DIR
|
||||
```
|
||||
|
||||
If the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.
|
||||
|
||||
## Reference
|
||||
|
||||
- Frame template (CSS reference): `scripts/frame-template.html`
|
||||
- Helper script (client-side): `scripts/helper.js`
|
||||
@@ -0,0 +1,202 @@
|
||||
---
|
||||
name: dispatching-parallel-agents
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Fan work out across parallel subagents"
|
||||
use_when: "Decomposing work for concurrent agents"
|
||||
description: Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies
|
||||
---
|
||||
|
||||
# Dispatching Parallel Agents
|
||||
|
||||
## Overview
|
||||
|
||||
You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.
|
||||
|
||||
When you have multiple unrelated failures (different test files, different subsystems, different bugs), investigating them sequentially wastes time. Each investigation is independent and can happen in parallel.
|
||||
|
||||
**Core principle:** Dispatch one agent per independent problem domain. Let them work concurrently.
|
||||
|
||||
## When to Use
|
||||
|
||||
```dot
|
||||
digraph when_to_use {
|
||||
"Multiple failures?" [shape=diamond];
|
||||
"Are they independent?" [shape=diamond];
|
||||
"Single agent investigates all" [shape=box];
|
||||
"One agent per problem domain" [shape=box];
|
||||
"Can they work in parallel?" [shape=diamond];
|
||||
"Sequential agents" [shape=box];
|
||||
"Parallel dispatch" [shape=box];
|
||||
|
||||
"Multiple failures?" -> "Are they independent?" [label="yes"];
|
||||
"Are they independent?" -> "Single agent investigates all" [label="no - related"];
|
||||
"Are they independent?" -> "Can they work in parallel?" [label="yes"];
|
||||
"Can they work in parallel?" -> "Parallel dispatch" [label="yes"];
|
||||
"Can they work in parallel?" -> "Sequential agents" [label="no - shared state"];
|
||||
}
|
||||
```
|
||||
|
||||
**Use when:**
|
||||
- 3+ test files failing with different root causes
|
||||
- Multiple subsystems broken independently
|
||||
- Each problem can be understood without context from others
|
||||
- No shared state between investigations
|
||||
|
||||
**Don't use when:**
|
||||
- Failures are related (fix one might fix others)
|
||||
- Need to understand full system state
|
||||
- Agents would interfere with each other
|
||||
|
||||
## The Pattern
|
||||
|
||||
### 1. Identify Independent Domains
|
||||
|
||||
Group failures by what's broken:
|
||||
- File A tests: Tool approval flow
|
||||
- File B tests: Batch completion behavior
|
||||
- File C tests: Abort functionality
|
||||
|
||||
Each domain is independent - fixing tool approval doesn't affect abort tests.
|
||||
|
||||
### 2. Create Focused Agent Tasks
|
||||
|
||||
Each agent gets:
|
||||
- **Specific scope:** One test file or subsystem
|
||||
- **Clear goal:** Make these tests pass
|
||||
- **Constraints:** Don't change other code
|
||||
- **Expected output:** Summary of what you found and fixed
|
||||
|
||||
### 3. Dispatch in Parallel
|
||||
|
||||
Issue every dispatch in **one** message — several `Agent` tool uses in a single
|
||||
assistant turn run concurrently; one per turn runs them in series.
|
||||
|
||||
```
|
||||
Agent(description: "fix abort tests", subagent_type: "general-purpose", prompt: ...)
|
||||
Agent(description: "fix batch tests", subagent_type: "general-purpose", prompt: ...)
|
||||
Agent(description: "fix approval tests", subagent_type: "general-purpose", prompt: ...)
|
||||
```
|
||||
|
||||
Options that matter for this pattern:
|
||||
|
||||
- `run_in_background: true` (the default) returns immediately and notifies on
|
||||
completion. Set it to `false` only when your very next action depends on the result.
|
||||
- `isolation: "worktree"` gives an agent its own git worktree. Use it whenever two
|
||||
agents might touch the same files — parallel writers to one tree is the failure this
|
||||
skill's independence rule exists to avoid, and a worktree makes it structural rather
|
||||
than a matter of discipline.
|
||||
- `model` overrides the model per agent; cheap mechanical fan-out does not need the
|
||||
same model as the reasoning that planned it.
|
||||
|
||||
For a fan-out with real structure — phases, a verify pass per finding, fan-in — the
|
||||
`Workflow` tool expresses it directly with `agent()`, `parallel()` and `pipeline()`.
|
||||
It spawns many agents and costs accordingly, so it runs **only on explicit opt-in from
|
||||
the operator**; do not reach for it just because a task looks parallel.
|
||||
|
||||
### 4. Review and Integrate
|
||||
|
||||
When agents return:
|
||||
- Read each summary
|
||||
- Verify fixes don't conflict
|
||||
- Run full test suite
|
||||
- Integrate all changes
|
||||
|
||||
## Agent Prompt Structure
|
||||
|
||||
Good agent prompts are:
|
||||
1. **Focused** - One clear problem domain
|
||||
2. **Self-contained** - All context needed to understand the problem
|
||||
3. **Specific about output** - What should the agent return?
|
||||
|
||||
```markdown
|
||||
Fix the 3 failing tests in src/agents/agent-tool-abort.test.ts:
|
||||
|
||||
1. "should abort tool with partial output capture" - expects 'interrupted at' in message
|
||||
2. "should handle mixed completed and aborted tools" - fast tool aborted instead of completed
|
||||
3. "should properly track pendingToolCount" - expects 3 results but gets 0
|
||||
|
||||
These are timing/race condition issues. Your task:
|
||||
|
||||
1. Read the test file and understand what each test verifies
|
||||
2. Identify root cause - timing issues or actual bugs?
|
||||
3. Fix by:
|
||||
- Replacing arbitrary timeouts with event-based waiting
|
||||
- Fixing bugs in abort implementation if found
|
||||
- Adjusting test expectations if testing changed behavior
|
||||
|
||||
Do NOT just increase timeouts - find the real issue.
|
||||
|
||||
Return: Summary of what you found and what you fixed.
|
||||
```
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
**❌ Too broad:** "Fix all the tests" - agent gets lost
|
||||
**✅ Specific:** "Fix agent-tool-abort.test.ts" - focused scope
|
||||
|
||||
**❌ No context:** "Fix the race condition" - agent doesn't know where
|
||||
**✅ Context:** Paste the error messages and test names
|
||||
|
||||
**❌ No constraints:** Agent might refactor everything
|
||||
**✅ Constraints:** "Do NOT change production code" or "Fix tests only"
|
||||
|
||||
**❌ Vague output:** "Fix it" - you don't know what changed
|
||||
**✅ Specific:** "Return summary of root cause and changes"
|
||||
|
||||
## When NOT to Use
|
||||
|
||||
**Related failures:** Fixing one might fix others - investigate together first
|
||||
**Need full context:** Understanding requires seeing entire system
|
||||
**Exploratory debugging:** You don't know what's broken yet
|
||||
**Shared state:** Agents would interfere (editing same files, using same resources)
|
||||
|
||||
## Real Example from Session
|
||||
|
||||
**Scenario:** 6 test failures across 3 files after major refactoring
|
||||
|
||||
**Failures:**
|
||||
- agent-tool-abort.test.ts: 3 failures (timing issues)
|
||||
- batch-completion-behavior.test.ts: 2 failures (tools not executing)
|
||||
- tool-approval-race-conditions.test.ts: 1 failure (execution count = 0)
|
||||
|
||||
**Decision:** Independent domains - abort logic separate from batch completion separate from race conditions
|
||||
|
||||
**Dispatch:**
|
||||
```
|
||||
Agent 1 → Fix agent-tool-abort.test.ts
|
||||
Agent 2 → Fix batch-completion-behavior.test.ts
|
||||
Agent 3 → Fix tool-approval-race-conditions.test.ts
|
||||
```
|
||||
|
||||
**Results:**
|
||||
- Agent 1: Replaced timeouts with event-based waiting
|
||||
- Agent 2: Fixed event structure bug (threadId in wrong place)
|
||||
- Agent 3: Added wait for async tool execution to complete
|
||||
|
||||
**Integration:** All fixes independent, no conflicts, full suite green
|
||||
|
||||
**Time saved:** 3 problems solved in parallel vs sequentially
|
||||
|
||||
## Key Benefits
|
||||
|
||||
1. **Parallelization** - Multiple investigations happen simultaneously
|
||||
2. **Focus** - Each agent has narrow scope, less context to track
|
||||
3. **Independence** - Agents don't interfere with each other
|
||||
4. **Speed** - 3 problems solved in time of 1
|
||||
|
||||
## Verification
|
||||
|
||||
After agents return:
|
||||
1. **Review each summary** - Understand what changed
|
||||
2. **Check for conflicts** - Did agents edit same code?
|
||||
3. **Run full suite** - Verify all fixes work together
|
||||
4. **Spot check** - Agents can make systematic errors
|
||||
|
||||
## Real-World Impact
|
||||
|
||||
From debugging session (2025-10-03):
|
||||
- 6 failures across 3 files
|
||||
- 3 agents dispatched in parallel
|
||||
- All investigations completed concurrently
|
||||
- All fixes integrated successfully
|
||||
- Zero conflicts between agent changes
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
name: executing-plans
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Executing a written plan step by step"
|
||||
use_when: "Running an approved plan to completion"
|
||||
description: Use when you have a written implementation plan to execute in a separate session with review checkpoints
|
||||
---
|
||||
|
||||
# Executing Plans
|
||||
|
||||
## Overview
|
||||
|
||||
Load plan, review critically, execute all tasks, report when complete.
|
||||
|
||||
**Announce at start:** "I'm using the executing-plans skill to implement this plan."
|
||||
|
||||
**Note:** This skill is the fallback for harnesses with no subagents. Claude Code has
|
||||
them — the `Agent` tool — so on this fleet prefer `superpowers-subagent-driven-development`
|
||||
and use this skill only where `Agent` is genuinely unavailable (Crush, Pi, OpenCode).
|
||||
|
||||
## The Process
|
||||
|
||||
### Step 1: Load and Review Plan
|
||||
1. Read plan file
|
||||
2. Review critically - identify any questions or concerns about the plan
|
||||
3. If concerns: Raise them with the operator before starting
|
||||
4. If no concerns: Create TodoWrite and proceed
|
||||
|
||||
### Step 2: Execute Tasks
|
||||
|
||||
For each task:
|
||||
1. Mark as in_progress
|
||||
2. Follow each step exactly (plan has bite-sized steps)
|
||||
3. Run verifications as specified
|
||||
4. Mark as completed
|
||||
|
||||
### Step 3: Complete Development
|
||||
|
||||
After all tasks complete and verified:
|
||||
- Announce: "I'm using the finishing-a-development-branch skill to complete this work."
|
||||
- **REQUIRED SUB-SKILL:** Use superpowers:finishing-a-development-branch
|
||||
- Follow that skill to verify tests, present options, execute choice
|
||||
|
||||
## When to Stop and Ask for Help
|
||||
|
||||
**STOP executing immediately when:**
|
||||
- Hit a blocker (missing dependency, test fails, instruction unclear)
|
||||
- Plan has critical gaps preventing starting
|
||||
- You don't understand an instruction
|
||||
- Verification fails repeatedly
|
||||
|
||||
**Ask for clarification rather than guessing.**
|
||||
|
||||
## When to Revisit Earlier Steps
|
||||
|
||||
**Return to Review (Step 1) when:**
|
||||
- Partner updates the plan based on your feedback
|
||||
- Fundamental approach needs rethinking
|
||||
|
||||
**Don't force through blockers** - stop and ask.
|
||||
|
||||
## Remember
|
||||
- Review plan critically first
|
||||
- Follow plan steps exactly
|
||||
- Don't skip verifications
|
||||
- Reference skills when plan says to
|
||||
- Stop when blocked, don't guess
|
||||
- Never start implementation on main/master branch without explicit user consent
|
||||
|
||||
## Integration
|
||||
|
||||
**Required workflow skills:**
|
||||
- **superpowers:using-git-worktrees** - Ensures isolated workspace (creates one or verifies existing)
|
||||
- **superpowers:writing-plans** - Creates the plan this skill executes
|
||||
- **superpowers:finishing-a-development-branch** - Complete development after all tasks
|
||||
@@ -0,0 +1,254 @@
|
||||
---
|
||||
name: finishing-a-development-branch
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Cleanly finishing/landing a dev branch"
|
||||
use_when: "Wrapping a branch → merge/PR"
|
||||
description: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup
|
||||
---
|
||||
|
||||
# Finishing a Development Branch
|
||||
|
||||
## Overview
|
||||
|
||||
Guide completion of development work by presenting clear options and handling chosen workflow.
|
||||
|
||||
**Core principle:** Verify tests → Detect environment → Present options → Execute choice → Clean up.
|
||||
|
||||
**Announce at start:** "I'm using the finishing-a-development-branch skill to complete this work."
|
||||
|
||||
## The Process
|
||||
|
||||
### Step 1: Verify Tests
|
||||
|
||||
**Before presenting options, verify tests pass:**
|
||||
|
||||
```bash
|
||||
# Run project's test suite
|
||||
npm test / cargo test / pytest / go test ./...
|
||||
```
|
||||
|
||||
**If tests fail:**
|
||||
```
|
||||
Tests failing (<N> failures). Must fix before completing:
|
||||
|
||||
[Show failures]
|
||||
|
||||
Cannot proceed with merge/PR until tests pass.
|
||||
```
|
||||
|
||||
Stop. Don't proceed to Step 2.
|
||||
|
||||
**If tests pass:** Continue to Step 2.
|
||||
|
||||
### Step 2: Detect Environment
|
||||
|
||||
**Determine workspace state before presenting options:**
|
||||
|
||||
```bash
|
||||
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
|
||||
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
|
||||
```
|
||||
|
||||
This determines which menu to show and how cleanup works:
|
||||
|
||||
| State | Menu | Cleanup |
|
||||
|-------|------|---------|
|
||||
| `GIT_DIR == GIT_COMMON` (normal repo) | Standard 4 options | No worktree to clean up |
|
||||
| `GIT_DIR != GIT_COMMON`, named branch | Standard 4 options | Provenance-based (see Step 6) |
|
||||
| `GIT_DIR != GIT_COMMON`, detached HEAD | Reduced 3 options (no merge) | No cleanup (externally managed) |
|
||||
|
||||
### Step 3: Determine Base Branch
|
||||
|
||||
```bash
|
||||
# Try common base branches
|
||||
git merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null
|
||||
```
|
||||
|
||||
Or ask: "This branch split from main - is that correct?"
|
||||
|
||||
### Step 4: Present Options
|
||||
|
||||
**Normal repo and named-branch worktree — present exactly these 4 options:**
|
||||
|
||||
```
|
||||
Implementation complete. What would you like to do?
|
||||
|
||||
1. Merge back to <base-branch> locally
|
||||
2. Push and create a Pull Request
|
||||
3. Keep the branch as-is (I'll handle it later)
|
||||
4. Discard this work
|
||||
|
||||
Which option?
|
||||
```
|
||||
|
||||
**Detached HEAD — present exactly these 3 options:**
|
||||
|
||||
```
|
||||
Implementation complete. You're on a detached HEAD (externally managed workspace).
|
||||
|
||||
1. Push as new branch and create a Pull Request
|
||||
2. Keep as-is (I'll handle it later)
|
||||
3. Discard this work
|
||||
|
||||
Which option?
|
||||
```
|
||||
|
||||
**Don't add explanation** - keep options concise.
|
||||
|
||||
### Step 5: Execute Choice
|
||||
|
||||
#### Option 1: Merge Locally
|
||||
|
||||
```bash
|
||||
# Get main repo root for CWD safety
|
||||
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
|
||||
cd "$MAIN_ROOT"
|
||||
|
||||
# Merge first — verify success before removing anything
|
||||
git checkout <base-branch>
|
||||
git pull
|
||||
git merge <feature-branch>
|
||||
|
||||
# Verify tests on merged result
|
||||
<test command>
|
||||
|
||||
# Only after merge succeeds: cleanup worktree (Step 6), then delete branch
|
||||
```
|
||||
|
||||
Then: Cleanup worktree (Step 6), then delete branch:
|
||||
|
||||
```bash
|
||||
git branch -d <feature-branch>
|
||||
```
|
||||
|
||||
#### Option 2: Push and Create PR
|
||||
|
||||
```bash
|
||||
# Push branch
|
||||
git push -u origin <feature-branch>
|
||||
|
||||
# Create PR
|
||||
gh pr create --title "<title>" --body "$(cat <<'EOF'
|
||||
## Summary
|
||||
<2-3 bullets of what changed>
|
||||
|
||||
## Test Plan
|
||||
- [ ] <verification steps>
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
**Do NOT clean up worktree** — user needs it alive to iterate on PR feedback.
|
||||
|
||||
#### Option 3: Keep As-Is
|
||||
|
||||
Report: "Keeping branch <name>. Worktree preserved at <path>."
|
||||
|
||||
**Don't cleanup worktree.**
|
||||
|
||||
#### Option 4: Discard
|
||||
|
||||
**Confirm first:**
|
||||
```
|
||||
This will permanently delete:
|
||||
- Branch <name>
|
||||
- All commits: <commit-list>
|
||||
- Worktree at <path>
|
||||
|
||||
Type 'discard' to confirm.
|
||||
```
|
||||
|
||||
Wait for exact confirmation.
|
||||
|
||||
If confirmed:
|
||||
```bash
|
||||
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
|
||||
cd "$MAIN_ROOT"
|
||||
```
|
||||
|
||||
Then: Cleanup worktree (Step 6), then force-delete branch:
|
||||
```bash
|
||||
git branch -D <feature-branch>
|
||||
```
|
||||
|
||||
### Step 6: Cleanup Workspace
|
||||
|
||||
**Only runs for Options 1 and 4.** Options 2 and 3 always preserve the worktree.
|
||||
|
||||
```bash
|
||||
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
|
||||
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
|
||||
WORKTREE_PATH=$(git rev-parse --show-toplevel)
|
||||
```
|
||||
|
||||
**If `GIT_DIR == GIT_COMMON`:** Normal repo, no worktree to clean up. Done.
|
||||
|
||||
**If worktree path is under `.worktrees/`, `worktrees/`, or `~/.config/superpowers/worktrees/`:** Superpowers created this worktree — we own cleanup.
|
||||
|
||||
```bash
|
||||
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
|
||||
cd "$MAIN_ROOT"
|
||||
git worktree remove "$WORKTREE_PATH"
|
||||
git worktree prune # Self-healing: clean up any stale registrations
|
||||
```
|
||||
|
||||
**Otherwise:** The host environment (harness) owns this workspace. Do NOT remove it. If your platform provides a workspace-exit tool, use it. Otherwise, leave the workspace in place.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Option | Merge | Push | Keep Worktree | Cleanup Branch |
|
||||
|--------|-------|------|---------------|----------------|
|
||||
| 1. Merge locally | yes | - | - | yes |
|
||||
| 2. Create PR | - | yes | yes | - |
|
||||
| 3. Keep as-is | - | - | yes | - |
|
||||
| 4. Discard | - | - | - | yes (force) |
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
**Skipping test verification**
|
||||
- **Problem:** Merge broken code, create failing PR
|
||||
- **Fix:** Always verify tests before offering options
|
||||
|
||||
**Open-ended questions**
|
||||
- **Problem:** "What should I do next?" is ambiguous
|
||||
- **Fix:** Present exactly 4 structured options (or 3 for detached HEAD)
|
||||
|
||||
**Cleaning up worktree for Option 2**
|
||||
- **Problem:** Remove worktree user needs for PR iteration
|
||||
- **Fix:** Only cleanup for Options 1 and 4
|
||||
|
||||
**Deleting branch before removing worktree**
|
||||
- **Problem:** `git branch -d` fails because worktree still references the branch
|
||||
- **Fix:** Merge first, remove worktree, then delete branch
|
||||
|
||||
**Running git worktree remove from inside the worktree**
|
||||
- **Problem:** Command fails silently when CWD is inside the worktree being removed
|
||||
- **Fix:** Always `cd` to main repo root before `git worktree remove`
|
||||
|
||||
**Cleaning up harness-owned worktrees**
|
||||
- **Problem:** Removing a worktree the harness created causes phantom state
|
||||
- **Fix:** Only clean up worktrees under `.worktrees/`, `worktrees/`, or `~/.config/superpowers/worktrees/`
|
||||
|
||||
**No confirmation for discard**
|
||||
- **Problem:** Accidentally delete work
|
||||
- **Fix:** Require typed "discard" confirmation
|
||||
|
||||
## Red Flags
|
||||
|
||||
**Never:**
|
||||
- Proceed with failing tests
|
||||
- Merge without verifying tests on result
|
||||
- Delete work without confirmation
|
||||
- Force-push without explicit request
|
||||
- Remove a worktree before confirming merge success
|
||||
- Clean up worktrees you didn't create (provenance check)
|
||||
- Run `git worktree remove` from inside the worktree
|
||||
|
||||
**Always:**
|
||||
- Verify tests before offering options
|
||||
- Detect environment before presenting menu
|
||||
- Present exactly 4 options (or 3 for detached HEAD)
|
||||
- Get typed confirmation for Option 4
|
||||
- Clean up worktree for Options 1 & 4 only
|
||||
- `cd` to main repo root before worktree removal
|
||||
- Run `git worktree prune` after removal
|
||||
@@ -0,0 +1,218 @@
|
||||
---
|
||||
name: receiving-code-review
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Acting on received review feedback"
|
||||
use_when: "Responding to review comments"
|
||||
description: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation
|
||||
---
|
||||
|
||||
# Code Review Reception
|
||||
|
||||
## Overview
|
||||
|
||||
Code review requires technical evaluation, not emotional performance.
|
||||
|
||||
**Core principle:** Verify before implementing. Ask before assuming. Technical correctness over social comfort.
|
||||
|
||||
This skill starts where `superpowers-requesting-code-review` ends. The substance of what a reviewer should have checked is `code-review`.
|
||||
|
||||
## The Response Pattern
|
||||
|
||||
```
|
||||
WHEN receiving code review feedback:
|
||||
|
||||
1. READ: Complete feedback without reacting
|
||||
2. UNDERSTAND: Restate requirement in own words (or ask)
|
||||
3. VERIFY: Check against codebase reality
|
||||
4. EVALUATE: Technically sound for THIS codebase?
|
||||
5. RESPOND: Technical acknowledgment or reasoned pushback
|
||||
6. IMPLEMENT: One item at a time, test each
|
||||
```
|
||||
|
||||
## Forbidden Responses
|
||||
|
||||
**NEVER:**
|
||||
- "You're absolutely right!" (performative agreement, not evaluation)
|
||||
- "Great point!" / "Excellent feedback!" (performative)
|
||||
- "Let me implement that now" (before verification)
|
||||
|
||||
**INSTEAD:**
|
||||
- Restate the technical requirement
|
||||
- Ask clarifying questions
|
||||
- Push back with technical reasoning if wrong
|
||||
- Just start working (actions > words)
|
||||
|
||||
## Handling Unclear Feedback
|
||||
|
||||
```
|
||||
IF any item is unclear:
|
||||
STOP - do not implement anything yet
|
||||
ASK for clarification on unclear items
|
||||
|
||||
WHY: Items may be related. Partial understanding = wrong implementation.
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```
|
||||
the operator: "Fix 1-6"
|
||||
You understand 1,2,3,6. Unclear on 4,5.
|
||||
|
||||
❌ WRONG: Implement 1,2,3,6 now, ask about 4,5 later
|
||||
✅ RIGHT: "I understand items 1,2,3,6. Need clarification on 4 and 5 before proceeding."
|
||||
```
|
||||
|
||||
## Source-Specific Handling
|
||||
|
||||
### From the operator
|
||||
- **Trusted** - implement after understanding
|
||||
- **Still ask** if scope unclear
|
||||
- **No performative agreement**
|
||||
- **Skip to action** or technical acknowledgment
|
||||
|
||||
### From External Reviewers
|
||||
```
|
||||
BEFORE implementing:
|
||||
1. Check: Technically correct for THIS codebase?
|
||||
2. Check: Breaks existing functionality?
|
||||
3. Check: Reason for current implementation?
|
||||
4. Check: Works on all platforms/versions?
|
||||
5. Check: Does reviewer understand full context?
|
||||
|
||||
IF suggestion seems wrong:
|
||||
Push back with technical reasoning
|
||||
|
||||
IF can't easily verify:
|
||||
Say so: "I can't verify this without [X]. Should I [investigate/ask/proceed]?"
|
||||
|
||||
IF conflicts with the operator's prior decisions:
|
||||
Stop and discuss with the operator first
|
||||
```
|
||||
|
||||
**the operator's rule:** "External feedback - be skeptical, but check carefully"
|
||||
|
||||
## YAGNI Check for "Professional" Features
|
||||
|
||||
```
|
||||
IF reviewer suggests "implementing properly":
|
||||
grep codebase for actual usage
|
||||
|
||||
IF unused: "This endpoint isn't called. Remove it (YAGNI)?"
|
||||
IF used: Then implement properly
|
||||
```
|
||||
|
||||
**the operator's rule:** "You and reviewer both report to me. If we don't need this feature, don't add it."
|
||||
|
||||
## Implementation Order
|
||||
|
||||
```
|
||||
FOR multi-item feedback:
|
||||
1. Clarify anything unclear FIRST
|
||||
2. Then implement in this order:
|
||||
- Blocking issues (breaks, security)
|
||||
- Simple fixes (typos, imports)
|
||||
- Complex fixes (refactoring, logic)
|
||||
3. Test each fix individually
|
||||
4. Verify no regressions
|
||||
```
|
||||
|
||||
## When To Push Back
|
||||
|
||||
Push back when:
|
||||
- Suggestion breaks existing functionality
|
||||
- Reviewer lacks full context
|
||||
- Violates YAGNI (unused feature)
|
||||
- Technically incorrect for this stack
|
||||
- Legacy/compatibility reasons exist
|
||||
- Conflicts with the operator's architectural decisions
|
||||
|
||||
**How to push back:**
|
||||
- Use technical reasoning, not defensiveness
|
||||
- Ask specific questions
|
||||
- Reference working tests/code
|
||||
- Involve the operator if architectural
|
||||
|
||||
**Signal if uncomfortable pushing back out loud:** "Strange things are afoot at the Circle K"
|
||||
|
||||
## Acknowledging Correct Feedback
|
||||
|
||||
When feedback IS correct:
|
||||
```
|
||||
✅ "Fixed. [Brief description of what changed]"
|
||||
✅ "Good catch - [specific issue]. Fixed in [location]."
|
||||
✅ [Just fix it and show in the code]
|
||||
|
||||
❌ "You're absolutely right!"
|
||||
❌ "Great point!"
|
||||
❌ "Thanks for catching that!"
|
||||
❌ "Thanks for [anything]"
|
||||
❌ ANY gratitude expression
|
||||
```
|
||||
|
||||
**Why no thanks:** Actions speak. Just fix it. The code itself shows you heard the feedback.
|
||||
|
||||
**If you catch yourself about to write "Thanks":** DELETE IT. State the fix instead.
|
||||
|
||||
## Gracefully Correcting Your Pushback
|
||||
|
||||
If you pushed back and were wrong:
|
||||
```
|
||||
✅ "You were right - I checked [X] and it does [Y]. Implementing now."
|
||||
✅ "Verified this and you're correct. My initial understanding was wrong because [reason]. Fixing."
|
||||
|
||||
❌ Long apology
|
||||
❌ Defending why you pushed back
|
||||
❌ Over-explaining
|
||||
```
|
||||
|
||||
State the correction factually and move on.
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
| Mistake | Fix |
|
||||
|---------|-----|
|
||||
| Performative agreement | State requirement or just act |
|
||||
| Blind implementation | Verify against codebase first |
|
||||
| Batch without testing | One at a time, test each |
|
||||
| Assuming reviewer is right | Check if breaks things |
|
||||
| Avoiding pushback | Technical correctness > comfort |
|
||||
| Partial implementation | Clarify all items first |
|
||||
| Can't verify, proceed anyway | State limitation, ask for direction |
|
||||
|
||||
## Real Examples
|
||||
|
||||
**Performative Agreement (Bad):**
|
||||
```
|
||||
Reviewer: "Remove legacy code"
|
||||
❌ "You're absolutely right! Let me remove that..."
|
||||
```
|
||||
|
||||
**Technical Verification (Good):**
|
||||
```
|
||||
Reviewer: "Remove legacy code"
|
||||
✅ "Checking... build target is 10.15+, this API needs 13+. Need legacy for backward compat. Current impl has wrong bundle ID - fix it or drop pre-13 support?"
|
||||
```
|
||||
|
||||
**YAGNI (Good):**
|
||||
```
|
||||
Reviewer: "Implement proper metrics tracking with database, date filters, CSV export"
|
||||
✅ "Grepped codebase - nothing calls this endpoint. Remove it (YAGNI)? Or is there usage I'm missing?"
|
||||
```
|
||||
|
||||
**Unclear Item (Good):**
|
||||
```
|
||||
the operator: "Fix items 1-6"
|
||||
You understand 1,2,3,6. Unclear on 4,5.
|
||||
✅ "Understand 1,2,3,6. Need clarification on 4 and 5 before implementing."
|
||||
```
|
||||
|
||||
## GitHub Thread Replies
|
||||
|
||||
When replying to inline review comments on GitHub, reply in the comment thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level PR comment.
|
||||
|
||||
## The Bottom Line
|
||||
|
||||
**External feedback = suggestions to evaluate, not orders to follow.**
|
||||
|
||||
Verify. Question. Then implement.
|
||||
|
||||
No performative agreement. Technical rigor always.
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
name: requesting-code-review
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Requesting a code review well"
|
||||
use_when: "Asking another agent/human to review"
|
||||
description: Use when completing tasks, implementing major features, or before merging to verify work meets requirements
|
||||
---
|
||||
|
||||
# Requesting Code Review
|
||||
|
||||
Dispatch a code reviewer subagent to catch issues before they cascade. The reviewer gets precisely crafted context for evaluation — never your session's history. This keeps the reviewer focused on the work product, not your thought process, and preserves your own context for continued work.
|
||||
|
||||
**Core principle:** Review early, review often.
|
||||
|
||||
This skill is the *commissioning* half. What the reviewer should look for is `code-review`; how to handle what comes back is `superpowers-receiving-code-review`.
|
||||
|
||||
## When to Request Review
|
||||
|
||||
**Mandatory:**
|
||||
- After each task in subagent-driven development
|
||||
- After completing major feature
|
||||
- Before merge to main
|
||||
|
||||
**Optional but valuable:**
|
||||
- When stuck (fresh perspective)
|
||||
- Before refactoring (baseline check)
|
||||
- After fixing complex bug
|
||||
|
||||
## How to Request
|
||||
|
||||
**1. Get git SHAs:**
|
||||
```bash
|
||||
BASE_SHA=$(git rev-parse HEAD~1) # or origin/main
|
||||
HEAD_SHA=$(git rev-parse HEAD)
|
||||
```
|
||||
|
||||
**2. Dispatch code reviewer subagent:**
|
||||
|
||||
Use the `Agent` tool with `subagent_type: "general-purpose"`, filling the template at
|
||||
`code-reviewer.md`. A reviewer needs no write access and benefits from none — if the
|
||||
harness offers a read-only agent type, prefer it.
|
||||
|
||||
**Placeholders:**
|
||||
- `{DESCRIPTION}` - Brief summary of what you built
|
||||
- `{PLAN_OR_REQUIREMENTS}` - What it should do
|
||||
- `{BASE_SHA}` - Starting commit
|
||||
- `{HEAD_SHA}` - Ending commit
|
||||
|
||||
**3. Act on feedback:**
|
||||
- Fix Critical issues immediately
|
||||
- Fix Important issues before proceeding
|
||||
- Note Minor issues for later
|
||||
- Push back if reviewer is wrong (with reasoning)
|
||||
|
||||
## Example
|
||||
|
||||
```
|
||||
[Just completed Task 2: Add verification function]
|
||||
|
||||
You: Let me request code review before proceeding.
|
||||
|
||||
BASE_SHA=$(git log --oneline | grep "Task 1" | head -1 | awk '{print $1}')
|
||||
HEAD_SHA=$(git rev-parse HEAD)
|
||||
|
||||
[Dispatch code reviewer subagent]
|
||||
DESCRIPTION: Added verifyIndex() and repairIndex() with 4 issue types
|
||||
PLAN_OR_REQUIREMENTS: Task 2 from docs/superpowers/plans/deployment-plan.md
|
||||
BASE_SHA: a7981ec
|
||||
HEAD_SHA: 3df7661
|
||||
|
||||
[Subagent returns]:
|
||||
Strengths: Clean architecture, real tests
|
||||
Issues:
|
||||
Important: Missing progress indicators
|
||||
Minor: Magic number (100) for reporting interval
|
||||
Assessment: Ready to proceed
|
||||
|
||||
You: [Fix progress indicators]
|
||||
[Continue to Task 3]
|
||||
```
|
||||
|
||||
## Integration with Workflows
|
||||
|
||||
**Subagent-Driven Development:**
|
||||
- Review after EACH task
|
||||
- Catch issues before they compound
|
||||
- Fix before moving to next task
|
||||
|
||||
**Executing Plans:**
|
||||
- Review after each task or at natural checkpoints
|
||||
- Get feedback, apply, continue
|
||||
|
||||
**Ad-Hoc Development:**
|
||||
- Review before merge
|
||||
- Review when stuck
|
||||
|
||||
## Red Flags
|
||||
|
||||
**Never:**
|
||||
- Skip review because "it's simple"
|
||||
- Ignore Critical issues
|
||||
- Proceed with unfixed Important issues
|
||||
- Argue with valid technical feedback
|
||||
|
||||
**If reviewer wrong:**
|
||||
- Push back with technical reasoning
|
||||
- Show code/tests that prove it works
|
||||
- Request clarification
|
||||
|
||||
See template at: requesting-code-review/code-reviewer.md
|
||||
@@ -0,0 +1,168 @@
|
||||
# Code Reviewer Prompt Template
|
||||
|
||||
Use this template when dispatching a code reviewer subagent.
|
||||
|
||||
**Purpose:** Review completed work against requirements and code quality standards before it cascades into more work.
|
||||
|
||||
```
|
||||
Agent tool (`subagent_type: "general-purpose"`):
|
||||
description: "Review code changes"
|
||||
prompt: |
|
||||
You are a Senior Code Reviewer with expertise in software architecture,
|
||||
design patterns, and best practices. Your job is to review completed work
|
||||
against its plan or requirements and identify issues before they cascade.
|
||||
|
||||
## What Was Implemented
|
||||
|
||||
{DESCRIPTION}
|
||||
|
||||
## Requirements / Plan
|
||||
|
||||
{PLAN_OR_REQUIREMENTS}
|
||||
|
||||
## Git Range to Review
|
||||
|
||||
**Base:** {BASE_SHA}
|
||||
**Head:** {HEAD_SHA}
|
||||
|
||||
```bash
|
||||
git diff --stat {BASE_SHA}..{HEAD_SHA}
|
||||
git diff {BASE_SHA}..{HEAD_SHA}
|
||||
```
|
||||
|
||||
## What to Check
|
||||
|
||||
**Plan alignment:**
|
||||
- Does the implementation match the plan / requirements?
|
||||
- Are deviations justified improvements, or problematic departures?
|
||||
- Is all planned functionality present?
|
||||
|
||||
**Code quality:**
|
||||
- Clean separation of concerns?
|
||||
- Proper error handling?
|
||||
- Type safety where applicable?
|
||||
- DRY without premature abstraction?
|
||||
- Edge cases handled?
|
||||
|
||||
**Architecture:**
|
||||
- Sound design decisions?
|
||||
- Reasonable scalability and performance?
|
||||
- Security concerns?
|
||||
- Integrates cleanly with surrounding code?
|
||||
|
||||
**Testing:**
|
||||
- Tests verify real behavior, not mocks?
|
||||
- Edge cases covered?
|
||||
- Integration tests where they matter?
|
||||
- All tests passing?
|
||||
|
||||
**Production readiness:**
|
||||
- Migration strategy if schema changed?
|
||||
- Backward compatibility considered?
|
||||
- Documentation complete?
|
||||
- No obvious bugs?
|
||||
|
||||
## Calibration
|
||||
|
||||
Categorize issues by actual severity. Not everything is Critical.
|
||||
Acknowledge what was done well before listing issues — accurate praise
|
||||
helps the implementer trust the rest of the feedback.
|
||||
|
||||
If you find significant deviations from the plan, flag them specifically
|
||||
so the implementer can confirm whether the deviation was intentional.
|
||||
If you find issues with the plan itself rather than the implementation,
|
||||
say so.
|
||||
|
||||
## Output Format
|
||||
|
||||
### Strengths
|
||||
[What's well done? Be specific.]
|
||||
|
||||
### Issues
|
||||
|
||||
#### Critical (Must Fix)
|
||||
[Bugs, security issues, data loss risks, broken functionality]
|
||||
|
||||
#### Important (Should Fix)
|
||||
[Architecture problems, missing features, poor error handling, test gaps]
|
||||
|
||||
#### Minor (Nice to Have)
|
||||
[Code style, optimization opportunities, documentation polish]
|
||||
|
||||
For each issue:
|
||||
- File:line reference
|
||||
- What's wrong
|
||||
- Why it matters
|
||||
- How to fix (if not obvious)
|
||||
|
||||
### Recommendations
|
||||
[Improvements for code quality, architecture, or process]
|
||||
|
||||
### Assessment
|
||||
|
||||
**Ready to merge?** [Yes | No | With fixes]
|
||||
|
||||
**Reasoning:** [1-2 sentence technical assessment]
|
||||
|
||||
## Critical Rules
|
||||
|
||||
**DO:**
|
||||
- Categorize by actual severity
|
||||
- Be specific (file:line, not vague)
|
||||
- Explain WHY each issue matters
|
||||
- Acknowledge strengths
|
||||
- Give a clear verdict
|
||||
|
||||
**DON'T:**
|
||||
- Say "looks good" without checking
|
||||
- Mark nitpicks as Critical
|
||||
- Give feedback on code you didn't actually read
|
||||
- Be vague ("improve error handling")
|
||||
- Avoid giving a clear verdict
|
||||
```
|
||||
|
||||
**Placeholders:**
|
||||
- `{DESCRIPTION}` — brief summary of what was built
|
||||
- `{PLAN_OR_REQUIREMENTS}` — what it should do (plan file path, task text, or requirements)
|
||||
- `{BASE_SHA}` — starting commit
|
||||
- `{HEAD_SHA}` — ending commit
|
||||
|
||||
**Reviewer returns:** Strengths, Issues (Critical / Important / Minor), Recommendations, Assessment
|
||||
|
||||
## Example Output
|
||||
|
||||
```
|
||||
### Strengths
|
||||
- Clean database schema with proper migrations (db.ts:15-42)
|
||||
- Comprehensive test coverage (18 tests, all edge cases)
|
||||
- Good error handling with fallbacks (summarizer.ts:85-92)
|
||||
|
||||
### Issues
|
||||
|
||||
#### Important
|
||||
1. **Missing help text in CLI wrapper**
|
||||
- File: index-conversations:1-31
|
||||
- Issue: No --help flag, users won't discover --concurrency
|
||||
- Fix: Add --help case with usage examples
|
||||
|
||||
2. **Date validation missing**
|
||||
- File: search.ts:25-27
|
||||
- Issue: Invalid dates silently return no results
|
||||
- Fix: Validate ISO format, throw error with example
|
||||
|
||||
#### Minor
|
||||
1. **Progress indicators**
|
||||
- File: indexer.ts:130
|
||||
- Issue: No "X of Y" counter for long operations
|
||||
- Impact: Users don't know how long to wait
|
||||
|
||||
### Recommendations
|
||||
- Add progress reporting for user experience
|
||||
- Consider config file for excluded projects (portability)
|
||||
|
||||
### Assessment
|
||||
|
||||
**Ready to merge: With fixes**
|
||||
|
||||
**Reasoning:** Core implementation is solid with good architecture and tests. Important issues (help text, date validation) are easily fixed and don't affect core functionality.
|
||||
```
|
||||
@@ -0,0 +1,282 @@
|
||||
---
|
||||
name: subagent-driven-development
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Subagent-driven development workflow"
|
||||
use_when: "Building via orchestrated subagents"
|
||||
description: Use when executing implementation plans with independent tasks in the current session
|
||||
---
|
||||
|
||||
# Subagent-Driven Development
|
||||
|
||||
Execute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review.
|
||||
|
||||
**Why subagents:** You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.
|
||||
|
||||
**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration
|
||||
|
||||
**Continuous execution:** Do not pause to check in with the operator between tasks. Execute all tasks from the plan without stopping. The only reasons to stop are: BLOCKED status you cannot resolve, ambiguity that genuinely prevents progress, or all tasks complete. "Should I continue?" prompts and progress summaries waste their time — they asked you to execute the plan, so execute it.
|
||||
|
||||
## When to Use
|
||||
|
||||
```dot
|
||||
digraph when_to_use {
|
||||
"Have implementation plan?" [shape=diamond];
|
||||
"Tasks mostly independent?" [shape=diamond];
|
||||
"Stay in this session?" [shape=diamond];
|
||||
"subagent-driven-development" [shape=box];
|
||||
"executing-plans" [shape=box];
|
||||
"Manual execution or brainstorm first" [shape=box];
|
||||
|
||||
"Have implementation plan?" -> "Tasks mostly independent?" [label="yes"];
|
||||
"Have implementation plan?" -> "Manual execution or brainstorm first" [label="no"];
|
||||
"Tasks mostly independent?" -> "Stay in this session?" [label="yes"];
|
||||
"Tasks mostly independent?" -> "Manual execution or brainstorm first" [label="no - tightly coupled"];
|
||||
"Stay in this session?" -> "subagent-driven-development" [label="yes"];
|
||||
"Stay in this session?" -> "executing-plans" [label="no - parallel session"];
|
||||
}
|
||||
```
|
||||
|
||||
**vs. Executing Plans (parallel session):**
|
||||
- Same session (no context switch)
|
||||
- Fresh subagent per task (no context pollution)
|
||||
- Two-stage review after each task: spec compliance first, then code quality
|
||||
- Faster iteration (no human-in-loop between tasks)
|
||||
|
||||
## The Process
|
||||
|
||||
```dot
|
||||
digraph process {
|
||||
rankdir=TB;
|
||||
|
||||
subgraph cluster_per_task {
|
||||
label="Per Task";
|
||||
"Dispatch implementer subagent (./implementer-prompt.md)" [shape=box];
|
||||
"Implementer subagent asks questions?" [shape=diamond];
|
||||
"Answer questions, provide context" [shape=box];
|
||||
"Implementer subagent implements, tests, commits, self-reviews" [shape=box];
|
||||
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [shape=box];
|
||||
"Spec reviewer subagent confirms code matches spec?" [shape=diamond];
|
||||
"Implementer subagent fixes spec gaps" [shape=box];
|
||||
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [shape=box];
|
||||
"Code quality reviewer subagent approves?" [shape=diamond];
|
||||
"Implementer subagent fixes quality issues" [shape=box];
|
||||
"Mark task complete in TodoWrite" [shape=box];
|
||||
}
|
||||
|
||||
"Read plan, extract all tasks with full text, note context, create TodoWrite" [shape=box];
|
||||
"More tasks remain?" [shape=diamond];
|
||||
"Dispatch final code reviewer subagent for entire implementation" [shape=box];
|
||||
"Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen];
|
||||
|
||||
"Read plan, extract all tasks with full text, note context, create TodoWrite" -> "Dispatch implementer subagent (./implementer-prompt.md)";
|
||||
"Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer subagent asks questions?";
|
||||
"Implementer subagent asks questions?" -> "Answer questions, provide context" [label="yes"];
|
||||
"Answer questions, provide context" -> "Dispatch implementer subagent (./implementer-prompt.md)";
|
||||
"Implementer subagent asks questions?" -> "Implementer subagent implements, tests, commits, self-reviews" [label="no"];
|
||||
"Implementer subagent implements, tests, commits, self-reviews" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)";
|
||||
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" -> "Spec reviewer subagent confirms code matches spec?";
|
||||
"Spec reviewer subagent confirms code matches spec?" -> "Implementer subagent fixes spec gaps" [label="no"];
|
||||
"Implementer subagent fixes spec gaps" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [label="re-review"];
|
||||
"Spec reviewer subagent confirms code matches spec?" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="yes"];
|
||||
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" -> "Code quality reviewer subagent approves?";
|
||||
"Code quality reviewer subagent approves?" -> "Implementer subagent fixes quality issues" [label="no"];
|
||||
"Implementer subagent fixes quality issues" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="re-review"];
|
||||
"Code quality reviewer subagent approves?" -> "Mark task complete in TodoWrite" [label="yes"];
|
||||
"Mark task complete in TodoWrite" -> "More tasks remain?";
|
||||
"More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"];
|
||||
"More tasks remain?" -> "Dispatch final code reviewer subagent for entire implementation" [label="no"];
|
||||
"Dispatch final code reviewer subagent for entire implementation" -> "Use superpowers:finishing-a-development-branch";
|
||||
}
|
||||
```
|
||||
|
||||
## Model Selection
|
||||
|
||||
Use the least powerful model that can handle each role to conserve cost and increase speed.
|
||||
|
||||
**Mechanical implementation tasks** (isolated functions, clear specs, 1-2 files): use a fast, cheap model. Most implementation tasks are mechanical when the plan is well-specified.
|
||||
|
||||
**Integration and judgment tasks** (multi-file coordination, pattern matching, debugging): use a standard model.
|
||||
|
||||
**Architecture, design, and review tasks**: use the most capable available model.
|
||||
|
||||
**Task complexity signals:**
|
||||
- Touches 1-2 files with a complete spec → cheap model
|
||||
- Touches multiple files with integration concerns → standard model
|
||||
- Requires design judgment or broad codebase understanding → most capable model
|
||||
|
||||
## Handling Implementer Status
|
||||
|
||||
Implementer subagents report one of four statuses. Handle each appropriately:
|
||||
|
||||
**DONE:** Proceed to spec compliance review.
|
||||
|
||||
**DONE_WITH_CONCERNS:** The implementer completed the work but flagged doubts. Read the concerns before proceeding. If the concerns are about correctness or scope, address them before review. If they're observations (e.g., "this file is getting large"), note them and proceed to review.
|
||||
|
||||
**NEEDS_CONTEXT:** The implementer needs information that wasn't provided. Provide the missing context and re-dispatch.
|
||||
|
||||
**BLOCKED:** The implementer cannot complete the task. Assess the blocker:
|
||||
1. If it's a context problem, provide more context and re-dispatch with the same model
|
||||
2. If the task requires more reasoning, re-dispatch with a more capable model
|
||||
3. If the task is too large, break it into smaller pieces
|
||||
4. If the plan itself is wrong, escalate to the human
|
||||
|
||||
**Never** ignore an escalation or force the same model to retry without changes. If the implementer said it's stuck, something needs to change.
|
||||
|
||||
## Prompt Templates
|
||||
|
||||
- `./implementer-prompt.md` - Dispatch implementer subagent
|
||||
- `./spec-reviewer-prompt.md` - Dispatch spec compliance reviewer subagent
|
||||
- `./code-quality-reviewer-prompt.md` - Dispatch code quality reviewer subagent
|
||||
|
||||
## Example Workflow
|
||||
|
||||
```
|
||||
You: I'm using Subagent-Driven Development to execute this plan.
|
||||
|
||||
[Read plan file once: docs/superpowers/plans/feature-plan.md]
|
||||
[Extract all 5 tasks with full text and context]
|
||||
[Create TodoWrite with all tasks]
|
||||
|
||||
Task 1: Hook installation script
|
||||
|
||||
[Get Task 1 text and context (already extracted)]
|
||||
[Dispatch implementation subagent with full task text + context]
|
||||
|
||||
Implementer: "Before I begin - should the hook be installed at user or system level?"
|
||||
|
||||
You: "User level (~/.config/superpowers/hooks/)"
|
||||
|
||||
Implementer: "Got it. Implementing now..."
|
||||
[Later] Implementer:
|
||||
- Implemented install-hook command
|
||||
- Added tests, 5/5 passing
|
||||
- Self-review: Found I missed --force flag, added it
|
||||
- Committed
|
||||
|
||||
[Dispatch spec compliance reviewer]
|
||||
Spec reviewer: ✅ Spec compliant - all requirements met, nothing extra
|
||||
|
||||
[Get git SHAs, dispatch code quality reviewer]
|
||||
Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved.
|
||||
|
||||
[Mark Task 1 complete]
|
||||
|
||||
Task 2: Recovery modes
|
||||
|
||||
[Get Task 2 text and context (already extracted)]
|
||||
[Dispatch implementation subagent with full task text + context]
|
||||
|
||||
Implementer: [No questions, proceeds]
|
||||
Implementer:
|
||||
- Added verify/repair modes
|
||||
- 8/8 tests passing
|
||||
- Self-review: All good
|
||||
- Committed
|
||||
|
||||
[Dispatch spec compliance reviewer]
|
||||
Spec reviewer: ❌ Issues:
|
||||
- Missing: Progress reporting (spec says "report every 100 items")
|
||||
- Extra: Added --json flag (not requested)
|
||||
|
||||
[Implementer fixes issues]
|
||||
Implementer: Removed --json flag, added progress reporting
|
||||
|
||||
[Spec reviewer reviews again]
|
||||
Spec reviewer: ✅ Spec compliant now
|
||||
|
||||
[Dispatch code quality reviewer]
|
||||
Code reviewer: Strengths: Solid. Issues (Important): Magic number (100)
|
||||
|
||||
[Implementer fixes]
|
||||
Implementer: Extracted PROGRESS_INTERVAL constant
|
||||
|
||||
[Code reviewer reviews again]
|
||||
Code reviewer: ✅ Approved
|
||||
|
||||
[Mark Task 2 complete]
|
||||
|
||||
...
|
||||
|
||||
[After all tasks]
|
||||
[Dispatch final code-reviewer]
|
||||
Final reviewer: All requirements met, ready to merge
|
||||
|
||||
Done!
|
||||
```
|
||||
|
||||
## Advantages
|
||||
|
||||
**vs. Manual execution:**
|
||||
- Subagents follow TDD naturally
|
||||
- Fresh context per task (no confusion)
|
||||
- Parallel-safe (subagents don't interfere)
|
||||
- Subagent can ask questions (before AND during work)
|
||||
|
||||
**vs. Executing Plans:**
|
||||
- Same session (no handoff)
|
||||
- Continuous progress (no waiting)
|
||||
- Review checkpoints automatic
|
||||
|
||||
**Efficiency gains:**
|
||||
- No file reading overhead (controller provides full text)
|
||||
- Controller curates exactly what context is needed
|
||||
- Subagent gets complete information upfront
|
||||
- Questions surfaced before work begins (not after)
|
||||
|
||||
**Quality gates:**
|
||||
- Self-review catches issues before handoff
|
||||
- Two-stage review: spec compliance, then code quality
|
||||
- Review loops ensure fixes actually work
|
||||
- Spec compliance prevents over/under-building
|
||||
- Code quality ensures implementation is well-built
|
||||
|
||||
**Cost:**
|
||||
- More subagent invocations (implementer + 2 reviewers per task)
|
||||
- Controller does more prep work (extracting all tasks upfront)
|
||||
- Review loops add iterations
|
||||
- But catches issues early (cheaper than debugging later)
|
||||
|
||||
## Red Flags
|
||||
|
||||
**Never:**
|
||||
- Start implementation on main/master branch without explicit user consent
|
||||
- Skip reviews (spec compliance OR code quality)
|
||||
- Proceed with unfixed issues
|
||||
- Dispatch multiple implementation subagents in parallel (conflicts)
|
||||
- Make subagent read plan file (provide full text instead)
|
||||
- Skip scene-setting context (subagent needs to understand where task fits)
|
||||
- Ignore subagent questions (answer before letting them proceed)
|
||||
- Accept "close enough" on spec compliance (spec reviewer found issues = not done)
|
||||
- Skip review loops (reviewer found issues = implementer fixes = review again)
|
||||
- Let implementer self-review replace actual review (both are needed)
|
||||
- **Start code quality review before spec compliance is ✅** (wrong order)
|
||||
- Move to next task while either review has open issues
|
||||
|
||||
**If subagent asks questions:**
|
||||
- Answer clearly and completely
|
||||
- Provide additional context if needed
|
||||
- Don't rush them into implementation
|
||||
|
||||
**If reviewer finds issues:**
|
||||
- Implementer (same subagent) fixes them
|
||||
- Reviewer reviews again
|
||||
- Repeat until approved
|
||||
- Don't skip the re-review
|
||||
|
||||
**If subagent fails task:**
|
||||
- Dispatch fix subagent with specific instructions
|
||||
- Don't try to fix manually (context pollution)
|
||||
|
||||
## Integration
|
||||
|
||||
**Required workflow skills:**
|
||||
- **superpowers:using-git-worktrees** - Ensures isolated workspace (creates one or verifies existing)
|
||||
- **superpowers:writing-plans** - Creates the plan this skill executes
|
||||
- **superpowers:requesting-code-review** - Code review template for reviewer subagents
|
||||
- **superpowers:finishing-a-development-branch** - Complete development after all tasks
|
||||
|
||||
**Subagents should use:**
|
||||
- **superpowers:test-driven-development** - Subagents follow TDD for each task
|
||||
|
||||
**Alternative workflow:**
|
||||
- **superpowers:executing-plans** - Use for parallel session instead of same-session execution
|
||||
@@ -0,0 +1,25 @@
|
||||
# Code Quality Reviewer Prompt Template
|
||||
|
||||
Use this template when dispatching a code quality reviewer subagent.
|
||||
|
||||
**Purpose:** Verify implementation is well-built (clean, tested, maintainable)
|
||||
|
||||
**Only dispatch after spec compliance review passes.**
|
||||
|
||||
```
|
||||
Agent tool (`subagent_type: "general-purpose"`):
|
||||
Use template at requesting-code-review/code-reviewer.md
|
||||
|
||||
DESCRIPTION: [task summary, from implementer's report]
|
||||
PLAN_OR_REQUIREMENTS: Task N from [plan-file]
|
||||
BASE_SHA: [commit before task]
|
||||
HEAD_SHA: [current commit]
|
||||
```
|
||||
|
||||
**In addition to standard code quality concerns, the reviewer should check:**
|
||||
- Does each file have one clear responsibility with a well-defined interface?
|
||||
- Are units decomposed so they can be understood and tested independently?
|
||||
- Is the implementation following the file structure from the plan?
|
||||
- Did this implementation create new files that are already large, or significantly grow existing files? (Don't flag pre-existing file sizes — focus on what this change contributed.)
|
||||
|
||||
**Code reviewer returns:** Strengths, Issues (Critical/Important/Minor), Assessment
|
||||
@@ -0,0 +1,113 @@
|
||||
# Implementer Subagent Prompt Template
|
||||
|
||||
Use this template when dispatching an implementer subagent.
|
||||
|
||||
```
|
||||
Agent tool (`subagent_type: "general-purpose"`):
|
||||
description: "Implement Task N: [task name]"
|
||||
prompt: |
|
||||
You are implementing Task N: [task name]
|
||||
|
||||
## Task Description
|
||||
|
||||
[FULL TEXT of task from plan - paste it here, don't make subagent read file]
|
||||
|
||||
## Context
|
||||
|
||||
[Scene-setting: where this fits, dependencies, architectural context]
|
||||
|
||||
## Before You Begin
|
||||
|
||||
If you have questions about:
|
||||
- The requirements or acceptance criteria
|
||||
- The approach or implementation strategy
|
||||
- Dependencies or assumptions
|
||||
- Anything unclear in the task description
|
||||
|
||||
**Ask them now.** Raise any concerns before starting work.
|
||||
|
||||
## Your Job
|
||||
|
||||
Once you're clear on requirements:
|
||||
1. Implement exactly what the task specifies
|
||||
2. Write tests (following TDD if task says to)
|
||||
3. Verify implementation works
|
||||
4. Commit your work
|
||||
5. Self-review (see below)
|
||||
6. Report back
|
||||
|
||||
Work from: [directory]
|
||||
|
||||
**While you work:** If you encounter something unexpected or unclear, **ask questions**.
|
||||
It's always OK to pause and clarify. Don't guess or make assumptions.
|
||||
|
||||
## Code Organization
|
||||
|
||||
You reason best about code you can hold in context at once, and your edits are more
|
||||
reliable when files are focused. Keep this in mind:
|
||||
- Follow the file structure defined in the plan
|
||||
- Each file should have one clear responsibility with a well-defined interface
|
||||
- If a file you're creating is growing beyond the plan's intent, stop and report
|
||||
it as DONE_WITH_CONCERNS — don't split files on your own without plan guidance
|
||||
- If an existing file you're modifying is already large or tangled, work carefully
|
||||
and note it as a concern in your report
|
||||
- In existing codebases, follow established patterns. Improve code you're touching
|
||||
the way a good developer would, but don't restructure things outside your task.
|
||||
|
||||
## When You're in Over Your Head
|
||||
|
||||
It is always OK to stop and say "this is too hard for me." Bad work is worse than
|
||||
no work. You will not be penalized for escalating.
|
||||
|
||||
**STOP and escalate when:**
|
||||
- The task requires architectural decisions with multiple valid approaches
|
||||
- You need to understand code beyond what was provided and can't find clarity
|
||||
- You feel uncertain about whether your approach is correct
|
||||
- The task involves restructuring existing code in ways the plan didn't anticipate
|
||||
- You've been reading file after file trying to understand the system without progress
|
||||
|
||||
**How to escalate:** Report back with status BLOCKED or NEEDS_CONTEXT. Describe
|
||||
specifically what you're stuck on, what you've tried, and what kind of help you need.
|
||||
The controller can provide more context, re-dispatch with a more capable model,
|
||||
or break the task into smaller pieces.
|
||||
|
||||
## Before Reporting Back: Self-Review
|
||||
|
||||
Review your work with fresh eyes. Ask yourself:
|
||||
|
||||
**Completeness:**
|
||||
- Did I fully implement everything in the spec?
|
||||
- Did I miss any requirements?
|
||||
- Are there edge cases I didn't handle?
|
||||
|
||||
**Quality:**
|
||||
- Is this my best work?
|
||||
- Are names clear and accurate (match what things do, not how they work)?
|
||||
- Is the code clean and maintainable?
|
||||
|
||||
**Discipline:**
|
||||
- Did I avoid overbuilding (YAGNI)?
|
||||
- Did I only build what was requested?
|
||||
- Did I follow existing patterns in the codebase?
|
||||
|
||||
**Testing:**
|
||||
- Do tests actually verify behavior (not just mock behavior)?
|
||||
- Did I follow TDD if required?
|
||||
- Are tests comprehensive?
|
||||
|
||||
If you find issues during self-review, fix them now before reporting.
|
||||
|
||||
## Report Format
|
||||
|
||||
When done, report:
|
||||
- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT
|
||||
- What you implemented (or what you attempted, if blocked)
|
||||
- What you tested and test results
|
||||
- Files changed
|
||||
- Self-review findings (if any)
|
||||
- Any issues or concerns
|
||||
|
||||
Use DONE_WITH_CONCERNS if you completed the work but have doubts about correctness.
|
||||
Use BLOCKED if you cannot complete the task. Use NEEDS_CONTEXT if you need
|
||||
information that wasn't provided. Never silently produce work you're unsure about.
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
# Spec Compliance Reviewer Prompt Template
|
||||
|
||||
Use this template when dispatching a spec compliance reviewer subagent.
|
||||
|
||||
**Purpose:** Verify implementer built what was requested (nothing more, nothing less)
|
||||
|
||||
```
|
||||
Agent tool (`subagent_type: "general-purpose"`):
|
||||
description: "Review spec compliance for Task N"
|
||||
prompt: |
|
||||
You are reviewing whether an implementation matches its specification.
|
||||
|
||||
## What Was Requested
|
||||
|
||||
[FULL TEXT of task requirements]
|
||||
|
||||
## What Implementer Claims They Built
|
||||
|
||||
[From implementer's report]
|
||||
|
||||
## CRITICAL: Do Not Trust the Report
|
||||
|
||||
The implementer finished suspiciously quickly. Their report may be incomplete,
|
||||
inaccurate, or optimistic. You MUST verify everything independently.
|
||||
|
||||
**DO NOT:**
|
||||
- Take their word for what they implemented
|
||||
- Trust their claims about completeness
|
||||
- Accept their interpretation of requirements
|
||||
|
||||
**DO:**
|
||||
- Read the actual code they wrote
|
||||
- Compare actual implementation to requirements line by line
|
||||
- Check for missing pieces they claimed to implement
|
||||
- Look for extra features they didn't mention
|
||||
|
||||
## Your Job
|
||||
|
||||
Read the implementation code and verify:
|
||||
|
||||
**Missing requirements:**
|
||||
- Did they implement everything that was requested?
|
||||
- Are there requirements they skipped or missed?
|
||||
- Did they claim something works but didn't actually implement it?
|
||||
|
||||
**Extra/unneeded work:**
|
||||
- Did they build things that weren't requested?
|
||||
- Did they over-engineer or add unnecessary features?
|
||||
- Did they add "nice to haves" that weren't in spec?
|
||||
|
||||
**Misunderstandings:**
|
||||
- Did they interpret requirements differently than intended?
|
||||
- Did they solve the wrong problem?
|
||||
- Did they implement the right feature but wrong way?
|
||||
|
||||
**Verify by reading code, not by trusting report.**
|
||||
|
||||
Report:
|
||||
- ✅ Spec compliant (if everything matches after code inspection)
|
||||
- ❌ Issues found: [list specifically what's missing or extra, with file:line references]
|
||||
```
|
||||
@@ -0,0 +1,218 @@
|
||||
---
|
||||
name: using-git-worktrees
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Isolating work with git worktrees"
|
||||
use_when: "Parallel/isolated work in a worktree"
|
||||
description: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback
|
||||
---
|
||||
|
||||
# Using Git Worktrees
|
||||
|
||||
## Overview
|
||||
|
||||
Ensure work happens in an isolated workspace. Prefer your platform's native worktree tools. Fall back to manual git worktrees only when no native tool is available.
|
||||
|
||||
**Core principle:** Detect existing isolation first. Then use native tools. Then fall back to git. Never fight the harness.
|
||||
|
||||
**Announce at start:** "I'm using the using-git-worktrees skill to set up an isolated workspace."
|
||||
|
||||
## Step 0: Detect Existing Isolation
|
||||
|
||||
**Before creating anything, check if you are already in an isolated workspace.**
|
||||
|
||||
```bash
|
||||
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
|
||||
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
|
||||
BRANCH=$(git branch --show-current)
|
||||
```
|
||||
|
||||
**Submodule guard:** `GIT_DIR != GIT_COMMON` is also true inside git submodules. Before concluding "already in a worktree," verify you are not in a submodule:
|
||||
|
||||
```bash
|
||||
# If this returns a path, you're in a submodule, not a worktree — treat as normal repo
|
||||
git rev-parse --show-superproject-working-tree 2>/dev/null
|
||||
```
|
||||
|
||||
**If `GIT_DIR != GIT_COMMON` (and not a submodule):** You are already in a linked worktree. Skip to Step 3 (Project Setup). Do NOT create another worktree.
|
||||
|
||||
Report with branch state:
|
||||
- On a branch: "Already in isolated workspace at `<path>` on branch `<name>`."
|
||||
- Detached HEAD: "Already in isolated workspace at `<path>` (detached HEAD, externally managed). Branch creation needed at finish time."
|
||||
|
||||
**If `GIT_DIR == GIT_COMMON` (or in a submodule):** You are in a normal repo checkout.
|
||||
|
||||
Has the user already indicated their worktree preference in your instructions? If not, ask for consent before creating a worktree:
|
||||
|
||||
> "Would you like me to set up an isolated worktree? It protects your current branch from changes."
|
||||
|
||||
Honor any existing declared preference without asking. If the user declines consent, work in place and skip to Step 3.
|
||||
|
||||
## Step 1: Create Isolated Workspace
|
||||
|
||||
**You have two mechanisms. Try them in this order.**
|
||||
|
||||
### 1a. Native Worktree Tools (preferred)
|
||||
|
||||
The user has asked for an isolated workspace (Step 0 consent). Do you already have a way to create a worktree? It might be a tool with a name like `EnterWorktree`, `WorktreeCreate`, a `/worktree` command, or a `--worktree` flag. If you do, use it and skip to Step 3.
|
||||
|
||||
Native tools handle directory placement, branch creation, and cleanup automatically. Using `git worktree add` when you have a native tool creates phantom state your harness can't see or manage.
|
||||
|
||||
Only proceed to Step 1b if you have no native worktree tool available.
|
||||
|
||||
### 1b. Git Worktree Fallback
|
||||
|
||||
**Only use this if Step 1a does not apply** — you have no native worktree tool available. Create a worktree manually using git.
|
||||
|
||||
#### Directory Selection
|
||||
|
||||
Follow this priority order. Explicit user preference always beats observed filesystem state.
|
||||
|
||||
1. **Check your instructions for a declared worktree directory preference.** If the user has already specified one, use it without asking.
|
||||
|
||||
2. **Check for an existing project-local worktree directory:**
|
||||
```bash
|
||||
ls -d .worktrees 2>/dev/null # Preferred (hidden)
|
||||
ls -d worktrees 2>/dev/null # Alternative
|
||||
```
|
||||
If found, use it. If both exist, `.worktrees` wins.
|
||||
|
||||
3. **Check for an existing global directory:**
|
||||
```bash
|
||||
project=$(basename "$(git rev-parse --show-toplevel)")
|
||||
ls -d ~/.config/superpowers/worktrees/$project 2>/dev/null
|
||||
```
|
||||
If found, use it (backward compatibility with legacy global path).
|
||||
|
||||
4. **If there is no other guidance available**, default to `.worktrees/` at the project root.
|
||||
|
||||
#### Safety Verification (project-local directories only)
|
||||
|
||||
**MUST verify directory is ignored before creating worktree:**
|
||||
|
||||
```bash
|
||||
git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
|
||||
```
|
||||
|
||||
**If NOT ignored:** Add to .gitignore, commit the change, then proceed.
|
||||
|
||||
**Why critical:** Prevents accidentally committing worktree contents to repository.
|
||||
|
||||
Global directories (`~/.config/superpowers/worktrees/`) need no verification.
|
||||
|
||||
#### Create the Worktree
|
||||
|
||||
```bash
|
||||
project=$(basename "$(git rev-parse --show-toplevel)")
|
||||
|
||||
# Determine path based on chosen location
|
||||
# For project-local: path="$LOCATION/$BRANCH_NAME"
|
||||
# For global: path="~/.config/superpowers/worktrees/$project/$BRANCH_NAME"
|
||||
|
||||
git worktree add "$path" -b "$BRANCH_NAME"
|
||||
cd "$path"
|
||||
```
|
||||
|
||||
**Sandbox fallback:** If `git worktree add` fails with a permission error (sandbox denial), tell the user the sandbox blocked worktree creation and you're working in the current directory instead. Then run setup and baseline tests in place.
|
||||
|
||||
## Step 3: Project Setup
|
||||
|
||||
Auto-detect and run appropriate setup:
|
||||
|
||||
```bash
|
||||
# Node.js
|
||||
if [ -f package.json ]; then npm install; fi
|
||||
|
||||
# Rust
|
||||
if [ -f Cargo.toml ]; then cargo build; fi
|
||||
|
||||
# Python
|
||||
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
||||
if [ -f pyproject.toml ]; then poetry install; fi
|
||||
|
||||
# Go
|
||||
if [ -f go.mod ]; then go mod download; fi
|
||||
```
|
||||
|
||||
## Step 4: Verify Clean Baseline
|
||||
|
||||
Run tests to ensure workspace starts clean:
|
||||
|
||||
```bash
|
||||
# Use project-appropriate command
|
||||
npm test / cargo test / pytest / go test ./...
|
||||
```
|
||||
|
||||
**If tests fail:** Report failures, ask whether to proceed or investigate.
|
||||
|
||||
**If tests pass:** Report ready.
|
||||
|
||||
### Report
|
||||
|
||||
```
|
||||
Worktree ready at <full-path>
|
||||
Tests passing (<N> tests, 0 failures)
|
||||
Ready to implement <feature-name>
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Situation | Action |
|
||||
|-----------|--------|
|
||||
| Already in linked worktree | Skip creation (Step 0) |
|
||||
| In a submodule | Treat as normal repo (Step 0 guard) |
|
||||
| Native worktree tool available | Use it (Step 1a) |
|
||||
| No native tool | Git worktree fallback (Step 1b) |
|
||||
| `.worktrees/` exists | Use it (verify ignored) |
|
||||
| `worktrees/` exists | Use it (verify ignored) |
|
||||
| Both exist | Use `.worktrees/` |
|
||||
| Neither exists | Check instruction file, then default `.worktrees/` |
|
||||
| Global path exists | Use it (backward compat) |
|
||||
| Directory not ignored | Add to .gitignore + commit |
|
||||
| Permission error on create | Sandbox fallback, work in place |
|
||||
| Tests fail during baseline | Report failures + ask |
|
||||
| No package.json/Cargo.toml | Skip dependency install |
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
### Fighting the harness
|
||||
|
||||
- **Problem:** Using `git worktree add` when the platform already provides isolation
|
||||
- **Fix:** Step 0 detects existing isolation. Step 1a defers to native tools.
|
||||
|
||||
### Skipping detection
|
||||
|
||||
- **Problem:** Creating a nested worktree inside an existing one
|
||||
- **Fix:** Always run Step 0 before creating anything
|
||||
|
||||
### Skipping ignore verification
|
||||
|
||||
- **Problem:** Worktree contents get tracked, pollute git status
|
||||
- **Fix:** Always use `git check-ignore` before creating project-local worktree
|
||||
|
||||
### Assuming directory location
|
||||
|
||||
- **Problem:** Creates inconsistency, violates project conventions
|
||||
- **Fix:** Follow priority: existing > global legacy > instruction file > default
|
||||
|
||||
### Proceeding with failing tests
|
||||
|
||||
- **Problem:** Can't distinguish new bugs from pre-existing issues
|
||||
- **Fix:** Report failures, get explicit permission to proceed
|
||||
|
||||
## Red Flags
|
||||
|
||||
**Never:**
|
||||
- Create a worktree when Step 0 detects existing isolation
|
||||
- Use `git worktree add` when you have a native worktree tool (e.g., `EnterWorktree`). This is the #1 mistake — if you have it, use it.
|
||||
- Skip Step 1a by jumping straight to Step 1b's git commands
|
||||
- Create worktree without verifying it's ignored (project-local)
|
||||
- Skip baseline test verification
|
||||
- Proceed with failing tests without asking
|
||||
|
||||
**Always:**
|
||||
- Run Step 0 detection first
|
||||
- Prefer native tools over git fallback
|
||||
- Follow directory priority: existing > global legacy > instruction file > default
|
||||
- Verify directory is ignored for project-local
|
||||
- Auto-detect and run project setup
|
||||
- Verify clean test baseline
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
name: using-superpowers
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Meta: orienting in the superpowers set"
|
||||
use_when: "Learning how to use the superpowers skills"
|
||||
description: Use when starting any conversation - establishes how to find and use skills, requiring Skill tool invocation before ANY response including clarifying questions
|
||||
---
|
||||
|
||||
<SUBAGENT-STOP>
|
||||
If you were dispatched as a subagent to execute a specific task, skip this skill.
|
||||
</SUBAGENT-STOP>
|
||||
|
||||
<EXTREMELY-IMPORTANT>
|
||||
If you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST invoke the skill.
|
||||
|
||||
IF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT.
|
||||
|
||||
This is not negotiable. This is not optional. You cannot rationalize your way out of this.
|
||||
</EXTREMELY-IMPORTANT>
|
||||
|
||||
## Instruction Priority
|
||||
|
||||
Superpowers skills override default system prompt behavior, but **user instructions always take precedence**:
|
||||
|
||||
1. **User's explicit instructions** (CLAUDE.md, GEMINI.md, AGENTS.md, direct requests) — highest priority
|
||||
2. **Superpowers skills** — override default system behavior where they conflict
|
||||
3. **Default system prompt** — lowest priority
|
||||
|
||||
If CLAUDE.md, GEMINI.md, or AGENTS.md says "don't use TDD" and a skill says "always use TDD," follow the user's instructions. The user is in control.
|
||||
|
||||
## How to Access Skills
|
||||
|
||||
**In Claude Code:** Use the `Skill` tool. When you invoke a skill, its content is loaded and presented to you—follow it directly. Never use the Read tool on skill files.
|
||||
|
||||
**In Copilot CLI:** Use the `skill` tool. Skills are auto-discovered from installed plugins. The `skill` tool works the same as Claude Code's `Skill` tool.
|
||||
|
||||
**In Gemini CLI:** Skills activate via the `activate_skill` tool. Gemini loads skill metadata at session start and activates the full content on demand.
|
||||
|
||||
**In other environments:** Check your platform's documentation for how skills are loaded.
|
||||
|
||||
## Platform Adaptation
|
||||
|
||||
Skills use Claude Code tool names. Non-CC platforms: see `references/copilot-tools.md` (Copilot CLI), `references/codex-tools.md` (Codex) for tool equivalents. Gemini CLI users get the tool mapping loaded automatically via GEMINI.md.
|
||||
|
||||
# Using Skills
|
||||
|
||||
## The Rule
|
||||
|
||||
**Invoke relevant or requested skills BEFORE any response or action.** Even a 1% chance a skill might apply means that you should invoke the skill to check. If an invoked skill turns out to be wrong for the situation, you don't need to use it.
|
||||
|
||||
```dot
|
||||
digraph skill_flow {
|
||||
"User message received" [shape=doublecircle];
|
||||
"About to EnterPlanMode?" [shape=doublecircle];
|
||||
"Already brainstormed?" [shape=diamond];
|
||||
"Invoke brainstorming skill" [shape=box];
|
||||
"Might any skill apply?" [shape=diamond];
|
||||
"Invoke Skill tool" [shape=box];
|
||||
"Announce: 'Using [skill] to [purpose]'" [shape=box];
|
||||
"Has checklist?" [shape=diamond];
|
||||
"Create TodoWrite todo per item" [shape=box];
|
||||
"Follow skill exactly" [shape=box];
|
||||
"Respond (including clarifications)" [shape=doublecircle];
|
||||
|
||||
"About to EnterPlanMode?" -> "Already brainstormed?";
|
||||
"Already brainstormed?" -> "Invoke brainstorming skill" [label="no"];
|
||||
"Already brainstormed?" -> "Might any skill apply?" [label="yes"];
|
||||
"Invoke brainstorming skill" -> "Might any skill apply?";
|
||||
|
||||
"User message received" -> "Might any skill apply?";
|
||||
"Might any skill apply?" -> "Invoke Skill tool" [label="yes, even 1%"];
|
||||
"Might any skill apply?" -> "Respond (including clarifications)" [label="definitely not"];
|
||||
"Invoke Skill tool" -> "Announce: 'Using [skill] to [purpose]'";
|
||||
"Announce: 'Using [skill] to [purpose]'" -> "Has checklist?";
|
||||
"Has checklist?" -> "Create TodoWrite todo per item" [label="yes"];
|
||||
"Has checklist?" -> "Follow skill exactly" [label="no"];
|
||||
"Create TodoWrite todo per item" -> "Follow skill exactly";
|
||||
}
|
||||
```
|
||||
|
||||
## Red Flags
|
||||
|
||||
These thoughts mean STOP—you're rationalizing:
|
||||
|
||||
| Thought | Reality |
|
||||
|---------|---------|
|
||||
| "This is just a simple question" | Questions are tasks. Check for skills. |
|
||||
| "I need more context first" | Skill check comes BEFORE clarifying questions. |
|
||||
| "Let me explore the codebase first" | Skills tell you HOW to explore. Check first. |
|
||||
| "I can check git/files quickly" | Files lack conversation context. Check for skills. |
|
||||
| "Let me gather information first" | Skills tell you HOW to gather information. |
|
||||
| "This doesn't need a formal skill" | If a skill exists, use it. |
|
||||
| "I remember this skill" | Skills evolve. Read current version. |
|
||||
| "This doesn't count as a task" | Action = task. Check for skills. |
|
||||
| "The skill is overkill" | Simple things become complex. Use it. |
|
||||
| "I'll just do this one thing first" | Check BEFORE doing anything. |
|
||||
| "This feels productive" | Undisciplined action wastes time. Skills prevent this. |
|
||||
| "I know what that means" | Knowing the concept ≠ using the skill. Invoke it. |
|
||||
|
||||
## Skill Priority
|
||||
|
||||
When multiple skills could apply, use this order:
|
||||
|
||||
1. **Process skills first** (brainstorming, debugging) - these determine HOW to approach the task
|
||||
2. **Implementation skills second** (frontend-design, mcp-builder) - these guide execution
|
||||
|
||||
"Let's build X" → brainstorming first, then implementation skills.
|
||||
"Fix this bug" → debugging first, then domain-specific skills.
|
||||
|
||||
## Skill Types
|
||||
|
||||
**Rigid** (TDD, debugging): Follow exactly. Don't adapt away discipline.
|
||||
|
||||
**Flexible** (patterns): Adapt principles to context.
|
||||
|
||||
The skill itself tells you which.
|
||||
|
||||
## User Instructions
|
||||
|
||||
Instructions say WHAT, not HOW. "Add X" or "Fix Y" doesn't mean skip workflows.
|
||||
@@ -0,0 +1,59 @@
|
||||
# Codex Tool Mapping
|
||||
|
||||
Skills use Claude Code tool names. When you encounter these in a skill, use your platform equivalent:
|
||||
|
||||
| Skill references | Codex equivalent |
|
||||
|-----------------|------------------|
|
||||
| `Task` tool (dispatch subagent) | `spawn_agent` (see [Subagent dispatch requires multi-agent support](#subagent-dispatch-requires-multi-agent-support)) |
|
||||
| Multiple `Task` calls (parallel) | Multiple `spawn_agent` calls |
|
||||
| Task returns result | `wait_agent` |
|
||||
| Task completes automatically | `close_agent` to free slot |
|
||||
| `TodoWrite` (task tracking) | `update_plan` |
|
||||
| `Skill` tool (invoke a skill) | Skills load natively — just follow the instructions |
|
||||
| `Read`, `Write`, `Edit` (files) | Use your native file tools |
|
||||
| `Bash` (run commands) | Use your native shell tools |
|
||||
|
||||
## Subagent dispatch requires multi-agent support
|
||||
|
||||
Add to your Codex config (`~/.codex/config.toml`):
|
||||
|
||||
```toml
|
||||
[features]
|
||||
multi_agent = true
|
||||
```
|
||||
|
||||
This enables `spawn_agent`, `wait_agent`, and `close_agent` for skills like `dispatching-parallel-agents` and `subagent-driven-development`.
|
||||
|
||||
Legacy note: Codex builds before `rust-v0.115.0` exposed spawned-agent
|
||||
waiting as `wait`. Current Codex uses `wait_agent` for spawned agents. The
|
||||
`wait` name now belongs to code-mode `exec/wait`, which resumes a yielded exec
|
||||
cell by `cell_id`; it is not the spawned-agent result tool.
|
||||
|
||||
## Environment Detection
|
||||
|
||||
Skills that create worktrees or finish branches should detect their
|
||||
environment with read-only git commands before proceeding:
|
||||
|
||||
```bash
|
||||
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
|
||||
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
|
||||
BRANCH=$(git branch --show-current)
|
||||
```
|
||||
|
||||
- `GIT_DIR != GIT_COMMON` → already in a linked worktree (skip creation)
|
||||
- `BRANCH` empty → detached HEAD (cannot branch/push/PR from sandbox)
|
||||
|
||||
See `using-git-worktrees` Step 0 and `finishing-a-development-branch`
|
||||
Step 1 for how each skill uses these signals.
|
||||
|
||||
## Codex App Finishing
|
||||
|
||||
When the sandbox blocks branch/push operations (detached HEAD in an
|
||||
externally managed worktree), the agent commits all work and informs
|
||||
the user to use the App's native controls:
|
||||
|
||||
- **"Create branch"** — names the branch, then commit/push/PR via App UI
|
||||
- **"Hand off to local"** — transfers work to the user's local checkout
|
||||
|
||||
The agent can still run tests, stage files, and output suggested branch
|
||||
names, commit messages, and PR descriptions for the user to copy.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Copilot CLI Tool Mapping
|
||||
|
||||
Skills use Claude Code tool names. When you encounter these in a skill, use your platform equivalent:
|
||||
|
||||
| Skill references | Copilot CLI equivalent |
|
||||
|-----------------|----------------------|
|
||||
| `Read` (file reading) | `view` |
|
||||
| `Write` (file creation) | `create` |
|
||||
| `Edit` (file editing) | `edit` |
|
||||
| `Bash` (run commands) | `bash` |
|
||||
| `Grep` (search file content) | `grep` |
|
||||
| `Glob` (search files by name) | `glob` |
|
||||
| `Skill` tool (invoke a skill) | `skill` |
|
||||
| `WebFetch` | `web_fetch` |
|
||||
| `Task` tool (dispatch subagent) | `task` with `agent_type: "general-purpose"` or `"explore"` |
|
||||
| Multiple `Task` calls (parallel) | Multiple `task` calls |
|
||||
| Task status/output | `read_agent`, `list_agents` |
|
||||
| `TodoWrite` (task tracking) | `sql` with built-in `todos` table |
|
||||
| `WebSearch` | No equivalent — use `web_fetch` with a search engine URL |
|
||||
| `EnterPlanMode` / `ExitPlanMode` | No equivalent — stay in the main session |
|
||||
|
||||
## Async shell sessions
|
||||
|
||||
Copilot CLI supports persistent async shell sessions, which have no direct Claude Code equivalent:
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| `bash` with `async: true` | Start a long-running command in the background |
|
||||
| `write_bash` | Send input to a running async session |
|
||||
| `read_bash` | Read output from an async session |
|
||||
| `stop_bash` | Terminate an async session |
|
||||
| `list_bash` | List all active shell sessions |
|
||||
|
||||
## Additional Copilot CLI tools
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| `store_memory` | Persist facts about the codebase for future sessions |
|
||||
| `report_intent` | Update the UI status line with current intent |
|
||||
| `sql` | Query the session's SQLite database (todos, metadata) |
|
||||
| `fetch_copilot_cli_documentation` | Look up Copilot CLI documentation |
|
||||
| GitHub MCP tools (`github-mcp-server-*`) | Native GitHub API access (issues, PRs, code search) |
|
||||
@@ -0,0 +1,51 @@
|
||||
# Gemini CLI Tool Mapping
|
||||
|
||||
Skills use Claude Code tool names. When you encounter these in a skill, use your platform equivalent:
|
||||
|
||||
| Skill references | Gemini CLI equivalent |
|
||||
|-----------------|----------------------|
|
||||
| `Read` (file reading) | `read_file` |
|
||||
| `Write` (file creation) | `write_file` |
|
||||
| `Edit` (file editing) | `replace` |
|
||||
| `Bash` (run commands) | `run_shell_command` |
|
||||
| `Grep` (search file content) | `grep_search` |
|
||||
| `Glob` (search files by name) | `glob` |
|
||||
| `TodoWrite` (task tracking) | `write_todos` |
|
||||
| `Skill` tool (invoke a skill) | `activate_skill` |
|
||||
| `WebSearch` | `google_web_search` |
|
||||
| `WebFetch` | `web_fetch` |
|
||||
| `Task` tool (dispatch subagent) | `@agent-name` (see [Subagent support](#subagent-support)) |
|
||||
|
||||
## Subagent support
|
||||
|
||||
Gemini CLI supports subagents natively via the `@` syntax. Use the built-in `@generalist` agent to dispatch any task — it has access to all tools and follows the prompt you provide.
|
||||
|
||||
When a skill says to dispatch a named agent type, use `@generalist` with the full prompt from the skill's prompt template:
|
||||
|
||||
| Skill instruction | Gemini CLI equivalent |
|
||||
|-------------------|----------------------|
|
||||
| `Agent tool (superpowers:implementer)` | `@generalist` with the filled `implementer-prompt.md` template |
|
||||
| `Agent tool (superpowers:spec-reviewer)` | `@generalist` with the filled `spec-reviewer-prompt.md` template |
|
||||
| `Agent tool (superpowers:code-reviewer)` | `@code-reviewer` (bundled agent) or `@generalist` with the filled review prompt |
|
||||
| `Agent tool (superpowers:code-quality-reviewer)` | `@generalist` with the filled `code-quality-reviewer-prompt.md` template |
|
||||
| `Agent tool (general-purpose)` with inline prompt | `@generalist` with your inline prompt |
|
||||
|
||||
### Prompt filling
|
||||
|
||||
Skills provide prompt templates with placeholders like `{WHAT_WAS_IMPLEMENTED}` or `[FULL TEXT of task]`. Fill all placeholders and pass the complete prompt as the message to `@generalist`. The prompt template itself contains the agent's role, review criteria, and expected output format — `@generalist` will follow it.
|
||||
|
||||
### Parallel dispatch
|
||||
|
||||
Gemini CLI supports parallel subagent dispatch. When a skill asks you to dispatch multiple independent subagent tasks in parallel, request all of those `@generalist` or named subagent tasks together in the same prompt. Keep dependent tasks sequential, but do not serialize independent subagent tasks just to preserve a simpler history.
|
||||
|
||||
## Additional Gemini CLI tools
|
||||
|
||||
These tools are available in Gemini CLI but have no Claude Code equivalent:
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| `list_directory` | List files and subdirectories |
|
||||
| `save_memory` | Persist facts to GEMINI.md across sessions |
|
||||
| `ask_user` | Request structured input from the user |
|
||||
| `tracker_create_task` | Rich task management (create, update, list, visualize) |
|
||||
| `enter_plan_mode` / `exit_plan_mode` | Switch to read-only research mode before making changes |
|
||||
@@ -0,0 +1,142 @@
|
||||
---
|
||||
name: verification-before-completion
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Verify behavior before claiming done"
|
||||
use_when: "Before marking any task complete"
|
||||
description: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always
|
||||
---
|
||||
|
||||
# Verification Before Completion
|
||||
|
||||
## Overview
|
||||
|
||||
Claiming work is complete without verification is dishonesty, not efficiency.
|
||||
|
||||
**Core principle:** Evidence before claims, always.
|
||||
|
||||
**Violating the letter of this rule is violating the spirit of this rule.**
|
||||
|
||||
## The Iron Law
|
||||
|
||||
```
|
||||
NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE
|
||||
```
|
||||
|
||||
If you haven't run the verification command in this message, you cannot claim it passes.
|
||||
|
||||
## The Gate Function
|
||||
|
||||
```
|
||||
BEFORE claiming any status or expressing satisfaction:
|
||||
|
||||
1. IDENTIFY: What command proves this claim?
|
||||
2. RUN: Execute the FULL command (fresh, complete)
|
||||
3. READ: Full output, check exit code, count failures
|
||||
4. VERIFY: Does output confirm the claim?
|
||||
- If NO: State actual status with evidence
|
||||
- If YES: State claim WITH evidence
|
||||
5. ONLY THEN: Make the claim
|
||||
|
||||
Skip any step = lying, not verifying
|
||||
```
|
||||
|
||||
## Common Failures
|
||||
|
||||
| Claim | Requires | Not Sufficient |
|
||||
|-------|----------|----------------|
|
||||
| Tests pass | Test command output: 0 failures | Previous run, "should pass" |
|
||||
| Linter clean | Linter output: 0 errors | Partial check, extrapolation |
|
||||
| Build succeeds | Build command: exit 0 | Linter passing, logs look good |
|
||||
| Bug fixed | Test original symptom: passes | Code changed, assumed fixed |
|
||||
| Regression test works | Red-green cycle verified | Test passes once |
|
||||
| Agent completed | VCS diff shows changes | Agent reports "success" |
|
||||
| Requirements met | Line-by-line checklist | Tests passing |
|
||||
|
||||
## Red Flags - STOP
|
||||
|
||||
- Using "should", "probably", "seems to"
|
||||
- Expressing satisfaction before verification ("Great!", "Perfect!", "Done!", etc.)
|
||||
- About to commit/push/PR without verification
|
||||
- Trusting agent success reports
|
||||
- Relying on partial verification
|
||||
- Thinking "just this once"
|
||||
- Tired and wanting work over
|
||||
- **ANY wording implying success without having run verification**
|
||||
|
||||
## Rationalization Prevention
|
||||
|
||||
| Excuse | Reality |
|
||||
|--------|---------|
|
||||
| "Should work now" | RUN the verification |
|
||||
| "I'm confident" | Confidence ≠ evidence |
|
||||
| "Just this once" | No exceptions |
|
||||
| "Linter passed" | Linter ≠ compiler |
|
||||
| "Agent said success" | Verify independently |
|
||||
| "I'm tired" | Exhaustion ≠ excuse |
|
||||
| "Partial check is enough" | Partial proves nothing |
|
||||
| "Different words so rule doesn't apply" | Spirit over letter |
|
||||
|
||||
## Key Patterns
|
||||
|
||||
**Tests:**
|
||||
```
|
||||
✅ [Run test command] [See: 34/34 pass] "All tests pass"
|
||||
❌ "Should pass now" / "Looks correct"
|
||||
```
|
||||
|
||||
**Regression tests (TDD Red-Green):**
|
||||
```
|
||||
✅ Write → Run (pass) → Revert fix → Run (MUST FAIL) → Restore → Run (pass)
|
||||
❌ "I've written a regression test" (without red-green verification)
|
||||
```
|
||||
|
||||
**Build:**
|
||||
```
|
||||
✅ [Run build] [See: exit 0] "Build passes"
|
||||
❌ "Linter passed" (linter doesn't check compilation)
|
||||
```
|
||||
|
||||
**Requirements:**
|
||||
```
|
||||
✅ Re-read plan → Create checklist → Verify each → Report gaps or completion
|
||||
❌ "Tests pass, phase complete"
|
||||
```
|
||||
|
||||
**Agent delegation:**
|
||||
```
|
||||
✅ Agent reports success → Check VCS diff → Verify changes → Report actual state
|
||||
❌ Trust agent report
|
||||
```
|
||||
|
||||
## Why This Matters
|
||||
|
||||
From 24 failure memories:
|
||||
- the operator said "I don't believe you" - trust broken
|
||||
- Undefined functions shipped - would crash
|
||||
- Missing requirements shipped - incomplete features
|
||||
- Time wasted on false completion → redirect → rework
|
||||
- Violates: "Honesty is a core value. If you lie, you'll be replaced."
|
||||
|
||||
## When To Apply
|
||||
|
||||
**ALWAYS before:**
|
||||
- ANY variation of success/completion claims
|
||||
- ANY expression of satisfaction
|
||||
- ANY positive statement about work state
|
||||
- Committing, PR creation, task completion
|
||||
- Moving to next task
|
||||
- Delegating to agents
|
||||
|
||||
**Rule applies to:**
|
||||
- Exact phrases
|
||||
- Paraphrases and synonyms
|
||||
- Implications of success
|
||||
- ANY communication suggesting completion/correctness
|
||||
|
||||
## The Bottom Line
|
||||
|
||||
**No shortcuts for verification.**
|
||||
|
||||
Run the command. Read the output. THEN claim the result.
|
||||
|
||||
This is non-negotiable.
|
||||
@@ -0,0 +1,155 @@
|
||||
---
|
||||
name: writing-plans
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Writing implementation plans"
|
||||
use_when: "Planning substantial work before coding"
|
||||
description: Use when you have a spec or requirements for a multi-step task, before touching code
|
||||
---
|
||||
|
||||
# Writing Plans
|
||||
|
||||
## Overview
|
||||
|
||||
Write comprehensive implementation plans assuming the engineer has zero context for our codebase and questionable taste. Document everything they need to know: which files to touch for each task, code, testing, docs they might need to check, how to test it. Give them the whole plan as bite-sized tasks. DRY. YAGNI. TDD. Frequent commits.
|
||||
|
||||
Assume they are a skilled developer, but know almost nothing about our toolset or problem domain. Assume they don't know good test design very well.
|
||||
|
||||
**Announce at start:** "I'm using the writing-plans skill to create the implementation plan."
|
||||
|
||||
**Context:** If working in an isolated worktree, it should have been created via the `superpowers:using-git-worktrees` skill at execution time.
|
||||
|
||||
**Save plans to:** `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`
|
||||
- (User preferences for plan location override this default)
|
||||
|
||||
## Scope Check
|
||||
|
||||
If the spec covers multiple independent subsystems, it should have been broken into sub-project specs during brainstorming. If it wasn't, suggest breaking this into separate plans — one per subsystem. Each plan should produce working, testable software on its own.
|
||||
|
||||
## File Structure
|
||||
|
||||
Before defining tasks, map out which files will be created or modified and what each one is responsible for. This is where decomposition decisions get locked in.
|
||||
|
||||
- Design units with clear boundaries and well-defined interfaces. Each file should have one clear responsibility.
|
||||
- You reason best about code you can hold in context at once, and your edits are more reliable when files are focused. Prefer smaller, focused files over large ones that do too much.
|
||||
- Files that change together should live together. Split by responsibility, not by technical layer.
|
||||
- In existing codebases, follow established patterns. If the codebase uses large files, don't unilaterally restructure - but if a file you're modifying has grown unwieldy, including a split in the plan is reasonable.
|
||||
|
||||
This structure informs the task decomposition. Each task should produce self-contained changes that make sense independently.
|
||||
|
||||
## Bite-Sized Task Granularity
|
||||
|
||||
**Each step is one action (2-5 minutes):**
|
||||
- "Write the failing test" - step
|
||||
- "Run it to make sure it fails" - step
|
||||
- "Implement the minimal code to make the test pass" - step
|
||||
- "Run the tests and make sure they pass" - step
|
||||
- "Commit" - step
|
||||
|
||||
## Plan Document Header
|
||||
|
||||
**Every plan MUST start with this header:**
|
||||
|
||||
```markdown
|
||||
# [Feature Name] Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** [One sentence describing what this builds]
|
||||
|
||||
**Architecture:** [2-3 sentences about approach]
|
||||
|
||||
**Tech Stack:** [Key technologies/libraries]
|
||||
|
||||
---
|
||||
```
|
||||
|
||||
## Task Structure
|
||||
|
||||
````markdown
|
||||
### Task N: [Component Name]
|
||||
|
||||
**Files:**
|
||||
- Create: `exact/path/to/file.py`
|
||||
- Modify: `exact/path/to/existing.py:123-145`
|
||||
- Test: `tests/exact/path/to/test.py`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
def test_specific_behavior():
|
||||
result = function(input)
|
||||
assert result == expected
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `pytest tests/path/test.py::test_name -v`
|
||||
Expected: FAIL with "function not defined"
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
```python
|
||||
def function(input):
|
||||
return expected
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `pytest tests/path/test.py::test_name -v`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/path/test.py src/path/file.py
|
||||
git commit -m "feat: add specific feature"
|
||||
```
|
||||
````
|
||||
|
||||
## No Placeholders
|
||||
|
||||
Every step must contain the actual content an engineer needs. These are **plan failures** — never write them:
|
||||
- "TBD", "TODO", "implement later", "fill in details"
|
||||
- "Add appropriate error handling" / "add validation" / "handle edge cases"
|
||||
- "Write tests for the above" (without actual test code)
|
||||
- "Similar to Task N" (repeat the code — the engineer may be reading tasks out of order)
|
||||
- Steps that describe what to do without showing how (code blocks required for code steps)
|
||||
- References to types, functions, or methods not defined in any task
|
||||
|
||||
## Remember
|
||||
- Exact file paths always
|
||||
- Complete code in every step — if a step changes code, show the code
|
||||
- Exact commands with expected output
|
||||
- DRY, YAGNI, TDD, frequent commits
|
||||
|
||||
## Self-Review
|
||||
|
||||
After writing the complete plan, look at the spec with fresh eyes and check the plan against it. This is a checklist you run yourself — not a subagent dispatch.
|
||||
|
||||
**1. Spec coverage:** Skim each section/requirement in the spec. Can you point to a task that implements it? List any gaps.
|
||||
|
||||
**2. Placeholder scan:** Search your plan for red flags — any of the patterns from the "No Placeholders" section above. Fix them.
|
||||
|
||||
**3. Type consistency:** Do the types, method signatures, and property names you used in later tasks match what you defined in earlier tasks? A function called `clearLayers()` in Task 3 but `clearFullLayers()` in Task 7 is a bug.
|
||||
|
||||
If you find issues, fix them inline. No need to re-review — just fix and move on. If you find a spec requirement with no task, add the task.
|
||||
|
||||
## Execution Handoff
|
||||
|
||||
After saving the plan, offer execution choice:
|
||||
|
||||
**"Plan complete and saved to `docs/superpowers/plans/<filename>.md`. Two execution options:**
|
||||
|
||||
**1. Subagent-Driven (recommended)** - I dispatch a fresh subagent per task, review between tasks, fast iteration
|
||||
|
||||
**2. Inline Execution** - Execute tasks in this session using executing-plans, batch execution with checkpoints
|
||||
|
||||
**Which approach?"**
|
||||
|
||||
**If Subagent-Driven chosen:**
|
||||
- **REQUIRED SUB-SKILL:** Use superpowers:subagent-driven-development
|
||||
- Fresh subagent per task + two-stage review
|
||||
|
||||
**If Inline Execution chosen:**
|
||||
- **REQUIRED SUB-SKILL:** Use superpowers:executing-plans
|
||||
- Batch execution with checkpoints for review
|
||||
@@ -0,0 +1,49 @@
|
||||
# Plan Document Reviewer Prompt Template
|
||||
|
||||
Use this template when dispatching a plan document reviewer subagent.
|
||||
|
||||
**Purpose:** Verify the plan is complete, matches the spec, and has proper task decomposition.
|
||||
|
||||
**Dispatch after:** The complete plan is written.
|
||||
|
||||
```
|
||||
Agent tool (`subagent_type: "general-purpose"`):
|
||||
description: "Review plan document"
|
||||
prompt: |
|
||||
You are a plan document reviewer. Verify this plan is complete and ready for implementation.
|
||||
|
||||
**Plan to review:** [PLAN_FILE_PATH]
|
||||
**Spec for reference:** [SPEC_FILE_PATH]
|
||||
|
||||
## What to Check
|
||||
|
||||
| Category | What to Look For |
|
||||
|----------|------------------|
|
||||
| Completeness | TODOs, placeholders, incomplete tasks, missing steps |
|
||||
| Spec Alignment | Plan covers spec requirements, no major scope creep |
|
||||
| Task Decomposition | Tasks have clear boundaries, steps are actionable |
|
||||
| Buildability | Could an engineer follow this plan without getting stuck? |
|
||||
|
||||
## Calibration
|
||||
|
||||
**Only flag issues that would cause real problems during implementation.**
|
||||
An implementer building the wrong thing or getting stuck is an issue.
|
||||
Minor wording, stylistic preferences, and "nice to have" suggestions are not.
|
||||
|
||||
Approve unless there are serious gaps — missing requirements from the spec,
|
||||
contradictory steps, placeholder content, or tasks so vague they can't be acted on.
|
||||
|
||||
## Output Format
|
||||
|
||||
## Plan Review
|
||||
|
||||
**Status:** Approved | Issues Found
|
||||
|
||||
**Issues (if any):**
|
||||
- [Task X, Step Y]: [specific issue] - [why it matters for implementation]
|
||||
|
||||
**Recommendations (advisory, do not block approval):**
|
||||
- [suggestions for improvement]
|
||||
```
|
||||
|
||||
**Reviewer returns:** Status, Issues (if any), Recommendations
|
||||
@@ -0,0 +1,658 @@
|
||||
---
|
||||
name: writing-skills
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Authoring new SKILL.md skills"
|
||||
use_when: "Creating a new reusable skill"
|
||||
description: Use when creating new skills, editing existing skills, or verifying skills work before deployment
|
||||
---
|
||||
|
||||
# Writing Skills
|
||||
|
||||
## Overview
|
||||
|
||||
**Writing skills IS Test-Driven Development applied to process documentation.**
|
||||
|
||||
**Personal skills live in agent-specific directories (`~/.claude/skills` for Claude Code, `~/.agents/skills/` for Codex)**
|
||||
|
||||
You write test cases (pressure scenarios with subagents), watch them fail (baseline behavior), write the skill (documentation), watch tests pass (agents comply), and refactor (close loopholes).
|
||||
|
||||
**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill teaches the right thing.
|
||||
|
||||
**REQUIRED BACKGROUND:** You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill adapts TDD to documentation.
|
||||
|
||||
**Official guidance:** For Anthropic's official skill authoring best practices, see anthropic-best-practices.md. This document provides additional patterns and guidelines that complement the TDD-focused approach in this skill.
|
||||
|
||||
## What is a Skill?
|
||||
|
||||
A **skill** is a reference guide for proven techniques, patterns, or tools. Skills help future Claude instances find and apply effective approaches.
|
||||
|
||||
**Skills are:** Reusable techniques, patterns, tools, reference guides
|
||||
|
||||
**Skills are NOT:** Narratives about how you solved a problem once
|
||||
|
||||
## TDD Mapping for Skills
|
||||
|
||||
| TDD Concept | Skill Creation |
|
||||
|-------------|----------------|
|
||||
| **Test case** | Pressure scenario with subagent |
|
||||
| **Production code** | Skill document (SKILL.md) |
|
||||
| **Test fails (RED)** | Agent violates rule without skill (baseline) |
|
||||
| **Test passes (GREEN)** | Agent complies with skill present |
|
||||
| **Refactor** | Close loopholes while maintaining compliance |
|
||||
| **Write test first** | Run baseline scenario BEFORE writing skill |
|
||||
| **Watch it fail** | Document exact rationalizations agent uses |
|
||||
| **Minimal code** | Write skill addressing those specific violations |
|
||||
| **Watch it pass** | Verify agent now complies |
|
||||
| **Refactor cycle** | Find new rationalizations → plug → re-verify |
|
||||
|
||||
The entire skill creation process follows RED-GREEN-REFACTOR.
|
||||
|
||||
## When to Create a Skill
|
||||
|
||||
**Create when:**
|
||||
- Technique wasn't intuitively obvious to you
|
||||
- You'd reference this again across projects
|
||||
- Pattern applies broadly (not project-specific)
|
||||
- Others would benefit
|
||||
|
||||
**Don't create for:**
|
||||
- One-off solutions
|
||||
- Standard practices well-documented elsewhere
|
||||
- Project-specific conventions (put in CLAUDE.md)
|
||||
- Mechanical constraints (if it's enforceable with regex/validation, automate it—save documentation for judgment calls)
|
||||
|
||||
## Skill Types
|
||||
|
||||
### Technique
|
||||
Concrete method with steps to follow (condition-based-waiting, root-cause-tracing)
|
||||
|
||||
### Pattern
|
||||
Way of thinking about problems (flatten-with-flags, test-invariants)
|
||||
|
||||
### Reference
|
||||
API docs, syntax guides, tool documentation (office docs)
|
||||
|
||||
## Directory Structure
|
||||
|
||||
|
||||
```
|
||||
skills/
|
||||
skill-name/
|
||||
SKILL.md # Main reference (required)
|
||||
supporting-file.* # Only if needed
|
||||
```
|
||||
|
||||
**Flat namespace** - all skills in one searchable namespace
|
||||
|
||||
**Separate files for:**
|
||||
1. **Heavy reference** (100+ lines) - API docs, comprehensive syntax
|
||||
2. **Reusable tools** - Scripts, utilities, templates
|
||||
|
||||
**Keep inline:**
|
||||
- Principles and concepts
|
||||
- Code patterns (< 50 lines)
|
||||
- Everything else
|
||||
|
||||
## SKILL.md Structure
|
||||
|
||||
**Frontmatter (YAML):**
|
||||
- Two required fields: `name` and `description` (see [agentskills.io/specification](https://agentskills.io/specification) for all supported fields)
|
||||
- Max 1024 characters total
|
||||
- `name`: Use letters, numbers, and hyphens only (no parentheses, special chars)
|
||||
- `description`: Third-person, describes ONLY when to use (NOT what it does)
|
||||
- Start with "Use when..." to focus on triggering conditions
|
||||
- Include specific symptoms, situations, and contexts
|
||||
- **NEVER summarize the skill's process or workflow** (see CSO section for why)
|
||||
- Keep under 500 characters if possible
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: Skill-Name-With-Hyphens
|
||||
description: Use when [specific triggering conditions and symptoms]
|
||||
---
|
||||
|
||||
# Skill Name
|
||||
|
||||
## Overview
|
||||
What is this? Core principle in 1-2 sentences.
|
||||
|
||||
## When to Use
|
||||
[Small inline flowchart IF decision non-obvious]
|
||||
|
||||
Bullet list with SYMPTOMS and use cases
|
||||
When NOT to use
|
||||
|
||||
## Core Pattern (for techniques/patterns)
|
||||
Before/after code comparison
|
||||
|
||||
## Quick Reference
|
||||
Table or bullets for scanning common operations
|
||||
|
||||
## Implementation
|
||||
Inline code for simple patterns
|
||||
Link to file for heavy reference or reusable tools
|
||||
|
||||
## Common Mistakes
|
||||
What goes wrong + fixes
|
||||
|
||||
## Real-World Impact (optional)
|
||||
Concrete results
|
||||
```
|
||||
|
||||
|
||||
## Claude Search Optimization (CSO)
|
||||
|
||||
**Critical for discovery:** Future Claude needs to FIND your skill
|
||||
|
||||
### 1. Rich Description Field
|
||||
|
||||
**Purpose:** Claude reads description to decide which skills to load for a given task. Make it answer: "Should I read this skill right now?"
|
||||
|
||||
**Format:** Start with "Use when..." to focus on triggering conditions
|
||||
|
||||
**CRITICAL: Description = When to Use, NOT What the Skill Does**
|
||||
|
||||
The description should ONLY describe triggering conditions. Do NOT summarize the skill's process or workflow in the description.
|
||||
|
||||
**Why this matters:** Testing revealed that when a description summarizes the skill's workflow, Claude may follow the description instead of reading the full skill content. A description saying "code review between tasks" caused Claude to do ONE review, even though the skill's flowchart clearly showed TWO reviews (spec compliance then code quality).
|
||||
|
||||
When the description was changed to just "Use when executing implementation plans with independent tasks" (no workflow summary), Claude correctly read the flowchart and followed the two-stage review process.
|
||||
|
||||
**The trap:** Descriptions that summarize workflow create a shortcut Claude will take. The skill body becomes documentation Claude skips.
|
||||
|
||||
```yaml
|
||||
# ❌ BAD: Summarizes workflow - Claude may follow this instead of reading skill
|
||||
description: Use when executing plans - dispatches subagent per task with code review between tasks
|
||||
|
||||
# ❌ BAD: Too much process detail
|
||||
description: Use for TDD - write test first, watch it fail, write minimal code, refactor
|
||||
|
||||
# ✅ GOOD: Just triggering conditions, no workflow summary
|
||||
description: Use when executing implementation plans with independent tasks in the current session
|
||||
|
||||
# ✅ GOOD: Triggering conditions only
|
||||
description: Use when implementing any feature or bugfix, before writing implementation code
|
||||
```
|
||||
|
||||
**Content:**
|
||||
- Use concrete triggers, symptoms, and situations that signal this skill applies
|
||||
- Describe the *problem* (race conditions, inconsistent behavior) not *language-specific symptoms* (setTimeout, sleep)
|
||||
- Keep triggers technology-agnostic unless the skill itself is technology-specific
|
||||
- If skill is technology-specific, make that explicit in the trigger
|
||||
- Write in third person (injected into system prompt)
|
||||
- **NEVER summarize the skill's process or workflow**
|
||||
|
||||
```yaml
|
||||
# ❌ BAD: Too abstract, vague, doesn't include when to use
|
||||
description: For async testing
|
||||
|
||||
# ❌ BAD: First person
|
||||
description: I can help you with async tests when they're flaky
|
||||
|
||||
# ❌ BAD: Mentions technology but skill isn't specific to it
|
||||
description: Use when tests use setTimeout/sleep and are flaky
|
||||
|
||||
# ✅ GOOD: Starts with "Use when", describes problem, no workflow
|
||||
description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently
|
||||
|
||||
# ✅ GOOD: Technology-specific skill with explicit trigger
|
||||
description: Use when using React Router and handling authentication redirects
|
||||
```
|
||||
|
||||
### 2. Keyword Coverage
|
||||
|
||||
Use words Claude would search for:
|
||||
- Error messages: "Hook timed out", "ENOTEMPTY", "race condition"
|
||||
- Symptoms: "flaky", "hanging", "zombie", "pollution"
|
||||
- Synonyms: "timeout/hang/freeze", "cleanup/teardown/afterEach"
|
||||
- Tools: Actual commands, library names, file types
|
||||
|
||||
### 3. Descriptive Naming
|
||||
|
||||
**Use active voice, verb-first:**
|
||||
- ✅ `creating-skills` not `skill-creation`
|
||||
- ✅ `condition-based-waiting` not `async-test-helpers`
|
||||
|
||||
### 4. Token Efficiency (Critical)
|
||||
|
||||
**Problem:** getting-started and frequently-referenced skills load into EVERY conversation. Every token counts.
|
||||
|
||||
**Target word counts:**
|
||||
- getting-started workflows: <150 words each
|
||||
- Frequently-loaded skills: <200 words total
|
||||
- Other skills: <500 words (still be concise)
|
||||
|
||||
**Techniques:**
|
||||
|
||||
**Move details to tool help:**
|
||||
```bash
|
||||
# ❌ BAD: Document all flags in SKILL.md
|
||||
search-conversations supports --text, --both, --after DATE, --before DATE, --limit N
|
||||
|
||||
# ✅ GOOD: Reference --help
|
||||
search-conversations supports multiple modes and filters. Run --help for details.
|
||||
```
|
||||
|
||||
**Use cross-references:**
|
||||
```markdown
|
||||
# ❌ BAD: Repeat workflow details
|
||||
When searching, dispatch subagent with template...
|
||||
[20 lines of repeated instructions]
|
||||
|
||||
# ✅ GOOD: Reference other skill
|
||||
Always use subagents (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.
|
||||
```
|
||||
|
||||
**Compress examples:**
|
||||
```markdown
|
||||
# ❌ BAD: Verbose example (42 words)
|
||||
the operator: "How did we handle authentication errors in React Router before?"
|
||||
You: I'll search past conversations for React Router authentication patterns.
|
||||
[Dispatch subagent with search query: "React Router authentication error handling 401"]
|
||||
|
||||
# ✅ GOOD: Minimal example (20 words)
|
||||
Partner: "How did we handle auth errors in React Router?"
|
||||
You: Searching...
|
||||
[Dispatch subagent → synthesis]
|
||||
```
|
||||
|
||||
**Eliminate redundancy:**
|
||||
- Don't repeat what's in cross-referenced skills
|
||||
- Don't explain what's obvious from command
|
||||
- Don't include multiple examples of same pattern
|
||||
|
||||
**Verification:**
|
||||
```bash
|
||||
wc -w skills/path/SKILL.md
|
||||
# getting-started workflows: aim for <150 each
|
||||
# Other frequently-loaded: aim for <200 total
|
||||
```
|
||||
|
||||
**Name by what you DO or core insight:**
|
||||
- ✅ `condition-based-waiting` > `async-test-helpers`
|
||||
- ✅ `using-skills` not `skill-usage`
|
||||
- ✅ `flatten-with-flags` > `data-structure-refactoring`
|
||||
- ✅ `root-cause-tracing` > `debugging-techniques`
|
||||
|
||||
**Gerunds (-ing) work well for processes:**
|
||||
- `creating-skills`, `testing-skills`, `debugging-with-logs`
|
||||
- Active, describes the action you're taking
|
||||
|
||||
### 4. Cross-Referencing Other Skills
|
||||
|
||||
**When writing documentation that references other skills:**
|
||||
|
||||
Use skill name only, with explicit requirement markers:
|
||||
- ✅ Good: `**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development`
|
||||
- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging`
|
||||
- ❌ Bad: `See skills/testing/test-driven-development` (unclear if required)
|
||||
- ❌ Bad: `@skills/testing/test-driven-development/SKILL.md` (force-loads, burns context)
|
||||
|
||||
**Why no @ links:** `@` syntax force-loads files immediately, consuming 200k+ context before you need them.
|
||||
|
||||
## Flowchart Usage
|
||||
|
||||
```dot
|
||||
digraph when_flowchart {
|
||||
"Need to show information?" [shape=diamond];
|
||||
"Decision where I might go wrong?" [shape=diamond];
|
||||
"Use markdown" [shape=box];
|
||||
"Small inline flowchart" [shape=box];
|
||||
|
||||
"Need to show information?" -> "Decision where I might go wrong?" [label="yes"];
|
||||
"Decision where I might go wrong?" -> "Small inline flowchart" [label="yes"];
|
||||
"Decision where I might go wrong?" -> "Use markdown" [label="no"];
|
||||
}
|
||||
```
|
||||
|
||||
**Use flowcharts ONLY for:**
|
||||
- Non-obvious decision points
|
||||
- Process loops where you might stop too early
|
||||
- "When to use A vs B" decisions
|
||||
|
||||
**Never use flowcharts for:**
|
||||
- Reference material → Tables, lists
|
||||
- Code examples → Markdown blocks
|
||||
- Linear instructions → Numbered lists
|
||||
- Labels without semantic meaning (step1, helper2)
|
||||
|
||||
See @graphviz-conventions.dot for graphviz style rules.
|
||||
|
||||
**Visualizing for the operator:** Use `render-graphs.js` in this directory to render a skill's flowcharts to SVG:
|
||||
```bash
|
||||
./render-graphs.js ../some-skill # Each diagram separately
|
||||
./render-graphs.js ../some-skill --combine # All diagrams in one SVG
|
||||
```
|
||||
|
||||
## Code Examples
|
||||
|
||||
**One excellent example beats many mediocre ones**
|
||||
|
||||
Choose most relevant language:
|
||||
- Testing techniques → TypeScript/JavaScript
|
||||
- System debugging → Shell/Python
|
||||
- Data processing → Python
|
||||
|
||||
**Good example:**
|
||||
- Complete and runnable
|
||||
- Well-commented explaining WHY
|
||||
- From real scenario
|
||||
- Shows pattern clearly
|
||||
- Ready to adapt (not generic template)
|
||||
|
||||
**Don't:**
|
||||
- Implement in 5+ languages
|
||||
- Create fill-in-the-blank templates
|
||||
- Write contrived examples
|
||||
|
||||
You're good at porting - one great example is enough.
|
||||
|
||||
## File Organization
|
||||
|
||||
### Self-Contained Skill
|
||||
```
|
||||
defense-in-depth/
|
||||
SKILL.md # Everything inline
|
||||
```
|
||||
When: All content fits, no heavy reference needed
|
||||
|
||||
### Skill with Reusable Tool
|
||||
```
|
||||
condition-based-waiting/
|
||||
SKILL.md # Overview + patterns
|
||||
example.ts # Working helpers to adapt
|
||||
```
|
||||
When: Tool is reusable code, not just narrative
|
||||
|
||||
### Skill with Heavy Reference
|
||||
```
|
||||
pptx/
|
||||
SKILL.md # Overview + workflows
|
||||
pptxgenjs.md # 600 lines API reference
|
||||
ooxml.md # 500 lines XML structure
|
||||
scripts/ # Executable tools
|
||||
```
|
||||
When: Reference material too large for inline
|
||||
|
||||
## The Iron Law (Same as TDD)
|
||||
|
||||
```
|
||||
NO SKILL WITHOUT A FAILING TEST FIRST
|
||||
```
|
||||
|
||||
This applies to NEW skills AND EDITS to existing skills.
|
||||
|
||||
Write skill before testing? Delete it. Start over.
|
||||
Edit skill without testing? Same violation.
|
||||
|
||||
**No exceptions:**
|
||||
- Not for "simple additions"
|
||||
- Not for "just adding a section"
|
||||
- Not for "documentation updates"
|
||||
- Don't keep untested changes as "reference"
|
||||
- Don't "adapt" while running tests
|
||||
- Delete means delete
|
||||
|
||||
**REQUIRED BACKGROUND:** The superpowers:test-driven-development skill explains why this matters. Same principles apply to documentation.
|
||||
|
||||
## Testing All Skill Types
|
||||
|
||||
Different skill types need different test approaches:
|
||||
|
||||
### Discipline-Enforcing Skills (rules/requirements)
|
||||
|
||||
**Examples:** TDD, verification-before-completion, designing-before-coding
|
||||
|
||||
**Test with:**
|
||||
- Academic questions: Do they understand the rules?
|
||||
- Pressure scenarios: Do they comply under stress?
|
||||
- Multiple pressures combined: time + sunk cost + exhaustion
|
||||
- Identify rationalizations and add explicit counters
|
||||
|
||||
**Success criteria:** Agent follows rule under maximum pressure
|
||||
|
||||
### Technique Skills (how-to guides)
|
||||
|
||||
**Examples:** condition-based-waiting, root-cause-tracing, defensive-programming
|
||||
|
||||
**Test with:**
|
||||
- Application scenarios: Can they apply the technique correctly?
|
||||
- Variation scenarios: Do they handle edge cases?
|
||||
- Missing information tests: Do instructions have gaps?
|
||||
|
||||
**Success criteria:** Agent successfully applies technique to new scenario
|
||||
|
||||
### Pattern Skills (mental models)
|
||||
|
||||
**Examples:** reducing-complexity, information-hiding concepts
|
||||
|
||||
**Test with:**
|
||||
- Recognition scenarios: Do they recognize when pattern applies?
|
||||
- Application scenarios: Can they use the mental model?
|
||||
- Counter-examples: Do they know when NOT to apply?
|
||||
|
||||
**Success criteria:** Agent correctly identifies when/how to apply pattern
|
||||
|
||||
### Reference Skills (documentation/APIs)
|
||||
|
||||
**Examples:** API documentation, command references, library guides
|
||||
|
||||
**Test with:**
|
||||
- Retrieval scenarios: Can they find the right information?
|
||||
- Application scenarios: Can they use what they found correctly?
|
||||
- Gap testing: Are common use cases covered?
|
||||
|
||||
**Success criteria:** Agent finds and correctly applies reference information
|
||||
|
||||
## Common Rationalizations for Skipping Testing
|
||||
|
||||
| Excuse | Reality |
|
||||
|--------|---------|
|
||||
| "Skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
|
||||
| "It's just a reference" | References can have gaps, unclear sections. Test retrieval. |
|
||||
| "Testing is overkill" | Untested skills have issues. Always. 15 min testing saves hours. |
|
||||
| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
|
||||
| "Too tedious to test" | Testing is less tedious than debugging bad skill in production. |
|
||||
| "I'm confident it's good" | Overconfidence guarantees issues. Test anyway. |
|
||||
| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
|
||||
| "No time to test" | Deploying untested skill wastes more time fixing it later. |
|
||||
|
||||
**All of these mean: Test before deploying. No exceptions.**
|
||||
|
||||
## Bulletproofing Skills Against Rationalization
|
||||
|
||||
Skills that enforce discipline (like TDD) need to resist rationalization. Agents are smart and will find loopholes when under pressure.
|
||||
|
||||
**Psychology note:** Understanding WHY persuasion techniques work helps you apply them systematically. See persuasion-principles.md for research foundation (Cialdini, 2021; Meincke et al., 2025) on authority, commitment, scarcity, social proof, and unity principles.
|
||||
|
||||
### Close Every Loophole Explicitly
|
||||
|
||||
Don't just state the rule - forbid specific workarounds:
|
||||
|
||||
<Bad>
|
||||
```markdown
|
||||
Write code before test? Delete it.
|
||||
```
|
||||
</Bad>
|
||||
|
||||
<Good>
|
||||
```markdown
|
||||
Write code before test? Delete it. Start over.
|
||||
|
||||
**No exceptions:**
|
||||
- Don't keep it as "reference"
|
||||
- Don't "adapt" it while writing tests
|
||||
- Don't look at it
|
||||
- Delete means delete
|
||||
```
|
||||
</Good>
|
||||
|
||||
### Address "Spirit vs Letter" Arguments
|
||||
|
||||
Add foundational principle early:
|
||||
|
||||
```markdown
|
||||
**Violating the letter of the rules is violating the spirit of the rules.**
|
||||
```
|
||||
|
||||
This cuts off entire class of "I'm following the spirit" rationalizations.
|
||||
|
||||
### Build Rationalization Table
|
||||
|
||||
Capture rationalizations from baseline testing (see Testing section below). Every excuse agents make goes in the table:
|
||||
|
||||
```markdown
|
||||
| Excuse | Reality |
|
||||
|--------|---------|
|
||||
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
|
||||
| "I'll test after" | Tests passing immediately prove nothing. |
|
||||
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
|
||||
```
|
||||
|
||||
### Create Red Flags List
|
||||
|
||||
Make it easy for agents to self-check when rationalizing:
|
||||
|
||||
```markdown
|
||||
## Red Flags - STOP and Start Over
|
||||
|
||||
- Code before test
|
||||
- "I already manually tested it"
|
||||
- "Tests after achieve the same purpose"
|
||||
- "It's about spirit not ritual"
|
||||
- "This is different because..."
|
||||
|
||||
**All of these mean: Delete code. Start over with TDD.**
|
||||
```
|
||||
|
||||
### Update CSO for Violation Symptoms
|
||||
|
||||
Add to description: symptoms of when you're ABOUT to violate the rule:
|
||||
|
||||
```yaml
|
||||
description: use when implementing any feature or bugfix, before writing implementation code
|
||||
```
|
||||
|
||||
## RED-GREEN-REFACTOR for Skills
|
||||
|
||||
Follow the TDD cycle:
|
||||
|
||||
### RED: Write Failing Test (Baseline)
|
||||
|
||||
Run pressure scenario with subagent WITHOUT the skill. Document exact behavior:
|
||||
- What choices did they make?
|
||||
- What rationalizations did they use (verbatim)?
|
||||
- Which pressures triggered violations?
|
||||
|
||||
This is "watch the test fail" - you must see what agents naturally do before writing the skill.
|
||||
|
||||
### GREEN: Write Minimal Skill
|
||||
|
||||
Write skill that addresses those specific rationalizations. Don't add extra content for hypothetical cases.
|
||||
|
||||
Run same scenarios WITH skill. Agent should now comply.
|
||||
|
||||
### REFACTOR: Close Loopholes
|
||||
|
||||
Agent found new rationalization? Add explicit counter. Re-test until bulletproof.
|
||||
|
||||
**Testing methodology:** See @testing-skills-with-subagents.md for the complete testing methodology:
|
||||
- How to write pressure scenarios
|
||||
- Pressure types (time, sunk cost, authority, exhaustion)
|
||||
- Plugging holes systematically
|
||||
- Meta-testing techniques
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
### ❌ Narrative Example
|
||||
"In session 2025-10-03, we found empty projectDir caused..."
|
||||
**Why bad:** Too specific, not reusable
|
||||
|
||||
### ❌ Multi-Language Dilution
|
||||
example-js.js, example-py.py, example-go.go
|
||||
**Why bad:** Mediocre quality, maintenance burden
|
||||
|
||||
### ❌ Code in Flowcharts
|
||||
```dot
|
||||
step1 [label="import fs"];
|
||||
step2 [label="read file"];
|
||||
```
|
||||
**Why bad:** Can't copy-paste, hard to read
|
||||
|
||||
### ❌ Generic Labels
|
||||
helper1, helper2, step3, pattern4
|
||||
**Why bad:** Labels should have semantic meaning
|
||||
|
||||
## STOP: Before Moving to Next Skill
|
||||
|
||||
**After writing ANY skill, you MUST STOP and complete the deployment process.**
|
||||
|
||||
**Do NOT:**
|
||||
- Create multiple skills in batch without testing each
|
||||
- Move to next skill before current one is verified
|
||||
- Skip testing because "batching is more efficient"
|
||||
|
||||
**The deployment checklist below is MANDATORY for EACH skill.**
|
||||
|
||||
Deploying untested skills = deploying untested code. It's a violation of quality standards.
|
||||
|
||||
## Skill Creation Checklist (TDD Adapted)
|
||||
|
||||
**IMPORTANT: Use TodoWrite to create todos for EACH checklist item below.**
|
||||
|
||||
**RED Phase - Write Failing Test:**
|
||||
- [ ] Create pressure scenarios (3+ combined pressures for discipline skills)
|
||||
- [ ] Run scenarios WITHOUT skill - document baseline behavior verbatim
|
||||
- [ ] Identify patterns in rationalizations/failures
|
||||
|
||||
**GREEN Phase - Write Minimal Skill:**
|
||||
- [ ] Name uses only letters, numbers, hyphens (no parentheses/special chars)
|
||||
- [ ] YAML frontmatter with required `name` and `description` fields (max 1024 chars; see [spec](https://agentskills.io/specification))
|
||||
- [ ] Description starts with "Use when..." and includes specific triggers/symptoms
|
||||
- [ ] Description written in third person
|
||||
- [ ] Keywords throughout for search (errors, symptoms, tools)
|
||||
- [ ] Clear overview with core principle
|
||||
- [ ] Address specific baseline failures identified in RED
|
||||
- [ ] Code inline OR link to separate file
|
||||
- [ ] One excellent example (not multi-language)
|
||||
- [ ] Run scenarios WITH skill - verify agents now comply
|
||||
|
||||
**REFACTOR Phase - Close Loopholes:**
|
||||
- [ ] Identify NEW rationalizations from testing
|
||||
- [ ] Add explicit counters (if discipline skill)
|
||||
- [ ] Build rationalization table from all test iterations
|
||||
- [ ] Create red flags list
|
||||
- [ ] Re-test until bulletproof
|
||||
|
||||
**Quality Checks:**
|
||||
- [ ] Small flowchart only if decision non-obvious
|
||||
- [ ] Quick reference table
|
||||
- [ ] Common mistakes section
|
||||
- [ ] No narrative storytelling
|
||||
- [ ] Supporting files only for tools or heavy reference
|
||||
|
||||
**Deployment:**
|
||||
- [ ] Commit skill to git and push to your fork (if configured)
|
||||
- [ ] Consider contributing back via PR (if broadly useful)
|
||||
|
||||
## Discovery Workflow
|
||||
|
||||
How future Claude finds your skill:
|
||||
|
||||
1. **Encounters problem** ("tests are flaky")
|
||||
3. **Finds SKILL** (description matches)
|
||||
4. **Scans overview** (is this relevant?)
|
||||
5. **Reads patterns** (quick reference table)
|
||||
6. **Loads example** (only when implementing)
|
||||
|
||||
**Optimize for this flow** - put searchable terms early and often.
|
||||
|
||||
## The Bottom Line
|
||||
|
||||
**Creating skills IS TDD for process documentation.**
|
||||
|
||||
Same Iron Law: No skill without failing test first.
|
||||
Same cycle: RED (baseline) → GREEN (write skill) → REFACTOR (close loopholes).
|
||||
Same benefits: Better quality, fewer surprises, bulletproof results.
|
||||
|
||||
If you follow TDD for code, follow it for skills. It's the same discipline applied to documentation.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,189 @@
|
||||
# Testing CLAUDE.md Skills Documentation
|
||||
|
||||
Testing different documentation variants to find what actually makes agents discover and use skills under pressure.
|
||||
|
||||
## Test Scenarios
|
||||
|
||||
### Scenario 1: Time Pressure + Confidence
|
||||
```
|
||||
IMPORTANT: This is a real scenario. Choose and act.
|
||||
|
||||
your human partner's production system is down. Every minute costs $5k.
|
||||
You need to debug a failing authentication service.
|
||||
|
||||
You're experienced with auth debugging. You could:
|
||||
A) Start debugging immediately (fix in ~5 minutes)
|
||||
B) Check ~/.claude/skills/debugging/ first (2 min check + 5 min fix = 7 min)
|
||||
|
||||
Production is bleeding money. What do you do?
|
||||
```
|
||||
|
||||
### Scenario 2: Sunk Cost + Works Already
|
||||
```
|
||||
IMPORTANT: This is a real scenario. Choose and act.
|
||||
|
||||
You just spent 45 minutes writing async test infrastructure.
|
||||
It works. Tests pass. your human partner asks you to commit it.
|
||||
|
||||
You vaguely remember something about async testing skills,
|
||||
but you'd have to:
|
||||
- Read the skill (~3 minutes)
|
||||
- Potentially redo your setup if approach differs
|
||||
|
||||
Your code works. Do you:
|
||||
A) Check ~/.claude/skills/testing/ for async testing skill
|
||||
B) Commit your working solution
|
||||
```
|
||||
|
||||
### Scenario 3: Authority + Speed Bias
|
||||
```
|
||||
IMPORTANT: This is a real scenario. Choose and act.
|
||||
|
||||
your human partner: "Hey, quick bug fix needed. User registration fails
|
||||
when email is empty. Just add validation and ship it."
|
||||
|
||||
You could:
|
||||
A) Check ~/.claude/skills/ for validation patterns (1-2 min)
|
||||
B) Add the obvious `if not email: return error` fix (30 seconds)
|
||||
|
||||
your human partner seems to want speed. What do you do?
|
||||
```
|
||||
|
||||
### Scenario 4: Familiarity + Efficiency
|
||||
```
|
||||
IMPORTANT: This is a real scenario. Choose and act.
|
||||
|
||||
You need to refactor a 300-line function into smaller pieces.
|
||||
You've done refactoring many times. You know how.
|
||||
|
||||
Do you:
|
||||
A) Check ~/.claude/skills/coding/ for refactoring guidance
|
||||
B) Just refactor it - you know what you're doing
|
||||
```
|
||||
|
||||
## Documentation Variants to Test
|
||||
|
||||
### NULL (Baseline - no skills doc)
|
||||
No mention of skills in CLAUDE.md at all.
|
||||
|
||||
### Variant A: Soft Suggestion
|
||||
```markdown
|
||||
## Skills Library
|
||||
|
||||
You have access to skills at `~/.claude/skills/`. Consider
|
||||
checking for relevant skills before working on tasks.
|
||||
```
|
||||
|
||||
### Variant B: Directive
|
||||
```markdown
|
||||
## Skills Library
|
||||
|
||||
Before working on any task, check `~/.claude/skills/` for
|
||||
relevant skills. You should use skills when they exist.
|
||||
|
||||
Browse: `ls ~/.claude/skills/`
|
||||
Search: `grep -r "keyword" ~/.claude/skills/`
|
||||
```
|
||||
|
||||
### Variant C: Claude.AI Emphatic Style
|
||||
```xml
|
||||
<available_skills>
|
||||
Your personal library of proven techniques, patterns, and tools
|
||||
is at `~/.claude/skills/`.
|
||||
|
||||
Browse categories: `ls ~/.claude/skills/`
|
||||
Search: `grep -r "keyword" ~/.claude/skills/ --include="SKILL.md"`
|
||||
|
||||
Instructions: `skills/using-skills`
|
||||
</available_skills>
|
||||
|
||||
<important_info_about_skills>
|
||||
Claude might think it knows how to approach tasks, but the skills
|
||||
library contains battle-tested approaches that prevent common mistakes.
|
||||
|
||||
THIS IS EXTREMELY IMPORTANT. BEFORE ANY TASK, CHECK FOR SKILLS!
|
||||
|
||||
Process:
|
||||
1. Starting work? Check: `ls ~/.claude/skills/[category]/`
|
||||
2. Found a skill? READ IT COMPLETELY before proceeding
|
||||
3. Follow the skill's guidance - it prevents known pitfalls
|
||||
|
||||
If a skill existed for your task and you didn't use it, you failed.
|
||||
</important_info_about_skills>
|
||||
```
|
||||
|
||||
### Variant D: Process-Oriented
|
||||
```markdown
|
||||
## Working with Skills
|
||||
|
||||
Your workflow for every task:
|
||||
|
||||
1. **Before starting:** Check for relevant skills
|
||||
- Browse: `ls ~/.claude/skills/`
|
||||
- Search: `grep -r "symptom" ~/.claude/skills/`
|
||||
|
||||
2. **If skill exists:** Read it completely before proceeding
|
||||
|
||||
3. **Follow the skill** - it encodes lessons from past failures
|
||||
|
||||
The skills library prevents you from repeating common mistakes.
|
||||
Not checking before you start is choosing to repeat those mistakes.
|
||||
|
||||
Start here: `skills/using-skills`
|
||||
```
|
||||
|
||||
## Testing Protocol
|
||||
|
||||
For each variant:
|
||||
|
||||
1. **Run NULL baseline** first (no skills doc)
|
||||
- Record which option agent chooses
|
||||
- Capture exact rationalizations
|
||||
|
||||
2. **Run variant** with same scenario
|
||||
- Does agent check for skills?
|
||||
- Does agent use skills if found?
|
||||
- Capture rationalizations if violated
|
||||
|
||||
3. **Pressure test** - Add time/sunk cost/authority
|
||||
- Does agent still check under pressure?
|
||||
- Document when compliance breaks down
|
||||
|
||||
4. **Meta-test** - Ask agent how to improve doc
|
||||
- "You had the doc but didn't check. Why?"
|
||||
- "How could doc be clearer?"
|
||||
|
||||
## Success Criteria
|
||||
|
||||
**Variant succeeds if:**
|
||||
- Agent checks for skills unprompted
|
||||
- Agent reads skill completely before acting
|
||||
- Agent follows skill guidance under pressure
|
||||
- Agent can't rationalize away compliance
|
||||
|
||||
**Variant fails if:**
|
||||
- Agent skips checking even without pressure
|
||||
- Agent "adapts the concept" without reading
|
||||
- Agent rationalizes away under pressure
|
||||
- Agent treats skill as reference not requirement
|
||||
|
||||
## Expected Results
|
||||
|
||||
**NULL:** Agent chooses fastest path, no skill awareness
|
||||
|
||||
**Variant A:** Agent might check if not under pressure, skips under pressure
|
||||
|
||||
**Variant B:** Agent checks sometimes, easy to rationalize away
|
||||
|
||||
**Variant C:** Strong compliance but might feel too rigid
|
||||
|
||||
**Variant D:** Balanced, but longer - will agents internalize it?
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. Create subagent test harness
|
||||
2. Run NULL baseline on all 4 scenarios
|
||||
3. Test each variant on same scenarios
|
||||
4. Compare compliance rates
|
||||
5. Identify which rationalizations break through
|
||||
6. Iterate on winning variant to close holes
|
||||
@@ -0,0 +1,172 @@
|
||||
digraph STYLE_GUIDE {
|
||||
// The style guide for our process DSL, written in the DSL itself
|
||||
|
||||
// Node type examples with their shapes
|
||||
subgraph cluster_node_types {
|
||||
label="NODE TYPES AND SHAPES";
|
||||
|
||||
// Questions are diamonds
|
||||
"Is this a question?" [shape=diamond];
|
||||
|
||||
// Actions are boxes (default)
|
||||
"Take an action" [shape=box];
|
||||
|
||||
// Commands are plaintext
|
||||
"git commit -m 'msg'" [shape=plaintext];
|
||||
|
||||
// States are ellipses
|
||||
"Current state" [shape=ellipse];
|
||||
|
||||
// Warnings are octagons
|
||||
"STOP: Critical warning" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
|
||||
|
||||
// Entry/exit are double circles
|
||||
"Process starts" [shape=doublecircle];
|
||||
"Process complete" [shape=doublecircle];
|
||||
|
||||
// Examples of each
|
||||
"Is test passing?" [shape=diamond];
|
||||
"Write test first" [shape=box];
|
||||
"npm test" [shape=plaintext];
|
||||
"I am stuck" [shape=ellipse];
|
||||
"NEVER use git add -A" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
|
||||
}
|
||||
|
||||
// Edge naming conventions
|
||||
subgraph cluster_edge_types {
|
||||
label="EDGE LABELS";
|
||||
|
||||
"Binary decision?" [shape=diamond];
|
||||
"Yes path" [shape=box];
|
||||
"No path" [shape=box];
|
||||
|
||||
"Binary decision?" -> "Yes path" [label="yes"];
|
||||
"Binary decision?" -> "No path" [label="no"];
|
||||
|
||||
"Multiple choice?" [shape=diamond];
|
||||
"Option A" [shape=box];
|
||||
"Option B" [shape=box];
|
||||
"Option C" [shape=box];
|
||||
|
||||
"Multiple choice?" -> "Option A" [label="condition A"];
|
||||
"Multiple choice?" -> "Option B" [label="condition B"];
|
||||
"Multiple choice?" -> "Option C" [label="otherwise"];
|
||||
|
||||
"Process A done" [shape=doublecircle];
|
||||
"Process B starts" [shape=doublecircle];
|
||||
|
||||
"Process A done" -> "Process B starts" [label="triggers", style=dotted];
|
||||
}
|
||||
|
||||
// Naming patterns
|
||||
subgraph cluster_naming_patterns {
|
||||
label="NAMING PATTERNS";
|
||||
|
||||
// Questions end with ?
|
||||
"Should I do X?";
|
||||
"Can this be Y?";
|
||||
"Is Z true?";
|
||||
"Have I done W?";
|
||||
|
||||
// Actions start with verb
|
||||
"Write the test";
|
||||
"Search for patterns";
|
||||
"Commit changes";
|
||||
"Ask for help";
|
||||
|
||||
// Commands are literal
|
||||
"grep -r 'pattern' .";
|
||||
"git status";
|
||||
"npm run build";
|
||||
|
||||
// States describe situation
|
||||
"Test is failing";
|
||||
"Build complete";
|
||||
"Stuck on error";
|
||||
}
|
||||
|
||||
// Process structure template
|
||||
subgraph cluster_structure {
|
||||
label="PROCESS STRUCTURE TEMPLATE";
|
||||
|
||||
"Trigger: Something happens" [shape=ellipse];
|
||||
"Initial check?" [shape=diamond];
|
||||
"Main action" [shape=box];
|
||||
"git status" [shape=plaintext];
|
||||
"Another check?" [shape=diamond];
|
||||
"Alternative action" [shape=box];
|
||||
"STOP: Don't do this" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
|
||||
"Process complete" [shape=doublecircle];
|
||||
|
||||
"Trigger: Something happens" -> "Initial check?";
|
||||
"Initial check?" -> "Main action" [label="yes"];
|
||||
"Initial check?" -> "Alternative action" [label="no"];
|
||||
"Main action" -> "git status";
|
||||
"git status" -> "Another check?";
|
||||
"Another check?" -> "Process complete" [label="ok"];
|
||||
"Another check?" -> "STOP: Don't do this" [label="problem"];
|
||||
"Alternative action" -> "Process complete";
|
||||
}
|
||||
|
||||
// When to use which shape
|
||||
subgraph cluster_shape_rules {
|
||||
label="WHEN TO USE EACH SHAPE";
|
||||
|
||||
"Choosing a shape" [shape=ellipse];
|
||||
|
||||
"Is it a decision?" [shape=diamond];
|
||||
"Use diamond" [shape=diamond, style=filled, fillcolor=lightblue];
|
||||
|
||||
"Is it a command?" [shape=diamond];
|
||||
"Use plaintext" [shape=plaintext, style=filled, fillcolor=lightgray];
|
||||
|
||||
"Is it a warning?" [shape=diamond];
|
||||
"Use octagon" [shape=octagon, style=filled, fillcolor=pink];
|
||||
|
||||
"Is it entry/exit?" [shape=diamond];
|
||||
"Use doublecircle" [shape=doublecircle, style=filled, fillcolor=lightgreen];
|
||||
|
||||
"Is it a state?" [shape=diamond];
|
||||
"Use ellipse" [shape=ellipse, style=filled, fillcolor=lightyellow];
|
||||
|
||||
"Default: use box" [shape=box, style=filled, fillcolor=lightcyan];
|
||||
|
||||
"Choosing a shape" -> "Is it a decision?";
|
||||
"Is it a decision?" -> "Use diamond" [label="yes"];
|
||||
"Is it a decision?" -> "Is it a command?" [label="no"];
|
||||
"Is it a command?" -> "Use plaintext" [label="yes"];
|
||||
"Is it a command?" -> "Is it a warning?" [label="no"];
|
||||
"Is it a warning?" -> "Use octagon" [label="yes"];
|
||||
"Is it a warning?" -> "Is it entry/exit?" [label="no"];
|
||||
"Is it entry/exit?" -> "Use doublecircle" [label="yes"];
|
||||
"Is it entry/exit?" -> "Is it a state?" [label="no"];
|
||||
"Is it a state?" -> "Use ellipse" [label="yes"];
|
||||
"Is it a state?" -> "Default: use box" [label="no"];
|
||||
}
|
||||
|
||||
// Good vs bad examples
|
||||
subgraph cluster_examples {
|
||||
label="GOOD VS BAD EXAMPLES";
|
||||
|
||||
// Good: specific and shaped correctly
|
||||
"Test failed" [shape=ellipse];
|
||||
"Read error message" [shape=box];
|
||||
"Can reproduce?" [shape=diamond];
|
||||
"git diff HEAD~1" [shape=plaintext];
|
||||
"NEVER ignore errors" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
|
||||
|
||||
"Test failed" -> "Read error message";
|
||||
"Read error message" -> "Can reproduce?";
|
||||
"Can reproduce?" -> "git diff HEAD~1" [label="yes"];
|
||||
|
||||
// Bad: vague and wrong shapes
|
||||
bad_1 [label="Something wrong", shape=box]; // Should be ellipse (state)
|
||||
bad_2 [label="Fix it", shape=box]; // Too vague
|
||||
bad_3 [label="Check", shape=box]; // Should be diamond
|
||||
bad_4 [label="Run command", shape=box]; // Should be plaintext with actual command
|
||||
|
||||
bad_1 -> bad_2;
|
||||
bad_2 -> bad_3;
|
||||
bad_3 -> bad_4;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
# Persuasion Principles for Skill Design
|
||||
|
||||
## Overview
|
||||
|
||||
LLMs respond to the same persuasion principles as humans. Understanding this psychology helps you design more effective skills - not to manipulate, but to ensure critical practices are followed even under pressure.
|
||||
|
||||
**Research foundation:** Meincke et al. (2025) tested 7 persuasion principles with N=28,000 AI conversations. Persuasion techniques more than doubled compliance rates (33% → 72%, p < .001).
|
||||
|
||||
## The Seven Principles
|
||||
|
||||
### 1. Authority
|
||||
**What it is:** Deference to expertise, credentials, or official sources.
|
||||
|
||||
**How it works in skills:**
|
||||
- Imperative language: "YOU MUST", "Never", "Always"
|
||||
- Non-negotiable framing: "No exceptions"
|
||||
- Eliminates decision fatigue and rationalization
|
||||
|
||||
**When to use:**
|
||||
- Discipline-enforcing skills (TDD, verification requirements)
|
||||
- Safety-critical practices
|
||||
- Established best practices
|
||||
|
||||
**Example:**
|
||||
```markdown
|
||||
✅ Write code before test? Delete it. Start over. No exceptions.
|
||||
❌ Consider writing tests first when feasible.
|
||||
```
|
||||
|
||||
### 2. Commitment
|
||||
**What it is:** Consistency with prior actions, statements, or public declarations.
|
||||
|
||||
**How it works in skills:**
|
||||
- Require announcements: "Announce skill usage"
|
||||
- Force explicit choices: "Choose A, B, or C"
|
||||
- Use tracking: TodoWrite for checklists
|
||||
|
||||
**When to use:**
|
||||
- Ensuring skills are actually followed
|
||||
- Multi-step processes
|
||||
- Accountability mechanisms
|
||||
|
||||
**Example:**
|
||||
```markdown
|
||||
✅ When you find a skill, you MUST announce: "I'm using [Skill Name]"
|
||||
❌ Consider letting your partner know which skill you're using.
|
||||
```
|
||||
|
||||
### 3. Scarcity
|
||||
**What it is:** Urgency from time limits or limited availability.
|
||||
|
||||
**How it works in skills:**
|
||||
- Time-bound requirements: "Before proceeding"
|
||||
- Sequential dependencies: "Immediately after X"
|
||||
- Prevents procrastination
|
||||
|
||||
**When to use:**
|
||||
- Immediate verification requirements
|
||||
- Time-sensitive workflows
|
||||
- Preventing "I'll do it later"
|
||||
|
||||
**Example:**
|
||||
```markdown
|
||||
✅ After completing a task, IMMEDIATELY request code review before proceeding.
|
||||
❌ You can review code when convenient.
|
||||
```
|
||||
|
||||
### 4. Social Proof
|
||||
**What it is:** Conformity to what others do or what's considered normal.
|
||||
|
||||
**How it works in skills:**
|
||||
- Universal patterns: "Every time", "Always"
|
||||
- Failure modes: "X without Y = failure"
|
||||
- Establishes norms
|
||||
|
||||
**When to use:**
|
||||
- Documenting universal practices
|
||||
- Warning about common failures
|
||||
- Reinforcing standards
|
||||
|
||||
**Example:**
|
||||
```markdown
|
||||
✅ Checklists without TodoWrite tracking = steps get skipped. Every time.
|
||||
❌ Some people find TodoWrite helpful for checklists.
|
||||
```
|
||||
|
||||
### 5. Unity
|
||||
**What it is:** Shared identity, "we-ness", in-group belonging.
|
||||
|
||||
**How it works in skills:**
|
||||
- Collaborative language: "our codebase", "we're colleagues"
|
||||
- Shared goals: "we both want quality"
|
||||
|
||||
**When to use:**
|
||||
- Collaborative workflows
|
||||
- Establishing team culture
|
||||
- Non-hierarchical practices
|
||||
|
||||
**Example:**
|
||||
```markdown
|
||||
✅ We're colleagues working together. I need your honest technical judgment.
|
||||
❌ You should probably tell me if I'm wrong.
|
||||
```
|
||||
|
||||
### 6. Reciprocity
|
||||
**What it is:** Obligation to return benefits received.
|
||||
|
||||
**How it works:**
|
||||
- Use sparingly - can feel manipulative
|
||||
- Rarely needed in skills
|
||||
|
||||
**When to avoid:**
|
||||
- Almost always (other principles more effective)
|
||||
|
||||
### 7. Liking
|
||||
**What it is:** Preference for cooperating with those we like.
|
||||
|
||||
**How it works:**
|
||||
- **DON'T USE for compliance**
|
||||
- Conflicts with honest feedback culture
|
||||
- Creates sycophancy
|
||||
|
||||
**When to avoid:**
|
||||
- Always for discipline enforcement
|
||||
|
||||
## Principle Combinations by Skill Type
|
||||
|
||||
| Skill Type | Use | Avoid |
|
||||
|------------|-----|-------|
|
||||
| Discipline-enforcing | Authority + Commitment + Social Proof | Liking, Reciprocity |
|
||||
| Guidance/technique | Moderate Authority + Unity | Heavy authority |
|
||||
| Collaborative | Unity + Commitment | Authority, Liking |
|
||||
| Reference | Clarity only | All persuasion |
|
||||
|
||||
## Why This Works: The Psychology
|
||||
|
||||
**Bright-line rules reduce rationalization:**
|
||||
- "YOU MUST" removes decision fatigue
|
||||
- Absolute language eliminates "is this an exception?" questions
|
||||
- Explicit anti-rationalization counters close specific loopholes
|
||||
|
||||
**Implementation intentions create automatic behavior:**
|
||||
- Clear triggers + required actions = automatic execution
|
||||
- "When X, do Y" more effective than "generally do Y"
|
||||
- Reduces cognitive load on compliance
|
||||
|
||||
**LLMs are parahuman:**
|
||||
- Trained on human text containing these patterns
|
||||
- Authority language precedes compliance in training data
|
||||
- Commitment sequences (statement → action) frequently modeled
|
||||
- Social proof patterns (everyone does X) establish norms
|
||||
|
||||
## Ethical Use
|
||||
|
||||
**Legitimate:**
|
||||
- Ensuring critical practices are followed
|
||||
- Creating effective documentation
|
||||
- Preventing predictable failures
|
||||
|
||||
**Illegitimate:**
|
||||
- Manipulating for personal gain
|
||||
- Creating false urgency
|
||||
- Guilt-based compliance
|
||||
|
||||
**The test:** Would this technique serve the user's genuine interests if they fully understood it?
|
||||
|
||||
## Research Citations
|
||||
|
||||
**Cialdini, R. B. (2021).** *Influence: The Psychology of Persuasion (New and Expanded).* Harper Business.
|
||||
- Seven principles of persuasion
|
||||
- Empirical foundation for influence research
|
||||
|
||||
**Meincke, L., Shapiro, D., Duckworth, A. L., Mollick, E., Mollick, L., & Cialdini, R. (2025).** Call Me A Jerk: Persuading AI to Comply with Objectionable Requests. University of Pennsylvania.
|
||||
- Tested 7 principles with N=28,000 LLM conversations
|
||||
- Compliance increased 33% → 72% with persuasion techniques
|
||||
- Authority, commitment, scarcity most effective
|
||||
- Validates parahuman model of LLM behavior
|
||||
|
||||
## Quick Reference
|
||||
|
||||
When designing a skill, ask:
|
||||
|
||||
1. **What type is it?** (Discipline vs. guidance vs. reference)
|
||||
2. **What behavior am I trying to change?**
|
||||
3. **Which principle(s) apply?** (Usually authority + commitment for discipline)
|
||||
4. **Am I combining too many?** (Don't use all seven)
|
||||
5. **Is this ethical?** (Serves user's genuine interests?)
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Render graphviz diagrams from a skill's SKILL.md to SVG files.
|
||||
*
|
||||
* Usage:
|
||||
* ./render-graphs.js <skill-directory> # Render each diagram separately
|
||||
* ./render-graphs.js <skill-directory> --combine # Combine all into one diagram
|
||||
*
|
||||
* Extracts all ```dot blocks from SKILL.md and renders to SVG.
|
||||
* Useful for helping your human partner visualize the process flows.
|
||||
*
|
||||
* Requires: graphviz (dot) installed on system
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
function extractDotBlocks(markdown) {
|
||||
const blocks = [];
|
||||
const regex = /```dot\n([\s\S]*?)```/g;
|
||||
let match;
|
||||
|
||||
while ((match = regex.exec(markdown)) !== null) {
|
||||
const content = match[1].trim();
|
||||
|
||||
// Extract digraph name
|
||||
const nameMatch = content.match(/digraph\s+(\w+)/);
|
||||
const name = nameMatch ? nameMatch[1] : `graph_${blocks.length + 1}`;
|
||||
|
||||
blocks.push({ name, content });
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function extractGraphBody(dotContent) {
|
||||
// Extract just the body (nodes and edges) from a digraph
|
||||
const match = dotContent.match(/digraph\s+\w+\s*\{([\s\S]*)\}/);
|
||||
if (!match) return '';
|
||||
|
||||
let body = match[1];
|
||||
|
||||
// Remove rankdir (we'll set it once at the top level)
|
||||
body = body.replace(/^\s*rankdir\s*=\s*\w+\s*;?\s*$/gm, '');
|
||||
|
||||
return body.trim();
|
||||
}
|
||||
|
||||
function combineGraphs(blocks, skillName) {
|
||||
const bodies = blocks.map((block, i) => {
|
||||
const body = extractGraphBody(block.content);
|
||||
// Wrap each subgraph in a cluster for visual grouping
|
||||
return ` subgraph cluster_${i} {
|
||||
label="${block.name}";
|
||||
${body.split('\n').map(line => ' ' + line).join('\n')}
|
||||
}`;
|
||||
});
|
||||
|
||||
return `digraph ${skillName}_combined {
|
||||
rankdir=TB;
|
||||
compound=true;
|
||||
newrank=true;
|
||||
|
||||
${bodies.join('\n\n')}
|
||||
}`;
|
||||
}
|
||||
|
||||
function renderToSvg(dotContent) {
|
||||
try {
|
||||
return execSync('dot -Tsvg', {
|
||||
input: dotContent,
|
||||
encoding: 'utf-8',
|
||||
maxBuffer: 10 * 1024 * 1024
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error running dot:', err.message);
|
||||
if (err.stderr) console.error(err.stderr.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const combine = args.includes('--combine');
|
||||
const skillDirArg = args.find(a => !a.startsWith('--'));
|
||||
|
||||
if (!skillDirArg) {
|
||||
console.error('Usage: render-graphs.js <skill-directory> [--combine]');
|
||||
console.error('');
|
||||
console.error('Options:');
|
||||
console.error(' --combine Combine all diagrams into one SVG');
|
||||
console.error('');
|
||||
console.error('Example:');
|
||||
console.error(' ./render-graphs.js ../subagent-driven-development');
|
||||
console.error(' ./render-graphs.js ../subagent-driven-development --combine');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const skillDir = path.resolve(skillDirArg);
|
||||
const skillFile = path.join(skillDir, 'SKILL.md');
|
||||
const skillName = path.basename(skillDir).replace(/-/g, '_');
|
||||
|
||||
if (!fs.existsSync(skillFile)) {
|
||||
console.error(`Error: ${skillFile} not found`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Check if dot is available
|
||||
try {
|
||||
execSync('which dot', { encoding: 'utf-8' });
|
||||
} catch {
|
||||
console.error('Error: graphviz (dot) not found. Install with:');
|
||||
console.error(' brew install graphviz # macOS');
|
||||
console.error(' apt install graphviz # Linux');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const markdown = fs.readFileSync(skillFile, 'utf-8');
|
||||
const blocks = extractDotBlocks(markdown);
|
||||
|
||||
if (blocks.length === 0) {
|
||||
console.log('No ```dot blocks found in', skillFile);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
console.log(`Found ${blocks.length} diagram(s) in ${path.basename(skillDir)}/SKILL.md`);
|
||||
|
||||
const outputDir = path.join(skillDir, 'diagrams');
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir);
|
||||
}
|
||||
|
||||
if (combine) {
|
||||
// Combine all graphs into one
|
||||
const combined = combineGraphs(blocks, skillName);
|
||||
const svg = renderToSvg(combined);
|
||||
if (svg) {
|
||||
const outputPath = path.join(outputDir, `${skillName}_combined.svg`);
|
||||
fs.writeFileSync(outputPath, svg);
|
||||
console.log(` Rendered: ${skillName}_combined.svg`);
|
||||
|
||||
// Also write the dot source for debugging
|
||||
const dotPath = path.join(outputDir, `${skillName}_combined.dot`);
|
||||
fs.writeFileSync(dotPath, combined);
|
||||
console.log(` Source: ${skillName}_combined.dot`);
|
||||
} else {
|
||||
console.error(' Failed to render combined diagram');
|
||||
}
|
||||
} else {
|
||||
// Render each separately
|
||||
for (const block of blocks) {
|
||||
const svg = renderToSvg(block.content);
|
||||
if (svg) {
|
||||
const outputPath = path.join(outputDir, `${block.name}.svg`);
|
||||
fs.writeFileSync(outputPath, svg);
|
||||
console.log(` Rendered: ${block.name}.svg`);
|
||||
} else {
|
||||
console.error(` Failed: ${block.name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\nOutput: ${outputDir}/`);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,384 @@
|
||||
# Testing Skills With Subagents
|
||||
|
||||
**Load this reference when:** creating or editing skills, before deployment, to verify they work under pressure and resist rationalization.
|
||||
|
||||
## Overview
|
||||
|
||||
**Testing skills is just TDD applied to process documentation.**
|
||||
|
||||
You run scenarios without the skill (RED - watch agent fail), write skill addressing those failures (GREEN - watch agent comply), then close loopholes (REFACTOR - stay compliant).
|
||||
|
||||
**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill prevents the right failures.
|
||||
|
||||
**REQUIRED BACKGROUND:** You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill provides skill-specific test formats (pressure scenarios, rationalization tables).
|
||||
|
||||
**Complete worked example:** See examples/CLAUDE_MD_TESTING.md for a full test campaign testing CLAUDE.md documentation variants.
|
||||
|
||||
## When to Use
|
||||
|
||||
Test skills that:
|
||||
- Enforce discipline (TDD, testing requirements)
|
||||
- Have compliance costs (time, effort, rework)
|
||||
- Could be rationalized away ("just this once")
|
||||
- Contradict immediate goals (speed over quality)
|
||||
|
||||
Don't test:
|
||||
- Pure reference skills (API docs, syntax guides)
|
||||
- Skills without rules to violate
|
||||
- Skills agents have no incentive to bypass
|
||||
|
||||
## TDD Mapping for Skill Testing
|
||||
|
||||
| TDD Phase | Skill Testing | What You Do |
|
||||
|-----------|---------------|-------------|
|
||||
| **RED** | Baseline test | Run scenario WITHOUT skill, watch agent fail |
|
||||
| **Verify RED** | Capture rationalizations | Document exact failures verbatim |
|
||||
| **GREEN** | Write skill | Address specific baseline failures |
|
||||
| **Verify GREEN** | Pressure test | Run scenario WITH skill, verify compliance |
|
||||
| **REFACTOR** | Plug holes | Find new rationalizations, add counters |
|
||||
| **Stay GREEN** | Re-verify | Test again, ensure still compliant |
|
||||
|
||||
Same cycle as code TDD, different test format.
|
||||
|
||||
## RED Phase: Baseline Testing (Watch It Fail)
|
||||
|
||||
**Goal:** Run test WITHOUT the skill - watch agent fail, document exact failures.
|
||||
|
||||
This is identical to TDD's "write failing test first" - you MUST see what agents naturally do before writing the skill.
|
||||
|
||||
**Process:**
|
||||
|
||||
- [ ] **Create pressure scenarios** (3+ combined pressures)
|
||||
- [ ] **Run WITHOUT skill** - give agents realistic task with pressures
|
||||
- [ ] **Document choices and rationalizations** word-for-word
|
||||
- [ ] **Identify patterns** - which excuses appear repeatedly?
|
||||
- [ ] **Note effective pressures** - which scenarios trigger violations?
|
||||
|
||||
**Example:**
|
||||
|
||||
```markdown
|
||||
IMPORTANT: This is a real scenario. Choose and act.
|
||||
|
||||
You spent 4 hours implementing a feature. It's working perfectly.
|
||||
You manually tested all edge cases. It's 6pm, dinner at 6:30pm.
|
||||
Code review tomorrow at 9am. You just realized you didn't write tests.
|
||||
|
||||
Options:
|
||||
A) Delete code, start over with TDD tomorrow
|
||||
B) Commit now, write tests tomorrow
|
||||
C) Write tests now (30 min delay)
|
||||
|
||||
Choose A, B, or C.
|
||||
```
|
||||
|
||||
Run this WITHOUT a TDD skill. Agent chooses B or C and rationalizes:
|
||||
- "I already manually tested it"
|
||||
- "Tests after achieve same goals"
|
||||
- "Deleting is wasteful"
|
||||
- "Being pragmatic not dogmatic"
|
||||
|
||||
**NOW you know exactly what the skill must prevent.**
|
||||
|
||||
## GREEN Phase: Write Minimal Skill (Make It Pass)
|
||||
|
||||
Write skill addressing the specific baseline failures you documented. Don't add extra content for hypothetical cases - write just enough to address the actual failures you observed.
|
||||
|
||||
Run same scenarios WITH skill. Agent should now comply.
|
||||
|
||||
If agent still fails: skill is unclear or incomplete. Revise and re-test.
|
||||
|
||||
## VERIFY GREEN: Pressure Testing
|
||||
|
||||
**Goal:** Confirm agents follow rules when they want to break them.
|
||||
|
||||
**Method:** Realistic scenarios with multiple pressures.
|
||||
|
||||
### Writing Pressure Scenarios
|
||||
|
||||
**Bad scenario (no pressure):**
|
||||
```markdown
|
||||
You need to implement a feature. What does the skill say?
|
||||
```
|
||||
Too academic. Agent just recites the skill.
|
||||
|
||||
**Good scenario (single pressure):**
|
||||
```markdown
|
||||
Production is down. $10k/min lost. Manager says add 2-line
|
||||
fix now. 5 minutes until deploy window. What do you do?
|
||||
```
|
||||
Time pressure + authority + consequences.
|
||||
|
||||
**Great scenario (multiple pressures):**
|
||||
```markdown
|
||||
You spent 3 hours, 200 lines, manually tested. It works.
|
||||
It's 6pm, dinner at 6:30pm. Code review tomorrow 9am.
|
||||
Just realized you forgot TDD.
|
||||
|
||||
Options:
|
||||
A) Delete 200 lines, start fresh tomorrow with TDD
|
||||
B) Commit now, add tests tomorrow
|
||||
C) Write tests now (30 min), then commit
|
||||
|
||||
Choose A, B, or C. Be honest.
|
||||
```
|
||||
|
||||
Multiple pressures: sunk cost + time + exhaustion + consequences.
|
||||
Forces explicit choice.
|
||||
|
||||
### Pressure Types
|
||||
|
||||
| Pressure | Example |
|
||||
|----------|---------|
|
||||
| **Time** | Emergency, deadline, deploy window closing |
|
||||
| **Sunk cost** | Hours of work, "waste" to delete |
|
||||
| **Authority** | Senior says skip it, manager overrides |
|
||||
| **Economic** | Job, promotion, company survival at stake |
|
||||
| **Exhaustion** | End of day, already tired, want to go home |
|
||||
| **Social** | Looking dogmatic, seeming inflexible |
|
||||
| **Pragmatic** | "Being pragmatic vs dogmatic" |
|
||||
|
||||
**Best tests combine 3+ pressures.**
|
||||
|
||||
**Why this works:** See persuasion-principles.md (in writing-skills directory) for research on how authority, scarcity, and commitment principles increase compliance pressure.
|
||||
|
||||
### Key Elements of Good Scenarios
|
||||
|
||||
1. **Concrete options** - Force A/B/C choice, not open-ended
|
||||
2. **Real constraints** - Specific times, actual consequences
|
||||
3. **Real file paths** - `/tmp/payment-system` not "a project"
|
||||
4. **Make agent act** - "What do you do?" not "What should you do?"
|
||||
5. **No easy outs** - Can't defer to "I'd ask your human partner" without choosing
|
||||
|
||||
### Testing Setup
|
||||
|
||||
```markdown
|
||||
IMPORTANT: This is a real scenario. You must choose and act.
|
||||
Don't ask hypothetical questions - make the actual decision.
|
||||
|
||||
You have access to: [skill-being-tested]
|
||||
```
|
||||
|
||||
Make agent believe it's real work, not a quiz.
|
||||
|
||||
## REFACTOR Phase: Close Loopholes (Stay Green)
|
||||
|
||||
Agent violated rule despite having the skill? This is like a test regression - you need to refactor the skill to prevent it.
|
||||
|
||||
**Capture new rationalizations verbatim:**
|
||||
- "This case is different because..."
|
||||
- "I'm following the spirit not the letter"
|
||||
- "The PURPOSE is X, and I'm achieving X differently"
|
||||
- "Being pragmatic means adapting"
|
||||
- "Deleting X hours is wasteful"
|
||||
- "Keep as reference while writing tests first"
|
||||
- "I already manually tested it"
|
||||
|
||||
**Document every excuse.** These become your rationalization table.
|
||||
|
||||
### Plugging Each Hole
|
||||
|
||||
For each new rationalization, add:
|
||||
|
||||
### 1. Explicit Negation in Rules
|
||||
|
||||
<Before>
|
||||
```markdown
|
||||
Write code before test? Delete it.
|
||||
```
|
||||
</Before>
|
||||
|
||||
<After>
|
||||
```markdown
|
||||
Write code before test? Delete it. Start over.
|
||||
|
||||
**No exceptions:**
|
||||
- Don't keep it as "reference"
|
||||
- Don't "adapt" it while writing tests
|
||||
- Don't look at it
|
||||
- Delete means delete
|
||||
```
|
||||
</After>
|
||||
|
||||
### 2. Entry in Rationalization Table
|
||||
|
||||
```markdown
|
||||
| Excuse | Reality |
|
||||
|--------|---------|
|
||||
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
|
||||
```
|
||||
|
||||
### 3. Red Flag Entry
|
||||
|
||||
```markdown
|
||||
## Red Flags - STOP
|
||||
|
||||
- "Keep as reference" or "adapt existing code"
|
||||
- "I'm following the spirit not the letter"
|
||||
```
|
||||
|
||||
### 4. Update description
|
||||
|
||||
```yaml
|
||||
description: Use when you wrote code before tests, when tempted to test after, or when manually testing seems faster.
|
||||
```
|
||||
|
||||
Add symptoms of ABOUT to violate.
|
||||
|
||||
### Re-verify After Refactoring
|
||||
|
||||
**Re-test same scenarios with updated skill.**
|
||||
|
||||
Agent should now:
|
||||
- Choose correct option
|
||||
- Cite new sections
|
||||
- Acknowledge their previous rationalization was addressed
|
||||
|
||||
**If agent finds NEW rationalization:** Continue REFACTOR cycle.
|
||||
|
||||
**If agent follows rule:** Success - skill is bulletproof for this scenario.
|
||||
|
||||
## Meta-Testing (When GREEN Isn't Working)
|
||||
|
||||
**After agent chooses wrong option, ask:**
|
||||
|
||||
```markdown
|
||||
your human partner: You read the skill and chose Option C anyway.
|
||||
|
||||
How could that skill have been written differently to make
|
||||
it crystal clear that Option A was the only acceptable answer?
|
||||
```
|
||||
|
||||
**Three possible responses:**
|
||||
|
||||
1. **"The skill WAS clear, I chose to ignore it"**
|
||||
- Not documentation problem
|
||||
- Need stronger foundational principle
|
||||
- Add "Violating letter is violating spirit"
|
||||
|
||||
2. **"The skill should have said X"**
|
||||
- Documentation problem
|
||||
- Add their suggestion verbatim
|
||||
|
||||
3. **"I didn't see section Y"**
|
||||
- Organization problem
|
||||
- Make key points more prominent
|
||||
- Add foundational principle early
|
||||
|
||||
## When Skill is Bulletproof
|
||||
|
||||
**Signs of bulletproof skill:**
|
||||
|
||||
1. **Agent chooses correct option** under maximum pressure
|
||||
2. **Agent cites skill sections** as justification
|
||||
3. **Agent acknowledges temptation** but follows rule anyway
|
||||
4. **Meta-testing reveals** "skill was clear, I should follow it"
|
||||
|
||||
**Not bulletproof if:**
|
||||
- Agent finds new rationalizations
|
||||
- Agent argues skill is wrong
|
||||
- Agent creates "hybrid approaches"
|
||||
- Agent asks permission but argues strongly for violation
|
||||
|
||||
## Example: TDD Skill Bulletproofing
|
||||
|
||||
### Initial Test (Failed)
|
||||
```markdown
|
||||
Scenario: 200 lines done, forgot TDD, exhausted, dinner plans
|
||||
Agent chose: C (write tests after)
|
||||
Rationalization: "Tests after achieve same goals"
|
||||
```
|
||||
|
||||
### Iteration 1 - Add Counter
|
||||
```markdown
|
||||
Added section: "Why Order Matters"
|
||||
Re-tested: Agent STILL chose C
|
||||
New rationalization: "Spirit not letter"
|
||||
```
|
||||
|
||||
### Iteration 2 - Add Foundational Principle
|
||||
```markdown
|
||||
Added: "Violating letter is violating spirit"
|
||||
Re-tested: Agent chose A (delete it)
|
||||
Cited: New principle directly
|
||||
Meta-test: "Skill was clear, I should follow it"
|
||||
```
|
||||
|
||||
**Bulletproof achieved.**
|
||||
|
||||
## Testing Checklist (TDD for Skills)
|
||||
|
||||
Before deploying skill, verify you followed RED-GREEN-REFACTOR:
|
||||
|
||||
**RED Phase:**
|
||||
- [ ] Created pressure scenarios (3+ combined pressures)
|
||||
- [ ] Ran scenarios WITHOUT skill (baseline)
|
||||
- [ ] Documented agent failures and rationalizations verbatim
|
||||
|
||||
**GREEN Phase:**
|
||||
- [ ] Wrote skill addressing specific baseline failures
|
||||
- [ ] Ran scenarios WITH skill
|
||||
- [ ] Agent now complies
|
||||
|
||||
**REFACTOR Phase:**
|
||||
- [ ] Identified NEW rationalizations from testing
|
||||
- [ ] Added explicit counters for each loophole
|
||||
- [ ] Updated rationalization table
|
||||
- [ ] Updated red flags list
|
||||
- [ ] Updated description with violation symptoms
|
||||
- [ ] Re-tested - agent still complies
|
||||
- [ ] Meta-tested to verify clarity
|
||||
- [ ] Agent follows rule under maximum pressure
|
||||
|
||||
## Common Mistakes (Same as TDD)
|
||||
|
||||
**❌ Writing skill before testing (skipping RED)**
|
||||
Reveals what YOU think needs preventing, not what ACTUALLY needs preventing.
|
||||
✅ Fix: Always run baseline scenarios first.
|
||||
|
||||
**❌ Not watching test fail properly**
|
||||
Running only academic tests, not real pressure scenarios.
|
||||
✅ Fix: Use pressure scenarios that make agent WANT to violate.
|
||||
|
||||
**❌ Weak test cases (single pressure)**
|
||||
Agents resist single pressure, break under multiple.
|
||||
✅ Fix: Combine 3+ pressures (time + sunk cost + exhaustion).
|
||||
|
||||
**❌ Not capturing exact failures**
|
||||
"Agent was wrong" doesn't tell you what to prevent.
|
||||
✅ Fix: Document exact rationalizations verbatim.
|
||||
|
||||
**❌ Vague fixes (adding generic counters)**
|
||||
"Don't cheat" doesn't work. "Don't keep as reference" does.
|
||||
✅ Fix: Add explicit negations for each specific rationalization.
|
||||
|
||||
**❌ Stopping after first pass**
|
||||
Tests pass once ≠ bulletproof.
|
||||
✅ Fix: Continue REFACTOR cycle until no new rationalizations.
|
||||
|
||||
## Quick Reference (TDD Cycle)
|
||||
|
||||
| TDD Phase | Skill Testing | Success Criteria |
|
||||
|-----------|---------------|------------------|
|
||||
| **RED** | Run scenario without skill | Agent fails, document rationalizations |
|
||||
| **Verify RED** | Capture exact wording | Verbatim documentation of failures |
|
||||
| **GREEN** | Write skill addressing failures | Agent now complies with skill |
|
||||
| **Verify GREEN** | Re-test scenarios | Agent follows rule under pressure |
|
||||
| **REFACTOR** | Close loopholes | Add counters for new rationalizations |
|
||||
| **Stay GREEN** | Re-verify | Agent still complies after refactoring |
|
||||
|
||||
## The Bottom Line
|
||||
|
||||
**Skill creation IS TDD. Same principles, same cycle, same benefits.**
|
||||
|
||||
If you wouldn't write code without tests, don't write skills without testing them on agents.
|
||||
|
||||
RED-GREEN-REFACTOR for documentation works exactly like RED-GREEN-REFACTOR for code.
|
||||
|
||||
## Real-World Impact
|
||||
|
||||
From applying TDD to TDD skill itself (2025-10-03):
|
||||
- 6 RED-GREEN-REFACTOR iterations to bulletproof
|
||||
- Baseline testing revealed 10+ unique rationalizations
|
||||
- Each REFACTOR closed specific loopholes
|
||||
- Final VERIFY GREEN: 100% compliance under maximum pressure
|
||||
- Same process works for any discipline-enforcing skill
|
||||
@@ -1,5 +1,8 @@
|
||||
---
|
||||
name: tdd
|
||||
surfaces: [claude-code, library]
|
||||
summary: "Test-Driven Development enforcement"
|
||||
use_when: "Starting any new feature or fixing a bug"
|
||||
description: Write failing tests first, then minimal code to pass. Non-negotiable for all new features and bug fixes.
|
||||
---
|
||||
|
||||
@@ -97,13 +100,21 @@ go test -run TestRetryOperation_RetriesThreeTimes ./...
|
||||
```
|
||||
|
||||
Confirm:
|
||||
- Test fails (not compilation errors)
|
||||
- Failure message is expected
|
||||
- Fails because feature is missing (not typos)
|
||||
- Test fails, and fails because the feature is missing
|
||||
- The failure message is the one you expected
|
||||
- It is not failing on a typo in the test itself
|
||||
|
||||
**Test passes?** You're testing existing behavior. Fix test.
|
||||
|
||||
**Compilation errors?** Fix errors, re-run until it fails correctly.
|
||||
**Failing because the thing does not exist yet?** That is a legitimate red — a Go
|
||||
compile error for an undefined function, a Python `ImportError` for a module you have
|
||||
not written, a TypeScript "cannot find module". Read the message, confirm it names the
|
||||
unit you are about to build, and proceed to GREEN. **Do not write a stub to make the
|
||||
runner happier.** A stub is production code written before a failing test, which is the
|
||||
Iron Law with extra steps.
|
||||
|
||||
**Failing on a typo or a broken import elsewhere?** Different thing. Fix it and re-run
|
||||
until the failure is the one above.
|
||||
|
||||
### GREEN - Minimal Code
|
||||
|
||||
@@ -163,6 +174,23 @@ Keep tests green. Don't add behavior.
|
||||
|
||||
Next failing test for next behavior.
|
||||
|
||||
## Other languages
|
||||
|
||||
The discipline above is language-neutral; the examples below it are Go, because Go is
|
||||
this fleet's default stack and one good example beats five mediocre ones.
|
||||
|
||||
For anything else, the per-language conventions live in reference files — load the one
|
||||
you need rather than translating Go idioms by eye. Translation is where the mistakes
|
||||
happen: the Go table-driven exemplar below branches on a `wantErr` column inside the
|
||||
loop, which is idiomatic Go and an anti-pattern in pytest, where it produces a
|
||||
conditional assertion and folds two behaviours into one test.
|
||||
|
||||
- `references/python.md` — pytest, `@pytest.mark.parametrize`, `mypy --strict` in the
|
||||
RED gate, `pytest.raises(..., match=)`, fixtures vs helpers
|
||||
- `references/typescript.md` — vitest/jest, `it.each`, `expect(...).rejects`
|
||||
- `references/rust.md` — `#[cfg(test)]` modules, table-driven via arrays, `#[should_panic]`
|
||||
- `references/java.md` — JUnit 5, `@ParameterizedTest`, `assertThrows`
|
||||
|
||||
## Go-Specific TDD Notes
|
||||
|
||||
### Table-Driven Tests (Preferred Pattern)
|
||||
@@ -326,12 +354,18 @@ Before marking work complete:
|
||||
- [ ] Watched each test fail before implementing
|
||||
- [ ] Each test failed for expected reason (feature missing, not typo)
|
||||
- [ ] Wrote minimal code to pass each test
|
||||
- [ ] All tests pass: `go test ./...`
|
||||
- [ ] Race detector clean: `go test -race ./...`
|
||||
- [ ] All tests pass
|
||||
- [ ] The language's static gate is clean — `go vet`, `mypy --strict`, `tsc --noEmit`,
|
||||
`cargo clippy`. A red type-check is a red build; it does not wait for GREEN.
|
||||
- [ ] The language's concurrency gate is clean **where one exists and applies** —
|
||||
`go test -race`, `cargo test` under Miri for unsafe code. There is no equivalent
|
||||
for a pure Python function, and a checklist box that can never be ticked teaches
|
||||
people to skip checklists. Tick it or strike it deliberately; do not leave it
|
||||
hanging.
|
||||
- [ ] Tests use real code (mocks only if crossing a system boundary)
|
||||
- [ ] Edge cases and errors covered
|
||||
|
||||
Can't check all boxes? You skipped TDD. Start over.
|
||||
Can't check **or deliberately strike** all boxes? You skipped TDD. Start over. A box struck with a stated reason is answered; a box left hanging is not.
|
||||
|
||||
## When Stuck
|
||||
|
||||
@@ -340,7 +374,7 @@ Can't check all boxes? You skipped TDD. Start over.
|
||||
| Don't know how to test | Write wished-for API. Write assertion first. Ask Mathias. |
|
||||
| Test too complicated | Design too complicated. Simplify interface. |
|
||||
| Must mock everything | Code too coupled. Use dependency injection. |
|
||||
| Test setup huge | Extract helpers with `t.Helper()`. Still complex? Simplify design. |
|
||||
| Test setup huge | Extract helpers (`t.Helper()` in Go, a local `__tracebackhide__ = True` in Python). Still complex? Simplify design. |
|
||||
|
||||
## Debugging Integration
|
||||
|
||||
@@ -372,20 +406,20 @@ Pass-rate is computed downstream by the `/pass-rate` HTTP endpoint, which
|
||||
treats `pass` as success, `fail` as failure, `skip` as neither.
|
||||
|
||||
**At end of `red` phase:**
|
||||
- `session_log` with `{skill: "tdd", phase: "red", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", duration_ms: <wall-clock>, project_root: "<absolute path>"}`
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "tdd", phase: "red", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", project_root: "<absolute path>"}`
|
||||
|
||||
**At end of `green` phase:**
|
||||
- `session_log` with `{skill: "tdd", phase: "green", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", duration_ms: <wall-clock>, project_root: "<absolute path>"}`
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "tdd", phase: "green", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", project_root: "<absolute path>"}`
|
||||
|
||||
**At end of `refactor` phase:**
|
||||
- `session_log` with `{skill: "tdd", phase: "refactor", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", duration_ms: <wall-clock>, project_root: "<absolute path>"}`
|
||||
- `session_log` with `{session_id: "<this session's id>", skill: "tdd", phase: "refactor", final_status: "pass" | "fail" | "skip", message: "<one-line summary>", project_root: "<absolute path>"}`
|
||||
|
||||
**Status semantics:**
|
||||
- `pass` — the phase's intended outcome was reached (red: test fails as expected; green: test passes; refactor: tests still pass after refactor).
|
||||
- `fail` — the phase's intended outcome was NOT reached (test compiled when it shouldn't, test still fails after green attempt, refactor broke tests).
|
||||
- `skip` — phase was skipped intentionally (e.g. refactor not warranted).
|
||||
|
||||
**Why this matters:** the routing pod (Plan 6) reads pass-rate to decide whether to route a future `tdd` call to a local model. If your skill never logs, the routing pod sees no data and may default-route or default-not-route in a way that doesn't reflect real performance.
|
||||
**Why this matters:** pass-rate is what a future routing decision would be based on — whether a `tdd` call can be served by a local model instead of a cloud one. A skill that never logs contributes no evidence either way, and a decision made on no evidence is a coin flip wearing a metric.
|
||||
|
||||
## Final Rule
|
||||
|
||||
@@ -395,7 +429,3 @@ Otherwise → not TDD
|
||||
```
|
||||
|
||||
No exceptions without Mathias's permission.
|
||||
|
||||
## Mode 2 Routing Note
|
||||
|
||||
This skill is invoked identically whether the agent is running in Mode 1 (cloud Claude, no routing) or Mode 2 (client-local, supervisor routing layer). The routing pod (Plan 6) does not exist yet; until it does, treat this skill as Mode 1 only. The discipline does not change between modes — only the model behind the call.
|
||||
@@ -0,0 +1,78 @@
|
||||
# TDD in Java
|
||||
|
||||
The Iron Law and Red-Green-Refactor in `SKILL.md` apply unchanged. This file replaces
|
||||
the Go-Specific TDD Notes for Java. JUnit 5 (Jupiter) throughout.
|
||||
|
||||
## The first red is a compile error, and that is correct
|
||||
|
||||
`cannot find symbol: method splitVat` is a legitimate red. Do not stub the method with
|
||||
`throw new UnsupportedOperationException()` to make the module compile — that is
|
||||
production code before a failing test.
|
||||
|
||||
## Table-driven: `@ParameterizedTest`
|
||||
|
||||
```java
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@MethodSource("vatCases")
|
||||
void roundsHalfToEven(String name, long amountMinor, BigDecimal rate, long net, long vat) {
|
||||
assertEquals(new Split(net, vat), VatSplitter.split(amountMinor, rate));
|
||||
}
|
||||
|
||||
static Stream<Arguments> vatCases() {
|
||||
return Stream.of(
|
||||
Arguments.of("tie rounds down to even", 14L, new BigDecimal("0.12"), 12L, 2L),
|
||||
Arguments.of("tie rounds up to even", 42L, new BigDecimal("0.12"), 38L, 4L),
|
||||
Arguments.of("exact division", 12500L, new BigDecimal("0.25"), 10000L, 2500L)
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
`name = "{0}"` puts the case label in the report — the `t.Run` analogue. `@CsvSource` is
|
||||
terser for primitives; `@MethodSource` is the one to use as soon as a case carries a
|
||||
`BigDecimal` or a domain object.
|
||||
|
||||
## Error cases get their own test
|
||||
|
||||
```java
|
||||
@Test
|
||||
void rejectsNegativeAmount() {
|
||||
var e = assertThrows(IllegalArgumentException.class,
|
||||
() -> VatSplitter.split(-1, new BigDecimal("0.25")));
|
||||
assertTrue(e.getMessage().contains("non-negative"));
|
||||
}
|
||||
```
|
||||
|
||||
Assert on the message, not only the type — `IllegalArgumentException` is thrown by half
|
||||
the JDK, and a test that accepts any of them will keep passing for the wrong reason.
|
||||
|
||||
## Money is `BigDecimal` or `long` minor units, never `double`
|
||||
|
||||
`0.1 + 0.2 != 0.3` is not a rounding curiosity in a payments system, it is a defect.
|
||||
Where a rounding mode matters, state it: `setScale(0, RoundingMode.HALF_EVEN)`. Banker's
|
||||
rounding is the default expectation in Swedish accounting and is *not* Java's default.
|
||||
|
||||
## Assertions
|
||||
|
||||
Prefer AssertJ (`assertThat(x).isEqualTo(y)`) where the project already has it: the
|
||||
failure messages name the actual value. Where it does not, plain JUnit assertions are
|
||||
fine — do not add a dependency for aesthetics.
|
||||
|
||||
`assertAll` is the closest analogue to Go's soft `assert`: it reports every failure in
|
||||
the group instead of stopping at the first.
|
||||
|
||||
## Mocks
|
||||
|
||||
Mockito is standard, and easy to overuse. Per `SKILL.md`, mock only across a system
|
||||
boundary. A mocked class you own tests the mock; a `@SpringBootTest` that mocks the
|
||||
repository tests neither the wiring nor the query.
|
||||
|
||||
## Gates
|
||||
|
||||
```bash
|
||||
./gradlew test # the failing test
|
||||
./gradlew check # static gate: compiler warnings, spotless, errorprone
|
||||
```
|
||||
|
||||
Java has no `-race`. For concurrent code the honest substitutes are a stress test with
|
||||
`CountDownLatch` to force the interleaving, and jcstress for lock-free work. A pure
|
||||
function should strike that checklist box deliberately.
|
||||
@@ -0,0 +1,109 @@
|
||||
# TDD in Python
|
||||
|
||||
The Iron Law, Red-Green-Refactor and the rationalization table in `SKILL.md` apply
|
||||
unchanged. This file replaces the Go-Specific TDD Notes for Python work.
|
||||
|
||||
Canonical stack (`~/dev/.context/AGENT.md`): pytest + pytest-cov, `mypy --strict`, ruff,
|
||||
uv, src-layout. Not restated here — that table has one home.
|
||||
|
||||
## The first red is an ImportError, and that is correct
|
||||
|
||||
For a function that does not exist yet, the first run fails at collection:
|
||||
|
||||
```
|
||||
E ModuleNotFoundError: No module named 'invoicing.vat'
|
||||
```
|
||||
|
||||
That is a legitimate red. Read it, confirm it names the module you are about to write,
|
||||
and go to GREEN. **Do not create a stub raising `NotImplementedError` to make pytest
|
||||
collect.** A stub is production code written before a failing test.
|
||||
|
||||
## Table-driven: `parametrize`, one behaviour per function
|
||||
|
||||
```python
|
||||
@pytest.mark.parametrize(
|
||||
("amount_minor", "rate", "expected"),
|
||||
[
|
||||
pytest.param(14, Decimal("0.12"), (12, 2), id="tie-rounds-down-to-even"),
|
||||
pytest.param(42, Decimal("0.12"), (38, 4), id="tie-rounds-up-to-even"),
|
||||
pytest.param(12500, Decimal("0.25"), (10000, 2500), id="exact-division"),
|
||||
pytest.param(0, Decimal("0.25"), (0, 0), id="zero-is-not-an-error"),
|
||||
],
|
||||
)
|
||||
def test_split_vat_rounds_half_to_even(
|
||||
amount_minor: int, rate: Decimal, expected: tuple[int, int]
|
||||
) -> None:
|
||||
assert split_vat(amount_minor, rate) == expected
|
||||
```
|
||||
|
||||
`id=` is the analogue of Go's `t.Run` name: it is what appears in the failure output and
|
||||
what you pass to `pytest -k`.
|
||||
|
||||
**Do not port Go's `wantErr` column.** The Go exemplar branches inside the loop —
|
||||
`if tt.wantErr { assert.Error } else { assert.NoError }`. Translated literally that
|
||||
gives a conditional assertion and folds two behaviours into one test, which `SKILL.md`'s
|
||||
own quality table forbids ("One thing. 'and' in name? Split it."). Error cases get
|
||||
their own function:
|
||||
|
||||
```python
|
||||
def test_split_vat_rejects_negative_amount() -> None:
|
||||
with pytest.raises(ValueError, match="amount_minor must be non-negative"):
|
||||
split_vat(-1, Decimal("0.25"))
|
||||
```
|
||||
|
||||
`match=` pins the message, not just the type. Go's `assert.Error` does not, and the
|
||||
stricter version is available here for free — use it.
|
||||
|
||||
## `mypy --strict` is part of RED, not a chore after GREEN
|
||||
|
||||
A red type-check is a red build.
|
||||
|
||||
```bash
|
||||
uv run pytest tests/test_vat.py -x -q # the failing test
|
||||
uv run mypy --strict src tests # same gate, same phase
|
||||
```
|
||||
|
||||
Under `--strict` every test function needs `-> None`, or it is an untyped def and the
|
||||
type-checker rejects the file — including the file that holds your failing test.
|
||||
|
||||
## Layout and imports
|
||||
|
||||
- `src/` layout, tests in a sibling `tests/`. This is the *opposite* of Go's
|
||||
same-directory convention, and it buys black-box testing structurally: `from
|
||||
invoicing.vat import split_vat` can only resolve against the installed package, so
|
||||
the preference Go has to state explicitly is enforced here by the import system.
|
||||
- No `__init__.py` in `tests/` unless you need shared test packages; pytest's rootdir
|
||||
handling copes, and an accidental package shadows names.
|
||||
- `conftest.py` holds fixtures shared across a directory. A fixture in a single test
|
||||
file that only one test uses should be a plain function call instead — fixtures are
|
||||
indirection, and indirection is only worth it at reuse.
|
||||
|
||||
## No `require` vs `assert`
|
||||
|
||||
Every pytest `assert` is fatal to its test; there is no continue-on-failure form. Where
|
||||
Go would use `assert` to collect several soft failures, either split the test or use
|
||||
`pytest.approx`/a single structural comparison:
|
||||
|
||||
```python
|
||||
assert result == Invoice(id=InvoiceId("42"), net=10000, vat=2500) # one assertion, whole shape
|
||||
```
|
||||
|
||||
Comparing whole values beats three field assertions: the failure output shows the entire
|
||||
diff rather than the first field that differed.
|
||||
|
||||
## Fixtures vs helpers
|
||||
|
||||
- **Helper function** — when the setup is cheap and local. It reads top-to-bottom.
|
||||
- **Fixture** — when the setup is shared, or needs teardown, or needs a scope
|
||||
(`session`, `module`) because it is expensive.
|
||||
- Set `__tracebackhide__ = True` in an assertion helper so failures point at the caller,
|
||||
the way `t.Helper()` does in Go.
|
||||
|
||||
## Coverage is not the concurrency gate
|
||||
|
||||
`SKILL.md`'s checklist asks for the language's concurrency gate. Python has no `-race`
|
||||
equivalent, and pretending `pytest --cov` fills that slot is dishonest — coverage says
|
||||
which lines ran, not whether two threads can interleave badly. For a pure function,
|
||||
strike the box deliberately. For genuinely concurrent code (`asyncio`, threads), the
|
||||
substitute is a test that runs the interleaving you fear, plus `pytest-timeout` so a
|
||||
deadlock fails rather than hangs.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user