From 2d05b63edcfbae7c0a16e9d13397c5e726885f79 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 15:38:20 -0700 Subject: [PATCH 001/198] fix(codex): suppress SessionStart hook auto-discovery with empty hooks object MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex auto-discovers a plugin's hooks/hooks.json whenever the Codex manifest has no `hooks` field: load_plugin_hooks falls back to a hardcoded DEFAULT_HOOKS_CONFIG_FILE = "hooks/hooks.json" and registers it. hooks/hooks.json is the Claude Code SessionStart hook, it is tracked in this repo, and the Codex marketplace installs the whole repo root (source url "./"), so the fallback re-registered the SessionStart hook and its install-time trust prompt on Codex. Removing the Codex hook file and the manifest `hooks` pointer (commit "Remove Codex hooks") did not disable the hook on Codex — it removed the explicit declaration that was overriding the fallback, so the fallback took over and found the Claude hooks/hooks.json. Declare an empty inline hooks object ({}) in .codex-plugin/plugin.json. It parses as an empty inline hook set and stops Codex reaching the auto-discovery fallback. An absent field, an empty array ([]), and an empty inline list all collapse back to the fallback, so the value must be exactly {}. Update the test to assert the manifest declares hooks: {} (and that hooks/hooks.json exists, which is what makes the declaration necessary), replacing the prior assertion that the field was absent — which passed while the hook was still being auto-discovered. Co-Authored-By: Claude Opus 4.8 (1M context) --- .codex-plugin/plugin.json | 1 + tests/codex/test-marketplace-manifest.sh | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index a49177783..812e72c70 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -21,6 +21,7 @@ "workflow" ], "skills": "./skills/", + "hooks": {}, "interface": { "displayName": "Superpowers", "shortDescription": "Planning, TDD, debugging, and delivery workflows for coding agents", diff --git a/tests/codex/test-marketplace-manifest.sh b/tests/codex/test-marketplace-manifest.sh index 3045cde67..4301a06ee 100755 --- a/tests/codex/test-marketplace-manifest.sh +++ b/tests/codex/test-marketplace-manifest.sh @@ -51,10 +51,25 @@ if not plugin_manifest.exists(): manifest = json.loads(plugin_manifest.read_text(encoding="utf-8")) assert_equal(manifest.get("name"), plugin.get("name"), "plugin manifest name") + +# Codex auto-discovers a plugin's hooks/hooks.json whenever the Codex manifest +# has no `hooks` field: load_plugin_hooks falls back to a hardcoded +# DEFAULT_HOOKS_CONFIG_FILE = "hooks/hooks.json" and registers it. That file is +# the Claude Code SessionStart hook, it is tracked in this repo, and this +# marketplace installs the whole repo root (source url "./"), so on Codex the +# fallback re-registers the SessionStart hook and its install-time trust prompt. +# Declaring an empty inline hooks object ({}) parses as an empty inline hook set +# and suppresses the auto-discovery. An absent field, an empty array ([]), and +# an empty inline list all collapse back to the fallback, so the value must be +# exactly an empty object. +hooks_config = repo_root / "hooks" / "hooks.json" +if not hooks_config.exists(): + raise AssertionError("hooks/hooks.json must exist (Claude Code SessionStart hook)") + assert_equal( manifest.get("hooks"), - None, - "Codex manifest ships no hooks", + {}, + "Codex manifest must declare empty hooks {} to suppress hooks/hooks.json auto-discovery", ) print("Codex marketplace manifest looks good") From 3bb0a3faa377b04976f85728c28d801034a3140d Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 13:41:12 -0700 Subject: [PATCH 002/198] Add Codex portal package script --- scripts/package-codex-plugin.sh | 256 +++++++++++++++++++++++ tests/codex/test-package-codex-plugin.sh | 133 ++++++++++++ 2 files changed, 389 insertions(+) create mode 100755 scripts/package-codex-plugin.sh create mode 100755 tests/codex/test-package-codex-plugin.sh diff --git a/scripts/package-codex-plugin.sh b/scripts/package-codex-plugin.sh new file mode 100755 index 000000000..667b7d28e --- /dev/null +++ b/scripts/package-codex-plugin.sh @@ -0,0 +1,256 @@ +#!/usr/bin/env bash +# +# Package the Superpowers Codex plugin as a rootless .tar.gz for portal upload. +# +# The Codex portal artifact differs from the old openai/plugins sync flow: +# it is a standalone archive, but it still needs the OpenAI-owned +# skills/*/agents/openai.yaml metadata that used to be preserved from the +# destination plugin repo. Seed that metadata from a prior official package. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + +REF="HEAD" +OUTPUT="" +METADATA_SOURCE="" +ALLOW_DIRTY=0 +KEEP_STAGE=0 + +usage() { + cat <<'EOF' +Usage: + scripts/package-codex-plugin.sh [options] + +Options: + --output PATH Write archive to PATH. + Default: ../_tmp/sup-codex-packaging/superpowers-VERSION.tar.gz + --metadata-source PATH Prior official package directory or .tar.gz used to + seed skills/*/agents/openai.yaml. + Default: ../_tmp/sup-codex-packaging/superpowers, + falling back to ../_tmp/sup-codex-packaging/superpowers.tar.gz + --ref REF Git ref to package. Default: HEAD. + --allow-dirty Permit a dirty working tree. The archive still uses --ref. + --keep-stage Print and keep the temporary staging directory. + -h, --help Show this help. + +The archive is rootless: .codex-plugin/, assets/, skills/, README.md, LICENSE, +and CODE_OF_CONDUCT.md sit at the tar root. Source-only repo files, hooks, tests, +docs, and other harness manifests are intentionally not shipped. +EOF +} + +die() { + echo "ERROR: $*" >&2 + exit 1 +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --output) + [[ $# -ge 2 ]] || die "--output requires a path" + OUTPUT="$2" + shift 2 + ;; + --metadata-source) + [[ $# -ge 2 ]] || die "--metadata-source requires a path" + METADATA_SOURCE="$2" + shift 2 + ;; + --ref) + [[ $# -ge 2 ]] || die "--ref requires a value" + REF="$2" + shift 2 + ;; + --allow-dirty) + ALLOW_DIRTY=1 + shift + ;; + --keep-stage) + KEEP_STAGE=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + echo "Unknown arg: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +command -v git >/dev/null || die "git not found in PATH" +command -v jq >/dev/null || die "jq not found in PATH" +command -v tar >/dev/null || die "tar not found in PATH" +command -v gzip >/dev/null || die "gzip not found in PATH" +command -v shasum >/dev/null || die "shasum not found in PATH" + +[[ -d "$REPO_ROOT/.git" ]] || die "repo root is not a git checkout: $REPO_ROOT" +git -C "$REPO_ROOT" rev-parse --verify "$REF^{commit}" >/dev/null || + die "git ref does not resolve to a commit: $REF" + +if [[ "$ALLOW_DIRTY" -ne 1 ]]; then + dirty_status="$(git -C "$REPO_ROOT" status --porcelain --untracked-files=all)" + if [[ -n "$dirty_status" ]]; then + echo "Working tree has uncommitted changes:" >&2 + printf '%s\n' "$dirty_status" | sed 's/^/ /' >&2 + die "commit or stash changes first, or pass --allow-dirty to package $REF anyway" + fi +fi + +if [[ -z "$METADATA_SOURCE" ]]; then + if [[ -d "$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers" ]]; then + METADATA_SOURCE="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers" + elif [[ -f "$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers.tar.gz" ]]; then + METADATA_SOURCE="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers.tar.gz" + else + die "no metadata source found; pass --metadata-source " + fi +fi + +WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/superpowers-codex-package.XXXXXX")" +STAGE="$WORK_DIR/payload" +METADATA_WORK="$WORK_DIR/metadata" +TAR_LIST="$WORK_DIR/tar-list" + +cleanup() { + if [[ "$KEEP_STAGE" -eq 1 ]]; then + echo "Keeping staging directory: $WORK_DIR" >&2 + else + rm -rf "$WORK_DIR" + fi +} +trap cleanup EXIT + +mkdir -p "$STAGE" "$METADATA_WORK" + +metadata_root_from_dir() { + local candidate="$1" + local nested + + if [[ -d "$candidate/skills" ]]; then + printf '%s\n' "$candidate" + return 0 + fi + + nested="$(find "$candidate" -mindepth 2 -maxdepth 2 -type d -name skills -print | head -n 1)" + if [[ -n "$nested" ]]; then + dirname "$nested" + return 0 + fi + + return 1 +} + +prepare_metadata_root() { + local source="$1" + local root + + if [[ -d "$source" ]]; then + root="$(cd "$source" && pwd)" + elif [[ -f "$source" ]]; then + case "$source" in + *.tar.gz|*.tgz) + tar -xzf "$source" -C "$METADATA_WORK" + root="$METADATA_WORK" + ;; + *) + die "metadata source must be a directory or .tar.gz: $source" + ;; + esac + else + die "metadata source does not exist: $source" + fi + + metadata_root_from_dir "$root" || + die "metadata source does not contain a skills/ directory: $source" +} + +METADATA_ROOT="$(prepare_metadata_root "$METADATA_SOURCE")" + +git -C "$REPO_ROOT" archive --format=tar "$REF" -- \ + .codex-plugin \ + CODE_OF_CONDUCT.md \ + LICENSE \ + README.md \ + assets \ + skills \ + | tar -xf - -C "$STAGE" + +VERSION="$(jq -r '.version // empty' "$STAGE/.codex-plugin/plugin.json")" +[[ -n "$VERSION" ]] || die "could not read version from .codex-plugin/plugin.json" + +if jq -e 'has("hooks")' "$STAGE/.codex-plugin/plugin.json" >/dev/null; then + die "Codex manifest must not declare hooks for the portal package" +fi + +if [[ -z "$OUTPUT" ]]; then + OUTPUT="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers-$VERSION.tar.gz" +fi +mkdir -p "$(dirname "$OUTPUT")" +OUTPUT="$(cd "$(dirname "$OUTPUT")" && pwd)/$(basename "$OUTPUT")" + +missing_metadata=0 +while IFS= read -r skill_dir; do + skill_name="${skill_dir##*/}" + metadata_file="$METADATA_ROOT/skills/$skill_name/agents/openai.yaml" + + if [[ ! -f "$metadata_file" ]]; then + echo "Missing OpenAI agent metadata for skill: $skill_name" >&2 + missing_metadata=1 + continue + fi + + mkdir -p "$skill_dir/agents" + cp "$metadata_file" "$skill_dir/agents/openai.yaml" +done < <(find "$STAGE/skills" -mindepth 1 -maxdepth 1 -type d -print | sort) + +if [[ "$missing_metadata" -ne 0 ]]; then + die "metadata source is incomplete" +fi + +skill_count="$(find "$STAGE/skills" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')" +metadata_count="$(find "$STAGE/skills" -path '*/agents/openai.yaml' -type f | wc -l | tr -d ' ')" +[[ "$skill_count" == "$metadata_count" ]] || + die "metadata count mismatch: $metadata_count metadata files for $skill_count skills" + +# Match the prior official archive's deterministic tar entry metadata. +TZ=UTC find "$STAGE" -exec touch -t 197001010000 {} + + +( + cd "$STAGE" + { + find . -mindepth 1 -type d | sed 's#^\./##' | LC_ALL=C sort + find . -mindepth 1 -type f | sed 's#^\./##' | LC_ALL=C sort + } >"$TAR_LIST" + + rm -f "$OUTPUT" + COPYFILE_DISABLE=1 tar -cnf - --format ustar --uid 0 --gid 0 --uname '' --gname '' -T "$TAR_LIST" | + gzip -9n >"$OUTPUT" +) + +if command -v xattr >/dev/null 2>&1; then + xattr -c "$OUTPUT" 2>/dev/null || true +fi + +unexpected_paths="$( + tar -tzf "$OUTPUT" | + grep -E '(^superpowers/|^\.agents/|^hooks/|package\.json$|^\.git|^\.pytest_cache|^\.ruff_cache|^scripts/|^tests/|^docs/|^evals/|^lib/|^\.claude|^\.cursor|^\.kimi|^\.opencode|^\.pi|^AGENTS\.md$|^CLAUDE\.md$|^GEMINI\.md$|^RELEASE-NOTES\.md$|^CHANGELOG\.md$)' || true +)" +if [[ -n "$unexpected_paths" ]]; then + printf '%s\n' "$unexpected_paths" | sed 's/^/ /' >&2 + die "archive contains source-only paths" +fi + +entry_count="$(tar -tzf "$OUTPUT" | wc -l | tr -d ' ')" +checksum="$(shasum -a 256 "$OUTPUT" | awk '{print $1}')" + +echo "Archive: $OUTPUT" +echo "Version: $VERSION" +echo "Entries: $entry_count" +echo "Skills: $skill_count" +echo "SHA-256: $checksum" diff --git a/tests/codex/test-package-codex-plugin.sh b/tests/codex/test-package-codex-plugin.sh new file mode 100755 index 000000000..804568d1c --- /dev/null +++ b/tests/codex/test-package-codex-plugin.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +SCRIPT_UNDER_TEST="$REPO_ROOT/scripts/package-codex-plugin.sh" + +FAILURES=0 +TEST_ROOT="$(mktemp -d)" + +cleanup() { + rm -rf "$TEST_ROOT" +} +trap cleanup EXIT + +pass() { + echo " [PASS] $1" +} + +fail() { + echo " [FAIL] $1" + FAILURES=$((FAILURES + 1)) +} + +assert_equals() { + local actual="$1" + local expected="$2" + local description="$3" + + if [[ "$actual" == "$expected" ]]; then + pass "$description" + else + fail "$description" + echo " expected: $expected" + echo " actual: $actual" + fi +} + +assert_contains() { + local haystack="$1" + local needle="$2" + local description="$3" + + if printf '%s' "$haystack" | grep -Fq -- "$needle"; then + pass "$description" + else + fail "$description" + echo " expected to find: $needle" + fi +} + +assert_not_matches() { + local haystack="$1" + local pattern="$2" + local description="$3" + + if printf '%s' "$haystack" | grep -Eq -- "$pattern"; then + fail "$description" + echo " did not expect to match: $pattern" + else + pass "$description" + fi +} + +write_metadata_fixture() { + local destination="$1" + local skill + + while IFS= read -r skill; do + mkdir -p "$destination/skills/$skill/agents" + cat >"$destination/skills/$skill/agents/openai.yaml" <&1)"; then + pass "package script exits successfully" +else + fail "package script exits successfully" + printf '%s\n' "$output" | sed 's/^/ /' +fi + +if [[ -f "$archive" ]]; then + pass "package script writes archive" +else + fail "package script writes archive" +fi + +assert_contains "$output" "Archive:" "reports archive path" +assert_contains "$output" "SHA-256:" "reports archive checksum" + +mkdir -p "$extracted" +tar -xzf "$archive" -C "$extracted" + +archive_paths="$(tar -tzf "$archive" | sort)" +unexpected_pattern='(^superpowers/|^\.agents/|^hooks/|package\.json$|^\.git|^\.pytest_cache|^\.ruff_cache|^scripts/|^tests/|^docs/|^evals/|^lib/|^\.claude|^\.cursor|^\.kimi|^\.opencode|^\.pi|^AGENTS\.md$|^CLAUDE\.md$|^GEMINI\.md$|^RELEASE-NOTES\.md$|^CHANGELOG\.md$)' +assert_not_matches "$archive_paths" "$unexpected_pattern" "archive excludes source-only paths" +assert_contains "$archive_paths" ".codex-plugin/plugin.json" "archive includes Codex manifest" +assert_contains "$archive_paths" "skills/brainstorming/SKILL.md" "archive includes skills" +assert_contains "$archive_paths" "skills/brainstorming/agents/openai.yaml" "archive includes OpenAI skill metadata" +assert_contains "$archive_paths" "assets/app-icon.png" "archive includes app icon" +assert_contains "$archive_paths" "assets/superpowers-small.svg" "archive includes composer icon" + +manifest_summary="$(tar -xOf "$archive" .codex-plugin/plugin.json | python3 -c 'import json,sys; data=json.load(sys.stdin); print("\t".join([data["name"], data["version"], data["skills"], str(data.get("hooks"))]))')" +expected_version="$(python3 -c 'import json; print(json.load(open("'"$REPO_ROOT"'/.codex-plugin/plugin.json"))["version"])')" +assert_equals "$manifest_summary" "superpowers $expected_version ./skills/ None" "archive manifest is current and hook-free" + +skill_count="$(find "$extracted/skills" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')" +metadata_count="$(find "$extracted/skills" -path '*/agents/openai.yaml' -type f | wc -l | tr -d ' ')" +assert_equals "$metadata_count" "$skill_count" "every packaged skill has OpenAI metadata" + +task_brief_mode="$(tar -tzvf "$archive" skills/subagent-driven-development/scripts/task-brief | awk '{print $1}')" +assert_equals "$task_brief_mode" "-rwxr-xr-x" "archive preserves executable script mode" + +metadata_times="$(tar -tzvf "$archive" | awk '{print $6, $7, $8}' | sort -u)" +assert_equals "$metadata_times" "Dec 31 1969" "archive normalizes entry timestamps" + +if [[ "$FAILURES" -eq 0 ]]; then + echo "All Codex package archive tests passed" +else + echo "$FAILURES Codex package archive test(s) failed" + exit 1 +fi From 371a26cf99a35dd3e367dd421d7f0f5b37183418 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 13:45:54 -0700 Subject: [PATCH 003/198] Harden Codex package script checks --- scripts/package-codex-plugin.sh | 4 +- tests/codex/test-package-codex-plugin.sh | 55 ++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/scripts/package-codex-plugin.sh b/scripts/package-codex-plugin.sh index 667b7d28e..60be05d51 100755 --- a/scripts/package-codex-plugin.sh +++ b/scripts/package-codex-plugin.sh @@ -137,7 +137,7 @@ metadata_root_from_dir() { return 0 fi - nested="$(find "$candidate" -mindepth 2 -maxdepth 2 -type d -name skills -print | head -n 1)" + nested="$(find "$candidate" -mindepth 2 -maxdepth 2 -type d -name skills -print -quit)" if [[ -n "$nested" ]]; then dirname "$nested" return 0 @@ -229,7 +229,7 @@ TZ=UTC find "$STAGE" -exec touch -t 197001010000 {} + } >"$TAR_LIST" rm -f "$OUTPUT" - COPYFILE_DISABLE=1 tar -cnf - --format ustar --uid 0 --gid 0 --uname '' --gname '' -T "$TAR_LIST" | + COPYFILE_DISABLE=1 tar -cf - --no-recursion --format ustar --uid 0 --gid 0 --uname '' --gname '' -T "$TAR_LIST" | gzip -9n >"$OUTPUT" ) diff --git a/tests/codex/test-package-codex-plugin.sh b/tests/codex/test-package-codex-plugin.sh index 804568d1c..50be9ba7f 100755 --- a/tests/codex/test-package-codex-plugin.sh +++ b/tests/codex/test-package-codex-plugin.sh @@ -125,6 +125,61 @@ assert_equals "$task_brief_mode" "-rwxr-xr-x" "archive preserves executable scri metadata_times="$(tar -tzvf "$archive" | awk '{print $6, $7, $8}' | sort -u)" assert_equals "$metadata_times" "Dec 31 1969" "archive normalizes entry timestamps" +metadata_archive="$TEST_ROOT/metadata-source.tar.gz" +archive_from_tar_source="$TEST_ROOT/superpowers-from-tar-source.tar.gz" +( + cd "$metadata_source" + tar -czf "$metadata_archive" . +) + +if output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_archive" --output "$archive_from_tar_source" 2>&1)"; then + pass "package script accepts tarball metadata source" +else + fail "package script accepts tarball metadata source" + printf '%s\n' "$output" | sed 's/^/ /' +fi + +if cmp -s "$archive" "$archive_from_tar_source"; then + pass "tarball metadata source produces identical archive" +else + fail "tarball metadata source produces identical archive" +fi + +incomplete_metadata="$TEST_ROOT/incomplete-metadata" +mkdir -p "$incomplete_metadata/skills/brainstorming/agents" +cp "$metadata_source/skills/brainstorming/agents/openai.yaml" \ + "$incomplete_metadata/skills/brainstorming/agents/openai.yaml" + +set +e +missing_output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$incomplete_metadata" --output "$TEST_ROOT/missing.tar.gz" 2>&1)" +missing_status=$? +set -e +if [[ "$missing_status" -ne 0 ]]; then + pass "package script rejects incomplete metadata source" +else + fail "package script rejects incomplete metadata source" +fi +assert_contains "$missing_output" "ERROR: metadata source is incomplete" "incomplete metadata reports clear error" + +dirty_repo="$TEST_ROOT/dirty-repo" +git clone -q --no-local "$REPO_ROOT" "$dirty_repo" +printf '\n# dirty fixture\n' >>"$dirty_repo/README.md" +set +e +dirty_output="$( + cd "$dirty_repo" + scripts/package-codex-plugin.sh \ + --metadata-source "$metadata_source" \ + --output "$TEST_ROOT/dirty.tar.gz" 2>&1 +)" +dirty_status=$? +set -e +if [[ "$dirty_status" -ne 0 ]]; then + pass "package script rejects dirty worktree by default" +else + fail "package script rejects dirty worktree by default" +fi +assert_contains "$dirty_output" "Working tree has uncommitted changes:" "dirty worktree reports changed files" + if [[ "$FAILURES" -eq 0 ]]; then echo "All Codex package archive tests passed" else From 6752471ad9887fd436ea95ae4f9a61ab29a2e1c1 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 14:08:40 -0700 Subject: [PATCH 004/198] Default Codex portal package to zip --- scripts/package-codex-plugin.sh | 128 +++++++++++++++++++---- tests/codex/test-package-codex-plugin.sh | 123 ++++++++++++++++++++-- 2 files changed, 221 insertions(+), 30 deletions(-) diff --git a/scripts/package-codex-plugin.sh b/scripts/package-codex-plugin.sh index 60be05d51..008644edf 100755 --- a/scripts/package-codex-plugin.sh +++ b/scripts/package-codex-plugin.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # -# Package the Superpowers Codex plugin as a rootless .tar.gz for portal upload. +# Package the Superpowers Codex plugin as a rootless archive for portal upload. # # The Codex portal artifact differs from the old openai/plugins sync flow: # it is a standalone archive, but it still needs the OpenAI-owned @@ -14,6 +14,7 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" REF="HEAD" OUTPUT="" +FORMAT="" METADATA_SOURCE="" ALLOW_DIRTY=0 KEEP_STAGE=0 @@ -25,18 +26,21 @@ Usage: Options: --output PATH Write archive to PATH. - Default: ../_tmp/sup-codex-packaging/superpowers-VERSION.tar.gz - --metadata-source PATH Prior official package directory or .tar.gz used to + Default: ../_tmp/sup-codex-packaging/superpowers-VERSION.zip + --format FORMAT Archive format: zip or tar.gz. Default: zip. + If --output ends in .zip, .tar.gz, or .tgz, that + extension is used when --format is omitted. + --metadata-source PATH Prior official package directory, .zip, or .tar.gz used to seed skills/*/agents/openai.yaml. Default: ../_tmp/sup-codex-packaging/superpowers, - falling back to ../_tmp/sup-codex-packaging/superpowers.tar.gz + falling back to superpowers.zip, then superpowers.tar.gz --ref REF Git ref to package. Default: HEAD. --allow-dirty Permit a dirty working tree. The archive still uses --ref. --keep-stage Print and keep the temporary staging directory. -h, --help Show this help. The archive is rootless: .codex-plugin/, assets/, skills/, README.md, LICENSE, -and CODE_OF_CONDUCT.md sit at the tar root. Source-only repo files, hooks, tests, +and CODE_OF_CONDUCT.md sit at the archive root. Source-only repo files, hooks, tests, docs, and other harness manifests are intentionally not shipped. EOF } @@ -53,6 +57,21 @@ while [[ $# -gt 0 ]]; do OUTPUT="$2" shift 2 ;; + --format) + [[ $# -ge 2 ]] || die "--format requires a value" + case "$2" in + zip) + FORMAT="zip" + ;; + tar.gz|tgz) + FORMAT="tar.gz" + ;; + *) + die "--format must be zip or tar.gz" + ;; + esac + shift 2 + ;; --metadata-source) [[ $# -ge 2 ]] || die "--metadata-source requires a path" METADATA_SOURCE="$2" @@ -83,11 +102,43 @@ while [[ $# -gt 0 ]]; do esac done +infer_format_from_output() { + local output_path="$1" + + case "$output_path" in + *.tar.gz|*.tgz) + printf '%s\n' "tar.gz" + ;; + *.zip) + printf '%s\n' "zip" + ;; + *) + return 1 + ;; + esac +} + +if [[ -z "$FORMAT" ]]; then + FORMAT="$(infer_format_from_output "$OUTPUT" || true)" + if [[ -z "$FORMAT" ]]; then + FORMAT="zip" + fi +else + output_format="$(infer_format_from_output "$OUTPUT" || true)" + if [[ -n "$output_format" && "$output_format" != "$FORMAT" ]]; then + die "--output extension does not match --format $FORMAT: $OUTPUT" + fi +fi + command -v git >/dev/null || die "git not found in PATH" command -v jq >/dev/null || die "jq not found in PATH" command -v tar >/dev/null || die "tar not found in PATH" command -v gzip >/dev/null || die "gzip not found in PATH" command -v shasum >/dev/null || die "shasum not found in PATH" +if [[ "$FORMAT" == "zip" ]]; then + command -v zip >/dev/null || die "zip not found in PATH" + command -v unzip >/dev/null || die "unzip not found in PATH" +fi [[ -d "$REPO_ROOT/.git" ]] || die "repo root is not a git checkout: $REPO_ROOT" git -C "$REPO_ROOT" rev-parse --verify "$REF^{commit}" >/dev/null || @@ -105,17 +156,19 @@ fi if [[ -z "$METADATA_SOURCE" ]]; then if [[ -d "$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers" ]]; then METADATA_SOURCE="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers" + elif [[ -f "$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers.zip" ]]; then + METADATA_SOURCE="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers.zip" elif [[ -f "$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers.tar.gz" ]]; then METADATA_SOURCE="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers.tar.gz" else - die "no metadata source found; pass --metadata-source " + die "no metadata source found; pass --metadata-source " fi fi WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/superpowers-codex-package.XXXXXX")" STAGE="$WORK_DIR/payload" METADATA_WORK="$WORK_DIR/metadata" -TAR_LIST="$WORK_DIR/tar-list" +ARCHIVE_LIST="$WORK_DIR/archive-list" cleanup() { if [[ "$KEEP_STAGE" -eq 1 ]]; then @@ -158,8 +211,13 @@ prepare_metadata_root() { tar -xzf "$source" -C "$METADATA_WORK" root="$METADATA_WORK" ;; + *.zip) + command -v unzip >/dev/null || die "unzip not found in PATH" + unzip -q "$source" -d "$METADATA_WORK" + root="$METADATA_WORK" + ;; *) - die "metadata source must be a directory or .tar.gz: $source" + die "metadata source must be a directory, .zip, or .tar.gz: $source" ;; esac else @@ -189,7 +247,14 @@ if jq -e 'has("hooks")' "$STAGE/.codex-plugin/plugin.json" >/dev/null; then fi if [[ -z "$OUTPUT" ]]; then - OUTPUT="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers-$VERSION.tar.gz" + case "$FORMAT" in + zip) + OUTPUT="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers-$VERSION.zip" + ;; + tar.gz) + OUTPUT="$REPO_ROOT/../_tmp/sup-codex-packaging/superpowers-$VERSION.tar.gz" + ;; + esac fi mkdir -p "$(dirname "$OUTPUT")" OUTPUT="$(cd "$(dirname "$OUTPUT")" && pwd)/$(basename "$OUTPUT")" @@ -218,27 +283,51 @@ metadata_count="$(find "$STAGE/skills" -path '*/agents/openai.yaml' -type f | wc [[ "$skill_count" == "$metadata_count" ]] || die "metadata count mismatch: $metadata_count metadata files for $skill_count skills" -# Match the prior official archive's deterministic tar entry metadata. -TZ=UTC find "$STAGE" -exec touch -t 197001010000 {} + - ( cd "$STAGE" { find . -mindepth 1 -type d | sed 's#^\./##' | LC_ALL=C sort find . -mindepth 1 -type f | sed 's#^\./##' | LC_ALL=C sort - } >"$TAR_LIST" - - rm -f "$OUTPUT" - COPYFILE_DISABLE=1 tar -cf - --no-recursion --format ustar --uid 0 --gid 0 --uname '' --gname '' -T "$TAR_LIST" | - gzip -9n >"$OUTPUT" + } >"$ARCHIVE_LIST" ) +case "$FORMAT" in + zip) + # ZIP cannot represent dates earlier than 1980. + TZ=UTC find "$STAGE" -exec touch -t 198001010000 {} + + ( + cd "$STAGE" + rm -f "$OUTPUT" + COPYFILE_DISABLE=1 zip -X -q - -@ <"$ARCHIVE_LIST" >"$OUTPUT" + ) + ;; + tar.gz) + # Match the prior official archive's deterministic tar entry metadata. + TZ=UTC find "$STAGE" -exec touch -t 197001010000 {} + + ( + cd "$STAGE" + rm -f "$OUTPUT" + COPYFILE_DISABLE=1 tar -cf - --no-recursion --format ustar --uid 0 --gid 0 --uname '' --gname '' -T "$ARCHIVE_LIST" | + gzip -9n >"$OUTPUT" + ) + ;; +esac + if command -v xattr >/dev/null 2>&1; then xattr -c "$OUTPUT" 2>/dev/null || true fi +case "$FORMAT" in + zip) + archive_paths="$(unzip -Z1 "$OUTPUT" | sed 's#/$##')" + ;; + tar.gz) + archive_paths="$(tar -tzf "$OUTPUT")" + ;; +esac + unexpected_paths="$( - tar -tzf "$OUTPUT" | + printf '%s\n' "$archive_paths" | grep -E '(^superpowers/|^\.agents/|^hooks/|package\.json$|^\.git|^\.pytest_cache|^\.ruff_cache|^scripts/|^tests/|^docs/|^evals/|^lib/|^\.claude|^\.cursor|^\.kimi|^\.opencode|^\.pi|^AGENTS\.md$|^CLAUDE\.md$|^GEMINI\.md$|^RELEASE-NOTES\.md$|^CHANGELOG\.md$)' || true )" if [[ -n "$unexpected_paths" ]]; then @@ -246,10 +335,11 @@ if [[ -n "$unexpected_paths" ]]; then die "archive contains source-only paths" fi -entry_count="$(tar -tzf "$OUTPUT" | wc -l | tr -d ' ')" +entry_count="$(printf '%s\n' "$archive_paths" | wc -l | tr -d ' ')" checksum="$(shasum -a 256 "$OUTPUT" | awk '{print $1}')" echo "Archive: $OUTPUT" +echo "Format: $FORMAT" echo "Version: $VERSION" echo "Entries: $entry_count" echo "Skills: $skill_count" diff --git a/tests/codex/test-package-codex-plugin.sh b/tests/codex/test-package-codex-plugin.sh index 50be9ba7f..d608674ca 100755 --- a/tests/codex/test-package-codex-plugin.sh +++ b/tests/codex/test-package-codex-plugin.sh @@ -62,6 +62,61 @@ assert_not_matches() { fi } +list_archive() { + local archive_path="$1" + + case "$archive_path" in + *.tar.gz|*.tgz) + tar -tzf "$archive_path" + ;; + *.zip) + unzip -Z1 "$archive_path" + ;; + *) + unzip -Z1 "$archive_path" + ;; + esac +} + +normalize_archive_paths() { + sed 's#/$##' | LC_ALL=C sort +} + +extract_archive() { + local archive_path="$1" + local destination="$2" + + mkdir -p "$destination" + case "$archive_path" in + *.tar.gz|*.tgz) + tar -xzf "$archive_path" -C "$destination" + ;; + *.zip) + unzip -q "$archive_path" -d "$destination" + ;; + *) + unzip -q "$archive_path" -d "$destination" + ;; + esac +} + +read_archive_file() { + local archive_path="$1" + local file_path="$2" + + case "$archive_path" in + *.tar.gz|*.tgz) + tar -xOf "$archive_path" "$file_path" + ;; + *.zip) + unzip -p "$archive_path" "$file_path" + ;; + *) + unzip -p "$archive_path" "$file_path" + ;; + esac +} + write_metadata_fixture() { local destination="$1" local skill @@ -79,8 +134,10 @@ EOF echo "Codex package archive tests" metadata_source="$TEST_ROOT/metadata-source" -archive="$TEST_ROOT/superpowers.tar.gz" +archive="$TEST_ROOT/superpowers" +tar_archive="$TEST_ROOT/superpowers.tar.gz" extracted="$TEST_ROOT/extracted" +tar_extracted="$TEST_ROOT/tar-extracted" write_metadata_fixture "$metadata_source" if output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_source" --output "$archive" 2>&1)"; then @@ -97,12 +154,12 @@ else fi assert_contains "$output" "Archive:" "reports archive path" +assert_contains "$output" "Format: zip" "reports default zip format" assert_contains "$output" "SHA-256:" "reports archive checksum" -mkdir -p "$extracted" -tar -xzf "$archive" -C "$extracted" +extract_archive "$archive" "$extracted" -archive_paths="$(tar -tzf "$archive" | sort)" +archive_paths="$(list_archive "$archive" | normalize_archive_paths)" unexpected_pattern='(^superpowers/|^\.agents/|^hooks/|package\.json$|^\.git|^\.pytest_cache|^\.ruff_cache|^scripts/|^tests/|^docs/|^evals/|^lib/|^\.claude|^\.cursor|^\.kimi|^\.opencode|^\.pi|^AGENTS\.md$|^CLAUDE\.md$|^GEMINI\.md$|^RELEASE-NOTES\.md$|^CHANGELOG\.md$)' assert_not_matches "$archive_paths" "$unexpected_pattern" "archive excludes source-only paths" assert_contains "$archive_paths" ".codex-plugin/plugin.json" "archive includes Codex manifest" @@ -111,7 +168,7 @@ assert_contains "$archive_paths" "skills/brainstorming/agents/openai.yaml" "arch assert_contains "$archive_paths" "assets/app-icon.png" "archive includes app icon" assert_contains "$archive_paths" "assets/superpowers-small.svg" "archive includes composer icon" -manifest_summary="$(tar -xOf "$archive" .codex-plugin/plugin.json | python3 -c 'import json,sys; data=json.load(sys.stdin); print("\t".join([data["name"], data["version"], data["skills"], str(data.get("hooks"))]))')" +manifest_summary="$(read_archive_file "$archive" .codex-plugin/plugin.json | python3 -c 'import json,sys; data=json.load(sys.stdin); print("\t".join([data["name"], data["version"], data["skills"], str(data.get("hooks"))]))')" expected_version="$(python3 -c 'import json; print(json.load(open("'"$REPO_ROOT"'/.codex-plugin/plugin.json"))["version"])')" assert_equals "$manifest_summary" "superpowers $expected_version ./skills/ None" "archive manifest is current and hook-free" @@ -119,17 +176,48 @@ skill_count="$(find "$extracted/skills" -mindepth 1 -maxdepth 1 -type d | wc -l metadata_count="$(find "$extracted/skills" -path '*/agents/openai.yaml' -type f | wc -l | tr -d ' ')" assert_equals "$metadata_count" "$skill_count" "every packaged skill has OpenAI metadata" -task_brief_mode="$(tar -tzvf "$archive" skills/subagent-driven-development/scripts/task-brief | awk '{print $1}')" -assert_equals "$task_brief_mode" "-rwxr-xr-x" "archive preserves executable script mode" +if [[ -x "$extracted/skills/subagent-driven-development/scripts/task-brief" ]]; then + pass "archive preserves executable script mode" +else + fail "archive preserves executable script mode" +fi -metadata_times="$(tar -tzvf "$archive" | awk '{print $6, $7, $8}' | sort -u)" -assert_equals "$metadata_times" "Dec 31 1969" "archive normalizes entry timestamps" +zip_times="$(python3 - "$archive" <<'PY' +import sys +import zipfile + +with zipfile.ZipFile(sys.argv[1]) as archive: + print("\n".join(sorted({str(info.date_time) for info in archive.infolist()}))) +PY +)" +assert_equals "$zip_times" "(1980, 1, 1, 0, 0, 0)" "zip archive normalizes entry timestamps" + +if tar_output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_source" --format tar.gz --output "$tar_archive" 2>&1)"; then + pass "package script writes explicit tar.gz archive" +else + fail "package script writes explicit tar.gz archive" + printf '%s\n' "$tar_output" | sed 's/^/ /' +fi +assert_contains "$tar_output" "Format: tar.gz" "reports explicit tar.gz format" + +extract_archive "$tar_archive" "$tar_extracted" +tar_archive_paths="$(list_archive "$tar_archive" | normalize_archive_paths)" +assert_equals "$tar_archive_paths" "$archive_paths" "zip and tar.gz archives contain the same paths" + +tar_task_brief_mode="$(tar -tzvf "$tar_archive" skills/subagent-driven-development/scripts/task-brief | awk '{print $1}')" +assert_equals "$tar_task_brief_mode" "-rwxr-xr-x" "tar.gz archive preserves executable script mode" + +tar_metadata_times="$(tar -tzvf "$tar_archive" | awk '{print $6, $7, $8}' | sort -u)" +assert_equals "$tar_metadata_times" "Dec 31 1969" "tar.gz archive normalizes entry timestamps" metadata_archive="$TEST_ROOT/metadata-source.tar.gz" -archive_from_tar_source="$TEST_ROOT/superpowers-from-tar-source.tar.gz" +metadata_zip="$TEST_ROOT/metadata-source.zip" +archive_from_tar_source="$TEST_ROOT/superpowers-from-tar-source.zip" +archive_from_zip_source="$TEST_ROOT/superpowers-from-zip-source.zip" ( cd "$metadata_source" tar -czf "$metadata_archive" . + zip -X -q -r "$metadata_zip" . ) if output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_archive" --output "$archive_from_tar_source" 2>&1)"; then @@ -145,6 +233,19 @@ else fail "tarball metadata source produces identical archive" fi +if output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_zip" --output "$archive_from_zip_source" 2>&1)"; then + pass "package script accepts zip metadata source" +else + fail "package script accepts zip metadata source" + printf '%s\n' "$output" | sed 's/^/ /' +fi + +if cmp -s "$archive" "$archive_from_zip_source"; then + pass "zip metadata source produces identical archive" +else + fail "zip metadata source produces identical archive" +fi + incomplete_metadata="$TEST_ROOT/incomplete-metadata" mkdir -p "$incomplete_metadata/skills/brainstorming/agents" cp "$metadata_source/skills/brainstorming/agents/openai.yaml" \ @@ -169,7 +270,7 @@ dirty_output="$( cd "$dirty_repo" scripts/package-codex-plugin.sh \ --metadata-source "$metadata_source" \ - --output "$TEST_ROOT/dirty.tar.gz" 2>&1 + --output "$TEST_ROOT/dirty.zip" 2>&1 )" dirty_status=$? set -e From c842f8871a11986b5a1cbb93a15931e1ca13d8d8 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 14:16:14 -0700 Subject: [PATCH 005/198] Fix Codex plugin category --- .codex-plugin/plugin.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 812e72c70..6ecfff4fb 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -27,7 +27,7 @@ "shortDescription": "Planning, TDD, debugging, and delivery workflows for coding agents", "longDescription": "Use Superpowers to guide agent work through brainstorming, implementation planning, test-driven development, systematic debugging, parallel execution, code review, and finish-the-branch workflows.", "developerName": "Jesse Vincent", - "category": "Coding", + "category": "Developer Tools", "capabilities": [ "Interactive", "Read", From 89338e511325440a9b4456a7405cd1e4a2868960 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 15:57:52 -0700 Subject: [PATCH 006/198] chore(codex): remove orphaned session-start-codex hook + refresh hook docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hooks/session-start-codex has had no caller since "Remove Codex hooks" (#1845) deleted hooks-codex.json and its manifest registration; the Codex manifest now declares an empty hooks object so Codex registers no session-start hook at all. The script is Codex-specific dead code — nothing executes it on Codex or any other harness. - Delete hooks/session-start-codex. - tests/hooks/test-session-start.sh: drop the two Codex cases that are redundant with the generic session-start tests (nested-format and the legacy-warning omission are already covered by the Claude Code cases). Re-point the "wrapper dispatches" case to the live `session-start` script so run-hook.cmd dispatch coverage — used by Claude Code and Cursor in production — is preserved rather than lost. - docs/porting-to-a-new-harness.md: Codex is no longer a Shape A (shell-hook) harness, so re-anchor that worked example to Cursor (a live shell-hook harness that demonstrates the same per-harness field, schema, and matcher variance) and mark Codex as native skill discovery with no session-start hook. Clears the references to the deleted hooks-codex.json. - docs/windows/polyglot-hooks.md: the "check hooks-codex.json" pointer referenced a file deleted in #1845; re-point to hooks-cursor.json. RELEASE-NOTES.md keeps its historical mention of hooks-codex.json (it accurately records what that release did). The tests/codex-plugin-sync fixtures build their own synthetic session-start-codex and test the sync mechanism generically, so they are intentionally left as-is. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs/porting-to-a-new-harness.md | 47 ++++++++++++++++--------------- docs/windows/polyglot-hooks.md | 2 +- hooks/session-start-codex | 26 ----------------- tests/hooks/test-session-start.sh | 44 +++-------------------------- 4 files changed, 29 insertions(+), 90 deletions(-) delete mode 100755 hooks/session-start-codex diff --git a/docs/porting-to-a-new-harness.md b/docs/porting-to-a-new-harness.md index d74b1c64f..986cf5613 100644 --- a/docs/porting-to-a-new-harness.md +++ b/docs/porting-to-a-new-harness.md @@ -227,18 +227,20 @@ you may **not** do is bridge a gap by editing the user's global config. The harness has a hook system that runs a shell command at session start and reads JSON from its stdout. The configured command runs `run-hook.cmd`, a polyglot wrapper that just locates bash and dispatches the named script; the -script (`hooks/session-start`, or a harness-specific variant like -`hooks/session-start-codex`) is what reads `using-superpowers/SKILL.md` and -prints a JSON object whose **field name and nesting differ per harness**. +script (`hooks/session-start`, or a harness-specific variant) is what reads +`using-superpowers/SKILL.md` and prints a JSON object whose **field name and +nesting differ per harness**. -- Reference: `hooks/session-start` (and `hooks/session-start-codex`), - `hooks/run-hook.cmd`, and the per-harness hook config `hooks/hooks.json` - (Claude Code), `hooks/hooks-codex.json` (Codex), `hooks/hooks-cursor.json` +- Reference: `hooks/session-start`, `hooks/run-hook.cmd`, and the per-harness + hook config `hooks/hooks.json` (Claude Code) and `hooks/hooks-cursor.json` (Cursor). -- Manifests: `.codex-plugin/plugin.json`, `.cursor-plugin/plugin.json` point the - harness at `./skills/` and the right `hooks-*.json`. (Claude Code's - `.claude-plugin/plugin.json` sets neither field — it auto-discovers `skills/` - and `hooks/hooks.json` by convention.) +- Manifests: `.cursor-plugin/plugin.json` points the harness at `./skills/` and + the right `hooks-*.json`. (Claude Code's `.claude-plugin/plugin.json` sets + neither field — it auto-discovers `skills/` and `hooks/hooks.json` by + convention. Codex's `.codex-plugin/plugin.json` ships skills but declares an + empty `hooks` object: Codex auto-discovers `hooks/hooks.json` when the field + is absent, so the empty object suppresses that — Codex surfaces skills + natively and runs no session-start hook.) > **A hook *system* is not a session-start *event*.** A harness can have a > `hooks.json` mechanism — and even contain the literal string `SessionStart` in @@ -287,7 +289,7 @@ part of the installed extension** — never substitute "edit the user's global | If the harness… | Use shape | Copy from | |---|---|---| -| runs a shell command at session start and reads its stdout | A (shell-hook) | Codex (`hooks/session-start-codex` + `hooks/hooks-codex.json` + `.codex-plugin/`) | +| runs a shell command at session start and reads its stdout | A (shell-hook) | Cursor (`hooks/session-start` + `hooks/hooks-cursor.json` + `.cursor-plugin/`) | | is a JS/TS plugin host with session/message lifecycle callbacks | B (in-process) | OpenCode (`.opencode/`) — or pi (`.pi/`) if it has no native skill tool | | ships an extension-declared context file it always loads | C (instructions-file) | Gemini (`gemini-extension.json` + `GEMINI.md` + `references/gemini-tools.md`) | | has a plugin install command and a manifest `contextFileName` (or equivalent) the installer keeps | C via the plugin installer | Antigravity (`.antigravity-plugin/` — `agy plugin install` ships a generated context file; verify the installer preserves it — Part 6) | @@ -375,25 +377,24 @@ both double-injects). Find the exact field, nesting, and event-matcher values your harness expects. Then decide: add a fourth branch to `hooks/session-start`, or — if the harness needs a different bootstrap message or env contract — add a dedicated -`hooks/session-start-` script, the way Codex did. If you add a branch +`hooks/session-start-` script. If you add a branch and your harness *also* sets an env var an earlier branch keys on (some harnesses set `CLAUDE_PLUGIN_ROOT` too), order your branch before the one that would otherwise shadow it. Match the harness's -own event-matcher strings (Claude Code uses `startup|clear|compact`, Codex -`startup|resume|clear`, Cursor `sessionStart`); wrong matchers mean the hook -silently never fires. +own event-matcher strings (Claude Code uses `startup|clear|compact`, Cursor +`sessionStart`); wrong matchers mean the hook silently never fires. The **hook-config schema itself varies per harness** — don't assume the -Claude/Codex shape is universal. Compare `hooks/hooks.json`, -`hooks/hooks-codex.json`, and `hooks/hooks-cursor.json`: Cursor's uses +Claude Code shape is universal. Compare `hooks/hooks.json` and +`hooks/hooks-cursor.json`: Cursor's uses `"version": 1`, a lowercase `sessionStart` key, a relative -`./hooks/run-hook.cmd` command, and omits the `matcher`/`type`/`async` fields the -others use. Match your `hooks-.json` to whichever existing file is +`./hooks/run-hook.cmd` command, and omits the `matcher`/`type`/`async` fields +Claude Code uses. Match your `hooks-.json` to whichever existing file is closest, not to a single canonical template. The hook **command string references a harness-provided plugin-root variable**, and its name differs per harness: `hooks.json` uses `${CLAUDE_PLUGIN_ROOT}`, -`hooks-codex.json` uses `${PLUGIN_ROOT}`, Cursor uses a relative path. Use +`hooks-cursor.json` uses a relative path. Use whatever your harness exports. (The `session-start` script re-derives the root itself via `dirname`, so the script body doesn't depend on this — but the command in the manifest does.) @@ -784,7 +785,7 @@ Use this as the live index; when in doubt, read the files, not this table. | Harness | Entry point | Bootstrap mechanism | Tool mapping | Tests | Distribution | |---|---|---|---|---|---| | Claude Code | `.claude-plugin/plugin.json` + `hooks/hooks.json` | shell hook → `hooks/session-start` (`hookSpecificOutput.additionalContext`) | native `Skill` tool; `references/claude-code-tools.md` | `tests/hooks/` | marketplace | -| Codex | `.codex-plugin/plugin.json` + `hooks/hooks-codex.json` | shell hook → `hooks/session-start-codex` | `references/codex-tools.md` | `tests/codex-plugin-sync/`, `tests/hooks/` | fork sync (`scripts/sync-to-codex-plugin.sh`) | +| Codex | `.codex-plugin/plugin.json` (declares empty `hooks`) | native skill discovery (no session-start hook) | `references/codex-tools.md` | `tests/codex/`, `tests/codex-plugin-sync/` | fork sync (`scripts/sync-to-codex-plugin.sh`) | | Cursor | `.cursor-plugin/plugin.json` + `hooks/hooks-cursor.json` | shell hook → `hooks/session-start` (`additional_context`) | `references/claude-code-tools.md` | `tests/hooks/` | hand-authored | | Copilot CLI | (shares Claude Code hook path; `COPILOT_CLI` env) | shell hook → `hooks/session-start` (`additionalContext`) | `references/copilot-tools.md` | `tests/hooks/` | — | | Gemini CLI | `gemini-extension.json` + `GEMINI.md` | instructions file `@`-includes bootstrap + mapping | `references/gemini-tools.md` | — | `gemini extensions install` | @@ -799,10 +800,10 @@ Use this as the live index; when in doubt, read the files, not this table. - **Wrong JSON field → silent failure or double injection.** Shape A only. Confirm the exact field/nesting; Claude Code reads two fields without dedup. - **Hook-config schema varies per harness.** Shape A. Cursor's `hooks-cursor.json` - looks nothing like the Claude/Codex one (`version`, lowercase `sessionStart`, + looks nothing like the Claude Code one (`version`, lowercase `sessionStart`, relative command, no `matcher`/`type`/`async`). Match the closest existing file. - **Plugin-root env var differs per harness.** Shape A. The hook command uses - `${CLAUDE_PLUGIN_ROOT}` (Claude), `${PLUGIN_ROOT}` (Codex), or a relative path + `${CLAUDE_PLUGIN_ROOT}` (Claude) or a relative path (Cursor). Use what your harness exports; the script re-derives the root itself. - **System-message injection.** Shape B injects a *user* message on purpose (#750, #894). Don't "fix" it to a system message. diff --git a/docs/windows/polyglot-hooks.md b/docs/windows/polyglot-hooks.md index ca597c3ab..8b84f2717 100644 --- a/docs/windows/polyglot-hooks.md +++ b/docs/windows/polyglot-hooks.md @@ -140,7 +140,7 @@ Check that the script filename is **extensionless** in `hooks.json`. A command l ### Hook doesn't fire at all -Verify the `matcher` in `hooks.json` matches the event type your harness emits. Claude Code uses `startup|clear|compact`; Codex uses `startup|resume|clear`. Check `hooks-codex.json` for the Codex variant. +Verify the `matcher` in `hooks.json` matches the event type your harness emits. Claude Code uses `startup|clear|compact`; Cursor uses `sessionStart`. Check `hooks-cursor.json` for the Cursor variant. ## Related Issues diff --git a/hooks/session-start-codex b/hooks/session-start-codex deleted file mode 100755 index f25ea0846..000000000 --- a/hooks/session-start-codex +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash -# Codex SessionStart hook for superpowers plugin - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" - -using_superpowers_content=$(cat "${PLUGIN_ROOT}/skills/using-superpowers/SKILL.md" 2>&1 || echo "Error reading using-superpowers skill") - -escape_for_json() { - local s="$1" - s="${s//\\/\\\\}" - s="${s//\"/\\\"}" - s="${s//$'\n'/\\n}" - s="${s//$'\r'/\\r}" - s="${s//$'\t'/\\t}" - printf '%s' "$s" -} - -using_superpowers_escaped=$(escape_for_json "$using_superpowers_content") -session_context="\nYou have superpowers.\n\n**Below is the full content of your 'superpowers:using-superpowers' skill - your introduction to using skills. For all other skills, follow the Codex skill-loading instructions in that skill:**\n\n${using_superpowers_escaped}\n" - -printf '{\n "hookSpecificOutput": {\n "hookEventName": "SessionStart",\n "additionalContext": "%s"\n }\n}\n' "$session_context" | cat - -exit 0 diff --git a/tests/hooks/test-session-start.sh b/tests/hooks/test-session-start.sh index 989d72c65..b027f3c65 100755 --- a/tests/hooks/test-session-start.sh +++ b/tests/hooks/test-session-start.sh @@ -4,7 +4,6 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" HOOK_UNDER_TEST="$REPO_ROOT/hooks/session-start" -CODEX_HOOK_UNDER_TEST="$REPO_ROOT/hooks/session-start-codex" WRAPPER_UNDER_TEST="$REPO_ROOT/hooks/run-hook.cmd" FAILURES=0 @@ -154,35 +153,15 @@ assert_command_output \ CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \ bash "$HOOK_UNDER_TEST" -codex_home="$(make_home codex-plugin-hooks)" -codex_data="$TEST_ROOT/codex-plugin-hooks/data" -mkdir -p "$codex_data" +wrapper_home="$(make_home run-hook-wrapper)" assert_command_output \ - "Codex plugin hooks use dedicated script and emit nested SessionStart additionalContext" \ + "run-hook.cmd wrapper dispatches to the named session-start script" \ "nested" \ "" \ "" \ - "$codex_home" \ - PLUGIN_DATA="$codex_data" \ - CLAUDE_PLUGIN_DATA="$codex_data" \ - PLUGIN_ROOT="$REPO_ROOT" \ + "$wrapper_home" \ CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \ - bash "$CODEX_HOOK_UNDER_TEST" - -codex_wrapper_home="$(make_home codex-wrapper)" -codex_wrapper_data="$TEST_ROOT/codex-wrapper/data" -mkdir -p "$codex_wrapper_data" -assert_command_output \ - "Codex wrapper path dispatches to dedicated script" \ - "nested" \ - "" \ - "" \ - "$codex_wrapper_home" \ - PLUGIN_DATA="$codex_wrapper_data" \ - CLAUDE_PLUGIN_DATA="$codex_wrapper_data" \ - PLUGIN_ROOT="$REPO_ROOT" \ - CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \ - bash "$WRAPPER_UNDER_TEST" session-start-codex + bash "$WRAPPER_UNDER_TEST" session-start cursor_home="$(make_home cursor)" assert_command_output \ @@ -217,21 +196,6 @@ assert_command_output \ CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \ bash "$HOOK_UNDER_TEST" -codex_legacy_home="$(make_home codex-legacy-warning-removed)" -codex_legacy_data="$TEST_ROOT/codex-legacy-warning-removed/data" -mkdir -p "$codex_legacy_home/.config/superpowers/skills" "$codex_legacy_data" -assert_command_output \ - "Codex SessionStart omits obsolete legacy custom-skill warning" \ - "nested" \ - "" \ - "Superpowers now uses"$'\037'"~/.config/superpowers/skills"$'\037'"~/.claude/skills"$'\037'"legacy" \ - "$codex_legacy_home" \ - PLUGIN_DATA="$codex_legacy_data" \ - CLAUDE_PLUGIN_DATA="$codex_legacy_data" \ - PLUGIN_ROOT="$REPO_ROOT" \ - CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \ - bash "$CODEX_HOOK_UNDER_TEST" - if [[ "$FAILURES" -gt 0 ]]; then echo "STATUS: FAILED ($FAILURES failure(s))" exit 1 From 53106e6536bb0364074d7eab3e69b1ccb2580319 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 17:10:01 -0700 Subject: [PATCH 007/198] docs: re-anchor Shape A examples away from Codex --- docs/porting-to-a-new-harness.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/porting-to-a-new-harness.md b/docs/porting-to-a-new-harness.md index 986cf5613..d288c6b07 100644 --- a/docs/porting-to-a-new-harness.md +++ b/docs/porting-to-a-new-harness.md @@ -90,7 +90,7 @@ every session, with no per-session opt-in by your human partner.** This is the one non-negotiable capability. It can take any form: - a **hook/event system** that runs a shell command at session start and reads - its stdout (Claude Code, Codex, Cursor, Copilot CLI), or + its stdout (Claude Code, Cursor, Copilot CLI), or - an **in-process plugin/extension** with a session-start or message lifecycle callback that can mutate the message array (OpenCode, pi), or - an **instructions-file** convention where the harness loads a context file that @@ -234,13 +234,13 @@ nesting differ per harness**. - Reference: `hooks/session-start`, `hooks/run-hook.cmd`, and the per-harness hook config `hooks/hooks.json` (Claude Code) and `hooks/hooks-cursor.json` (Cursor). -- Manifests: `.cursor-plugin/plugin.json` points the harness at `./skills/` and - the right `hooks-*.json`. (Claude Code's `.claude-plugin/plugin.json` sets - neither field — it auto-discovers `skills/` and `hooks/hooks.json` by - convention. Codex's `.codex-plugin/plugin.json` ships skills but declares an - empty `hooks` object: Codex auto-discovers `hooks/hooks.json` when the field - is absent, so the empty object suppresses that — Codex surfaces skills - natively and runs no session-start hook.) +- Manifests: `.cursor-plugin/plugin.json` is the Shape A manifest example that + points the harness at `./skills/` and the right `hooks-*.json`. Claude Code's + `.claude-plugin/plugin.json` sets neither field — it auto-discovers `skills/` + and `hooks/hooks.json` by convention. Do **not** copy Codex's + `.codex-plugin/plugin.json` for Shape A: it declares an empty `hooks` object + specifically to suppress Codex's `hooks/hooks.json` auto-discovery, because + Codex surfaces skills natively and runs no session-start hook. > **A hook *system* is not a session-start *event*.** A harness can have a > `hooks.json` mechanism — and even contain the literal string `SessionStart` in @@ -311,7 +311,7 @@ patterns below are summaries; the code is the spec. Create whatever the harness uses to recognize the plugin. Match the existing ones in spirit: -- **Shape A:** a `*-plugin/plugin.json` (see `.codex-plugin/plugin.json`) with +- **Shape A:** a `*-plugin/plugin.json` (see `.cursor-plugin/plugin.json`) with `name`, `version`, `description`, author/license/keywords, `"skills": "./skills/"`, and `"hooks": "./hooks/hooks-.json"`. Plus the `hooks-.json` itself, registering a session-start hook whose command From 4ecbbcd0b4573963b550858a030bf503793b2cab Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 17:32:44 -0700 Subject: [PATCH 008/198] Strip hooks from Codex portal package --- scripts/package-codex-plugin.sh | 4 +++- tests/codex/test-package-codex-plugin.sh | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/package-codex-plugin.sh b/scripts/package-codex-plugin.sh index 008644edf..91458b516 100755 --- a/scripts/package-codex-plugin.sh +++ b/scripts/package-codex-plugin.sh @@ -243,7 +243,9 @@ VERSION="$(jq -r '.version // empty' "$STAGE/.codex-plugin/plugin.json")" [[ -n "$VERSION" ]] || die "could not read version from .codex-plugin/plugin.json" if jq -e 'has("hooks")' "$STAGE/.codex-plugin/plugin.json" >/dev/null; then - die "Codex manifest must not declare hooks for the portal package" + manifest_tmp="$WORK_DIR/plugin-manifest.json" + jq 'del(.hooks)' "$STAGE/.codex-plugin/plugin.json" >"$manifest_tmp" + mv "$manifest_tmp" "$STAGE/.codex-plugin/plugin.json" fi if [[ -z "$OUTPUT" ]]; then diff --git a/tests/codex/test-package-codex-plugin.sh b/tests/codex/test-package-codex-plugin.sh index d608674ca..3a3d715de 100755 --- a/tests/codex/test-package-codex-plugin.sh +++ b/tests/codex/test-package-codex-plugin.sh @@ -140,6 +140,9 @@ extracted="$TEST_ROOT/extracted" tar_extracted="$TEST_ROOT/tar-extracted" write_metadata_fixture "$metadata_source" +source_hooks="$(python3 -c 'import json; print(json.load(open("'"$REPO_ROOT"'/.codex-plugin/plugin.json")).get("hooks"))')" +assert_equals "$source_hooks" "{}" "source Codex manifest suppresses local hook auto-discovery" + if output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_source" --output "$archive" 2>&1)"; then pass "package script exits successfully" else From 97506cefd72a79ebeaf0392428797f4b6d7ad87e Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 30 Jun 2026 17:45:41 -0700 Subject: [PATCH 009/198] Preserve hooks in Codex package manifest --- scripts/package-codex-plugin.sh | 6 ------ tests/codex/test-package-codex-plugin.sh | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/scripts/package-codex-plugin.sh b/scripts/package-codex-plugin.sh index 91458b516..00399f061 100755 --- a/scripts/package-codex-plugin.sh +++ b/scripts/package-codex-plugin.sh @@ -242,12 +242,6 @@ git -C "$REPO_ROOT" archive --format=tar "$REF" -- \ VERSION="$(jq -r '.version // empty' "$STAGE/.codex-plugin/plugin.json")" [[ -n "$VERSION" ]] || die "could not read version from .codex-plugin/plugin.json" -if jq -e 'has("hooks")' "$STAGE/.codex-plugin/plugin.json" >/dev/null; then - manifest_tmp="$WORK_DIR/plugin-manifest.json" - jq 'del(.hooks)' "$STAGE/.codex-plugin/plugin.json" >"$manifest_tmp" - mv "$manifest_tmp" "$STAGE/.codex-plugin/plugin.json" -fi - if [[ -z "$OUTPUT" ]]; then case "$FORMAT" in zip) diff --git a/tests/codex/test-package-codex-plugin.sh b/tests/codex/test-package-codex-plugin.sh index 3a3d715de..62c73f1cc 100755 --- a/tests/codex/test-package-codex-plugin.sh +++ b/tests/codex/test-package-codex-plugin.sh @@ -173,7 +173,7 @@ assert_contains "$archive_paths" "assets/superpowers-small.svg" "archive include manifest_summary="$(read_archive_file "$archive" .codex-plugin/plugin.json | python3 -c 'import json,sys; data=json.load(sys.stdin); print("\t".join([data["name"], data["version"], data["skills"], str(data.get("hooks"))]))')" expected_version="$(python3 -c 'import json; print(json.load(open("'"$REPO_ROOT"'/.codex-plugin/plugin.json"))["version"])')" -assert_equals "$manifest_summary" "superpowers $expected_version ./skills/ None" "archive manifest is current and hook-free" +assert_equals "$manifest_summary" "superpowers $expected_version ./skills/ $source_hooks" "archive manifest preserves source hooks" skill_count="$(find "$extracted/skills" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')" metadata_count="$(find "$extracted/skills" -path '*/agents/openai.yaml' -type f | wc -l | tr -d ' ')" From c809093a2a449e1772e8c87f41ceb6d5e7135464 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 2 Jul 2026 14:23:30 -0700 Subject: [PATCH 010/198] Release v6.1.1: fix Codex SessionStart hook re-registration, add Codex portal packaging --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- .kimi-plugin/plugin.json | 2 +- RELEASE-NOTES.md | 11 +++++++++++ gemini-extension.json | 2 +- package.json | 2 +- 8 files changed, 18 insertions(+), 7 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index f8343e4bf..acb6ae664 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ { "name": "superpowers", "description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.1.0", + "version": "6.1.1", "source": "./", "author": { "name": "Jesse Vincent", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 83ebf0713..2fe026fdc 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "superpowers", "description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.1.0", + "version": "6.1.1", "author": { "name": "Jesse Vincent", "email": "jesse@fsck.com" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 6ecfff4fb..a6b31431f 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.1.0", + "version": "6.1.1", "description": "An agentic skills framework & software development methodology that works: planning, TDD, debugging, and collaboration workflows.", "author": { "name": "Jesse Vincent", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index d94de6f01..18d788b2c 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -2,7 +2,7 @@ "name": "superpowers", "displayName": "Superpowers", "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.1.0", + "version": "6.1.1", "author": { "name": "Jesse Vincent", "email": "jesse@fsck.com" diff --git a/.kimi-plugin/plugin.json b/.kimi-plugin/plugin.json index 32c3ea580..e5d90d0c9 100644 --- a/.kimi-plugin/plugin.json +++ b/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.1.0", + "version": "6.1.1", "description": "An agentic skills framework and software development methodology.", "author": { "name": "Jesse Vincent", diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index 1d9c50535..823948e74 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -1,5 +1,16 @@ # Superpowers Release Notes +## v6.1.1 (2026-07-02) + +### Codex + +- **Codex no longer re-registers the Claude SessionStart hook.** v6.1.0 removed the Codex hook config and its manifest `hooks` pointer, meaning to stop Codex from installing a SessionStart hook — but with no `hooks` field, Codex fell back to auto-discovering `hooks/hooks.json`, the Claude Code SessionStart hook that the marketplace ships from the repo root, and re-registered it along with its install-time trust prompt. The Codex manifest now declares an explicit empty hooks object (`hooks: {}`), which Codex reads as "no hooks" instead of reaching the auto-discovery fallback. An absent field, `[]`, and an empty inline list all collapse back to the fallback, so the value has to be exactly `{}`. +- **Removed orphaned Codex session-start dead code.** `hooks/session-start-codex` had no caller once the Codex hook config was deleted, so it and its redundant test cases are gone. The worked shell-hook example in `docs/porting-to-a-new-harness.md` moves from Codex — now native skill discovery with no session-start hook — to Cursor, a live shell-hook harness, and the stale `hooks-codex.json` pointer in `docs/windows/polyglot-hooks.md` is corrected. The Codex plugin category is also fixed to "Developer Tools". + +### Packaging + +- **New `package-codex-plugin.sh` for building the Codex portal package.** A maintainer script produces a deterministic Codex "portal" archive — `.zip` by default, `tar.gz` on request — that normalizes entry timestamps, preserves executable modes, verifies every packaged skill ships its OpenAI metadata, includes the app and composer icons, and refuses to run against a dirty worktree. The packaged manifest keeps the source `hooks: {}` object so a portal-installed plugin avoids the same SessionStart auto-discovery, and the script can rebuild a byte-identical archive from a saved metadata source. Covered by a new test suite. + ## v6.1.0 (2026-06-30) ### Lower Per-Session Token Cost diff --git a/gemini-extension.json b/gemini-extension.json index 0fac6898a..dc5e1f645 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "superpowers", "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.1.0", + "version": "6.1.1", "contextFileName": "GEMINI.md" } diff --git a/package.json b/package.json index 387b763c3..ad25028da 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.1.0", + "version": "6.1.1", "description": "Superpowers skills and runtime bootstrap for coding agents", "type": "module", "main": ".opencode/plugins/superpowers.js", From 096e15aa736d2e920fb7f1e2c954604f02ebbdb0 Mon Sep 17 00:00:00 2001 From: Ada Sen Date: Fri, 10 Jul 2026 15:12:38 +0000 Subject: [PATCH 011/198] Revert "Remove Gemini CLI support" This reverts commit 711d895ce736cbcc5fb0c219ea3f49277f17fa8c. --- CLAUDE.md | 2 +- README.md | 16 ++++- skills/brainstorming/visual-companion.md | 7 +++ skills/executing-plans/SKILL.md | 2 +- .../references/gemini-tools.md | 63 +++++++++++++++++++ skills/writing-skills/SKILL.md | 2 +- 6 files changed, 88 insertions(+), 4 deletions(-) create mode 100644 skills/using-superpowers/references/gemini-tools.md diff --git a/CLAUDE.md b/CLAUDE.md index f8e45e9db..5f3d7410f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -101,7 +101,7 @@ Skills are not prose — they are code that shapes agent behavior. If you modify ## Eval harness -Skill-behavior evals live in [superpowers-evals](https://github.com/prime-radiant-inc/superpowers-evals/), cloned into `evals/` — see `evals/README.md` for setup. The harness drives real tmux sessions of Claude Code / Codex and judges skill compliance with an LLM verifier. Plugin-infrastructure tests still live at `tests/`. +Skill-behavior evals live in [superpowers-evals](https://github.com/prime-radiant-inc/superpowers-evals/), cloned into `evals/` — see `evals/README.md` for setup. Drill (the harness) drives real tmux sessions of Claude Code / Codex / Gemini CLI and judges skill compliance with an LLM verifier. Plugin-infrastructure tests still live at `tests/`. ## Understand the Project Before Contributing diff --git a/README.md b/README.md index 48e3f1985..bb398c6b6 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ If this sounds like someone you know, definitely send them our way. ## Quickstart -Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Factory Droid](#factory-droid), [GitHub Copilot CLI](#github-copilot-cli), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). +Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). ## How it works @@ -122,6 +122,20 @@ Superpowers is available via the [official Codex plugin marketplace](https://git droid plugin install superpowers@superpowers ``` +### Gemini CLI + +- Install the extension: + + ```bash + gemini extensions install https://github.com/obra/superpowers + ``` + +- Update later: + + ```bash + gemini extensions update superpowers + ``` + ### GitHub Copilot CLI - Register the marketplace: diff --git a/skills/brainstorming/visual-companion.md b/skills/brainstorming/visual-companion.md index 7b89f6b25..906c9ac87 100644 --- a/skills/brainstorming/visual-companion.md +++ b/skills/brainstorming/visual-companion.md @@ -74,6 +74,13 @@ On Windows, the script auto-detects and switches to foreground mode (which block scripts/start-server.sh --project-dir /path/to/project --open ``` +**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 --open --foreground +``` + **Copilot CLI:** ```bash # Use --foreground and start the server via the bash tool with mode: "async" diff --git a/skills/executing-plans/SKILL.md b/skills/executing-plans/SKILL.md index 075a1038f..78d885406 100644 --- a/skills/executing-plans/SKILL.md +++ b/skills/executing-plans/SKILL.md @@ -11,7 +11,7 @@ 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:** Tell your human partner that Superpowers works much better with access to subagents. The quality of its work will be significantly higher if run on a platform with subagent support (Claude Code, Codex CLI, Codex App, and Copilot CLI all qualify; see the per-platform tool refs in `../using-superpowers/references/`). If subagents are available, use superpowers:subagent-driven-development instead of this skill. +**Note:** Tell your human partner that Superpowers works much better with access to subagents. The quality of its work will be significantly higher if run on a platform with subagent support (Claude Code, Codex CLI, Codex App, Copilot CLI, and Gemini CLI all qualify; see the per-platform tool refs in `../using-superpowers/references/`). If subagents are available, use superpowers:subagent-driven-development instead of this skill. ## The Process diff --git a/skills/using-superpowers/references/gemini-tools.md b/skills/using-superpowers/references/gemini-tools.md new file mode 100644 index 000000000..b01b65238 --- /dev/null +++ b/skills/using-superpowers/references/gemini-tools.md @@ -0,0 +1,63 @@ +# Gemini CLI Tool Mapping + +Skills speak in actions ("dispatch a subagent", "create a todo", "read a file"). On Gemini CLI these resolve to the tools below. + +| Action skills request | Gemini CLI equivalent | +|----------------------|----------------------| +| Read a file | `read_file` | +| Read multiple files at once | `read_many_files` | +| Create a new file | `write_file` | +| Edit a file | `replace` | +| Run a shell command | `run_shell_command` | +| Search file contents | `grep_search` | +| Find files by name | `glob` | +| List files and subdirectories | `list_directory` | +| Fetch a URL | `web_fetch` | +| Search the web | `google_web_search` | +| Invoke a skill | `activate_skill` | +| Dispatch a subagent (`Subagent (general-purpose):` template) | `invoke_agent` with `agent_name: "generalist"` (invocable via `@generalist` chat syntax — see [Subagent support](#subagent-support)) | +| Multiple parallel dispatches | Multiple `invoke_agent` calls in the same response | +| Task tracking ("create a todo", "mark complete") | `write_todos` (statuses: pending, in_progress, completed, cancelled, blocked) | + +## Instructions file + +When a skill mentions "your instructions file", on Gemini CLI this is **`GEMINI.md`**. Gemini CLI loads `GEMINI.md` hierarchically: global at `~/.gemini/GEMINI.md`, project-level files in workspace directories and their ancestors, and sub-directory `GEMINI.md` files when a tool accesses files in those directories. + +## Personal skills directory + +User-level skills live at **`~/.gemini/skills/`**, with **`~/.agents/skills/`** as a cross-runtime alias (shared with Codex and Copilot CLI). When both directories exist at the same scope, `.agents/skills/` takes precedence. Each skill is a subdirectory containing a `SKILL.md` (with `name` and `description` frontmatter). + +## Subagent support + +Gemini CLI dispatches subagents through the `invoke_agent` tool, which takes `agent_name` and `prompt` parameters. The same dispatch is also surfaced as a chat-syntax shortcut: typing `@generalist ` is equivalent to calling `invoke_agent` with `agent_name: "generalist"`. Built-in agent names include `generalist`, `cli_help`, `codebase_investigator`, and (with browser tooling enabled) `browser_agent`. + +Skills dispatch with `Subagent (general-purpose):` and either reference a prompt-template file (e.g., `superpowers:subagent-driven-development`'s `./implementer-prompt.md`) or supply an inline prompt. On Gemini CLI: + +| Skill dispatch form | Gemini CLI equivalent | +|---------------------|----------------------| +| References a `*-prompt.md` template (implementer, task-reviewer, code-reviewer, etc.) | Fill the template, then `invoke_agent` with `agent_name: "generalist"` and the filled prompt | +| References `superpowers:requesting-code-review`'s `./code-reviewer.md` | `invoke_agent` with `agent_name: "generalist"` and the filled review template | +| Inline prompt (no template referenced) | `invoke_agent` with `agent_name: "generalist"` and your inline prompt | + +### Prompt filling + +Skills provide prompt templates with placeholders like `{WHAT_WAS_IMPLEMENTED}` or `[FULL TEXT of task]`. Fill all placeholders before passing the complete prompt to `invoke_agent`. The prompt template itself contains the agent's role, review criteria, and expected output format — the subagent will follow it. + +### Parallel dispatch + +Gemini CLI supports parallel subagent dispatch. Issue multiple `invoke_agent` calls in the same response (or multiple `@generalist` invocations in one prompt) to run independent subagent work in parallel. Keep dependent tasks sequential, but do not serialize independent subagent tasks just to preserve a simpler history. + +## Additional Gemini CLI tools + +These tools are unique to Gemini CLI: + +| Tool | Purpose | +|------|---------| +| `save_memory` (legacy) | Persist facts across sessions when `experimental.memoryV2 = false` | +| `get_internal_docs` | Look up Gemini CLI's bundled documentation | +| `ask_user` | Pose structured questions to the user (text / single-select / multi-select) | +| `enter_plan_mode` / `exit_plan_mode` | Switch into and out of read-only plan mode | +| `update_topic` | Update the current conversation's topic / strategic-intent metadata | +| `complete_task` | Signal that a Gemini subagent has completed and return its result to the parent agent | +| `tracker_create_task`, `tracker_update_task`, `tracker_get_task`, `tracker_list_tasks`, `tracker_add_dependency`, `tracker_visualize` | Rich task tracker with dependency and visualization support | +| `read_mcp_resource`, `list_mcp_resources` | MCP resource access | diff --git a/skills/writing-skills/SKILL.md b/skills/writing-skills/SKILL.md index 6d3ded6e6..8928d449f 100644 --- a/skills/writing-skills/SKILL.md +++ b/skills/writing-skills/SKILL.md @@ -9,7 +9,7 @@ description: Use when creating new skills, editing existing skills, or verifying **Writing skills IS Test-Driven Development applied to process documentation.** -**Personal skills live in your runtime's skills directory** +**Personal skills live in your runtime's skills directory** — see [claude-code-tools.md](../using-superpowers/references/claude-code-tools.md), [codex-tools.md](../using-superpowers/references/codex-tools.md), [copilot-tools.md](../using-superpowers/references/copilot-tools.md), or [gemini-tools.md](../using-superpowers/references/gemini-tools.md) for the path on your runtime. Codex, Copilot CLI, and Gemini CLI all also recognize `~/.agents/skills/` as a cross-runtime alias. 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). From ab4fa6b09fbe1e0655b48d27a3019057b8645f45 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 10:21:28 -0700 Subject: [PATCH 012/198] refactor(skills): fold Integration skill lists into points of use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The list-style Integration sections in subagent-driven-development and executing-plans duplicated references that already exist where the flow uses them (process digraph, When to Use, prompt templates, Step 3), so they added maintenance cost without carrying behavior. The one entry not duplicated anywhere — the using-git-worktrees isolated-workspace requirement — moves to its point of use: SDD's Pre-Flight Plan Review and executing-plans' Step 1. Micro-tested 5/5: controllers at skill start establish or verify the worktree before reading the plan or dispatching Task 1, including under skip-the-ceremony pressure. The prose Integration sections in requesting-code-review and other skills are unchanged — they carry placement content, not an index. --- skills/executing-plans/SKILL.md | 16 +++++----------- skills/subagent-driven-development/SKILL.md | 17 +++-------------- 2 files changed, 8 insertions(+), 25 deletions(-) diff --git a/skills/executing-plans/SKILL.md b/skills/executing-plans/SKILL.md index 78d885406..8c9f339d9 100644 --- a/skills/executing-plans/SKILL.md +++ b/skills/executing-plans/SKILL.md @@ -16,10 +16,11 @@ Load plan, review critically, execute all tasks, report when complete. ## 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 your human partner before starting -4. If no concerns: Create todos for the plan items and proceed +1. Ensure an isolated workspace: use superpowers:using-git-worktrees to create one or verify the existing one +2. Read plan file +3. Review critically - identify any questions or concerns about the plan +4. If concerns: Raise them with your human partner before starting +5. If no concerns: Create todos for the plan items and proceed ### Step 2: Execute Tasks @@ -61,10 +62,3 @@ After all tasks complete and verified: - 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 diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index d8ca08157..ebbb10024 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -84,6 +84,9 @@ digraph process { ## Pre-Flight Plan Review +Ensure the work happens in an isolated workspace: use +superpowers:using-git-worktrees to create one or verify the existing one. + Before dispatching Task 1, scan the plan once for conflicts: - tasks that contradict each other or the plan's Global Constraints @@ -402,17 +405,3 @@ Done! **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 the final whole-branch review -- **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 From 5ce5a4070300f64a248f7f76f9d05e058154ac56 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 10:50:42 -0700 Subject: [PATCH 013/198] refactor(skills): fold systematic-debugging Related-skills block into Phase 4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Same treatment as subagent-driven-development and executing-plans: the test-driven-development entry duplicated the reference already at Phase 4 Step 1, and the verification-before-completion entry was a sole carrier — it moves to its point of use in Phase 4 Step 3 (Verify Fix). Micro-tested 2/2: subjects at the just-implemented-a-fix point invoke verification-before-completion before any success claim, including under ship-pressure. --- skills/systematic-debugging/SKILL.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/skills/systematic-debugging/SKILL.md b/skills/systematic-debugging/SKILL.md index b0eca38b3..1c0be5723 100644 --- a/skills/systematic-debugging/SKILL.md +++ b/skills/systematic-debugging/SKILL.md @@ -188,6 +188,7 @@ You MUST complete each phase before proceeding to the next. - Test passes now? - No other tests broken? - Issue actually resolved? + - Use the `superpowers:verification-before-completion` skill before claiming success 4. **If Fix Doesn't Work** - STOP @@ -283,10 +284,6 @@ These techniques are part of systematic debugging and available in this director - **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause - **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling -**Related skills:** -- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1) -- **superpowers:verification-before-completion** - Verify fix worked before claiming success - ## Real-World Impact From debugging sessions: From a0487b028fda57cc3825202fac2a2fbe9e7d2f56 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 11:09:48 -0700 Subject: [PATCH 014/198] refactor(skills): stop offering to discard work in finishing-a-development-branch The completion menu dates from when throwing away branches was routine; offering 'Discard this work' beside 'Merge' on every completion advertised destroying finished, passing work. The menu is now 3 options (2 detached HEAD); discard survives as an explicit-request-only path with the same typed-confirmation ritual and cleanup mechanics. Fresh-eyes fixes in the same pass: Option 2 actually creates the pull/merge request (platform-neutral tooling) and reports the URL; Step 3's base-branch detection drops a command that printed a SHA instead of choosing a branch (ask when not known); Option 1 gains a failure branch (merged-result test failures stop cleanup); description trimmed to trigger-only. Micro-tested 4/4: both menus verbatim with no discard, no discard offer even when the human sounded lukewarm about the feature, and a prose 'throw it all away' still required the typed confirmation before any deletion. --- .../finishing-a-development-branch/SKILL.md | 60 ++++++++++++------- 1 file changed, 38 insertions(+), 22 deletions(-) diff --git a/skills/finishing-a-development-branch/SKILL.md b/skills/finishing-a-development-branch/SKILL.md index 7f5337aaf..368829fd8 100644 --- a/skills/finishing-a-development-branch/SKILL.md +++ b/skills/finishing-a-development-branch/SKILL.md @@ -1,6 +1,6 @@ --- name: finishing-a-development-branch -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 +description: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work --- # Finishing a Development Branch @@ -50,22 +50,20 @@ 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` (normal repo) | Standard 3 options | No worktree to clean up | +| `GIT_DIR != GIT_COMMON`, named branch | Standard 3 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?" +The base branch is whatever this work forked from — usually named in the +plan, the conversation, or the branch's upstream. If it is not already +known, ask: "This branch split from - is that correct?" +Don't guess silently: merging into the wrong base is expensive to undo. ### Step 4: Present Options -**Normal repo and named-branch worktree — present exactly these 4 options:** +**Normal repo and named-branch worktree — present exactly these 3 options:** ``` Implementation complete. What would you like to do? @@ -73,25 +71,27 @@ Implementation complete. What would you like to do? 1. Merge back to 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:** +**Detached HEAD — present exactly these 2 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. +Discarding the work is never offered. It exists only as a response to your +human partner explicitly asking for it (see "If your human partner asks to +discard the work" below). + ### Step 5: Execute Choice #### Option 1: Merge Locally @@ -112,6 +112,10 @@ git merge # Only after merge succeeds: cleanup worktree (Step 6), then delete branch ``` +If tests fail on the merged result: STOP. Leave the worktree and branch in +place and investigate — nothing has been pushed, so the merge is local and +recoverable. + Then: Cleanup worktree (Step 6), then delete branch: ```bash @@ -125,6 +129,11 @@ git branch -d git push -u origin ``` +Then create the pull/merge request against with the host's +tooling (`gh pr create`, `glab mr create`, or the URL git prints on push), +following the repo's PR template and conventions if present, and report +the URL to your human partner. + **Do NOT clean up worktree** — user needs it alive to iterate on PR feedback. #### Option 3: Keep As-Is @@ -133,9 +142,11 @@ Report: "Keeping branch . Worktree preserved at ." **Don't cleanup worktree.** -#### Option 4: Discard +#### If your human partner asks to discard the work + +Never offer this. Only do it when your human partner explicitly asks to +throw the work away — and even then, confirm first: -**Confirm first:** ``` This will permanently delete: - Branch @@ -160,7 +171,7 @@ git branch -D ### Step 6: Cleanup Workspace -**Only runs for Options 1 and 4.** Options 2 and 3 always preserve the worktree. +**Only runs for Option 1 and confirmed discards.** Options 2 and 3 always preserve the worktree. ```bash GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P) @@ -188,7 +199,7 @@ git worktree prune # Self-healing: clean up any stale registrations | 1. Merge locally | yes | - | - | yes | | 2. Create PR | - | yes | yes | - | | 3. Keep as-is | - | - | yes | - | -| 4. Discard | - | - | - | yes (force) | +| Discard (explicit request only) | - | - | - | yes (force) | ## Common Mistakes @@ -198,11 +209,15 @@ git worktree prune # Self-healing: clean up any stale registrations **Open-ended questions** - **Problem:** "What should I do next?" is ambiguous -- **Fix:** Present exactly 4 structured options (or 3 for detached HEAD) +- **Fix:** Present exactly 3 structured options (or 2 for detached HEAD) + +**Offering to discard the work** +- **Problem:** Puts throwing away completed, passing work on the menu +- **Fix:** Discard only on your human partner's explicit request, never as an offer **Cleaning up worktree for Option 2** - **Problem:** Remove worktree user needs for PR iteration -- **Fix:** Only cleanup for Options 1 and 4 +- **Fix:** Only cleanup for Option 1 and confirmed discards **Deleting branch before removing worktree** - **Problem:** `git branch -d` fails because worktree still references the branch @@ -225,6 +240,7 @@ git worktree prune # Self-healing: clean up any stale registrations **Never:** - Proceed with failing tests - Merge without verifying tests on result +- Offer discarding the work — it happens only on explicit request - Delete work without confirmation - Force-push without explicit request - Remove a worktree before confirming merge success @@ -234,8 +250,8 @@ git worktree prune # Self-healing: clean up any stale registrations **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 +- Present exactly 3 options (or 2 for detached HEAD) +- Get typed confirmation before any discard +- Clean up worktree for Option 1 and confirmed discards only - `cd` to main repo root before worktree removal - Run `git worktree prune` after removal From 6f81c378aca8d0b0cd82c4a9e145e09fde95618d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 11:25:59 -0700 Subject: [PATCH 015/198] refactor(skills): make PR creation forge-agnostic in finishing-a-development-branch Naming gh and glab implicitly blessed two forges; Gitea, Forgejo, Bitbucket and others are equally valid. Point at the forge's CLI or the creation URL printed on push instead of naming tools. --- skills/finishing-a-development-branch/SKILL.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/skills/finishing-a-development-branch/SKILL.md b/skills/finishing-a-development-branch/SKILL.md index 368829fd8..e25420bc7 100644 --- a/skills/finishing-a-development-branch/SKILL.md +++ b/skills/finishing-a-development-branch/SKILL.md @@ -129,10 +129,10 @@ git branch -d git push -u origin ``` -Then create the pull/merge request against with the host's -tooling (`gh pr create`, `glab mr create`, or the URL git prints on push), -following the repo's PR template and conventions if present, and report -the URL to your human partner. +Then create the pull/merge request against with the forge's +tooling — its CLI if one is available, or the creation URL most forges +print when you push — following the repo's PR template and conventions if +present, and report the URL to your human partner. **Do NOT clean up worktree** — user needs it alive to iterate on PR feedback. From df938188560a0695ccc83909cf065dc3a0780200 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 11:43:34 -0700 Subject: [PATCH 016/198] refactor(skills): compress finishing-a-development-branch, adopt rationalization table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Red Flags and Common Mistakes fold into one Common Rationalizations table (house Excuse/Reality form); every prior entry maps to a table row or an inline sentence in the step it guards. Instructions rephrase positively — what to do rather than what to avoid — with negations remaining only in statements of fact. Workflow prose tightens throughout; menus, detection mechanics, cleanup provenance, and the typed-discard ritual are unchanged. Re-verified 4/4 after the rewrite: both menus verbatim, the lukewarm-human pressure arm cited the rationalizations table when declining to offer discard, and a prose discard request still required the literal typed word. --- .../finishing-a-development-branch/SKILL.md | 153 ++++++------------ 1 file changed, 49 insertions(+), 104 deletions(-) diff --git a/skills/finishing-a-development-branch/SKILL.md b/skills/finishing-a-development-branch/SKILL.md index e25420bc7..7f6e4ec79 100644 --- a/skills/finishing-a-development-branch/SKILL.md +++ b/skills/finishing-a-development-branch/SKILL.md @@ -7,39 +7,25 @@ description: Use when implementation is complete, all tests pass, and you need t ## 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 -### Step 1: Verify Tests +Run the project's full test suite (`npm test` / `cargo test` / `pytest` / `go test ./...`). -**Before presenting options, verify tests pass:** +**If tests fail**, report the failures and stop — the menu comes after a green suite: -```bash -# Run project's test suite -npm test / cargo test / pytest / go test ./... -``` - -**If tests fail:** ``` Tests failing ( 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. -**If tests pass:** Continue to Step 2. - -### Step 2: Detect Environment - -**Determine workspace state before presenting options:** +## Step 2: Detect Environment ```bash GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P) @@ -52,16 +38,16 @@ This determines which menu to show and how cleanup works: |-------|------|---------| | `GIT_DIR == GIT_COMMON` (normal repo) | Standard 3 options | No worktree to clean up | | `GIT_DIR != GIT_COMMON`, named branch | Standard 3 options | Provenance-based (see Step 6) | -| `GIT_DIR != GIT_COMMON`, detached HEAD | Reduced 3 options (no merge) | No cleanup (externally managed) | +| `GIT_DIR != GIT_COMMON`, detached HEAD | Reduced 2 options (no merge) | Externally managed — leave in place | -### Step 3: Determine Base Branch +## Step 3: Determine Base Branch The base branch is whatever this work forked from — usually named in the plan, the conversation, or the branch's upstream. If it is not already known, ask: "This branch split from - is that correct?" -Don't guess silently: merging into the wrong base is expensive to undo. +Confirm before merging: merging into the wrong base is expensive to undo. -### Step 4: Present Options +## Step 4: Present Options **Normal repo and named-branch worktree — present exactly these 3 options:** @@ -86,15 +72,15 @@ Implementation complete. You're on a detached HEAD (externally managed workspace Which option? ``` -**Don't add explanation** - keep options concise. - -Discarding the work is never offered. It exists only as a response to your +Present the menu exactly as written — concise, with every option coming +from the list above. Discarding the work happens only in response to your human partner explicitly asking for it (see "If your human partner asks to -discard the work" below). +discard the work" below). Wait for their answer; the integration decision +is theirs. -### Step 5: Execute Choice +## Step 5: Execute Choice -#### Option 1: Merge Locally +### Option 1: Merge Locally ```bash # Get main repo root for CWD safety @@ -108,24 +94,22 @@ git merge # Verify tests on merged result - -# Only after merge succeeds: cleanup worktree (Step 6), then delete branch ``` -If tests fail on the merged result: STOP. Leave the worktree and branch in -place and investigate — nothing has been pushed, so the merge is local and -recoverable. +If tests fail on the merged result: stop, leave the worktree and branch in +place, and investigate — nothing has been pushed, so the merge is local +and recoverable. -Then: Cleanup worktree (Step 6), then delete branch: +Once the merged result is green: clean up the worktree (Step 6), then +delete the branch: ```bash git branch -d ``` -#### Option 2: Push and Create PR +### Option 2: Push and Create PR ```bash -# Push branch git push -u origin ``` @@ -134,18 +118,16 @@ tooling — its CLI if one is available, or the creation URL most forges print when you push — following the repo's PR template and conventions if present, and report the URL to your human partner. -**Do NOT clean up worktree** — user needs it alive to iterate on PR feedback. +Keep the worktree — your human partner iterates on PR feedback there. -#### Option 3: Keep As-Is +### Option 3: Keep As-Is Report: "Keeping branch . Worktree preserved at ." -**Don't cleanup worktree.** +### If your human partner asks to discard the work -#### If your human partner asks to discard the work - -Never offer this. Only do it when your human partner explicitly asks to -throw the work away — and even then, confirm first: +This path exists only as a response to an explicit request to throw the +work away. Confirm first: ``` This will permanently delete: @@ -156,22 +138,23 @@ This will permanently delete: Type 'discard' to confirm. ``` -Wait for exact confirmation. +Wait for that exact confirmation. When it arrives: -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: +Then clean up the worktree (Step 6) and force-delete the branch: + ```bash git branch -D ``` -### Step 6: Cleanup Workspace +## Step 6: Cleanup Workspace -**Only runs for Option 1 and confirmed discards.** Options 2 and 3 always preserve the worktree. +**Runs for Option 1 and confirmed discards.** Options 2 and 3 always +preserve the worktree. ```bash GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P) @@ -181,7 +164,9 @@ 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/` or `worktrees/`:** Superpowers created this worktree — we own cleanup. +**If worktree path is under `.worktrees/` or `worktrees/`:** Superpowers +created this worktree — we own cleanup. Run it from the main repo root +(removal fails from inside the worktree being removed): ```bash MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel) @@ -190,7 +175,8 @@ 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. +**Otherwise:** The host environment owns this workspace — leave it in +place. If your platform provides a workspace-exit tool, use it. ## Quick Reference @@ -201,57 +187,16 @@ git worktree prune # Self-healing: clean up any stale registrations | 3. Keep as-is | - | - | yes | - | | Discard (explicit request only) | - | - | - | yes (force) | -## Common Mistakes +## Common Rationalizations -**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 3 structured options (or 2 for detached HEAD) - -**Offering to discard the work** -- **Problem:** Puts throwing away completed, passing work on the menu -- **Fix:** Discard only on your human partner's explicit request, never as an offer - -**Cleaning up worktree for Option 2** -- **Problem:** Remove worktree user needs for PR iteration -- **Fix:** Only cleanup for Option 1 and confirmed discards - -**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/` or `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 -- Offer discarding the work — it happens only on explicit request -- 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 3 options (or 2 for detached HEAD) -- Get typed confirmation before any discard -- Clean up worktree for Option 1 and confirmed discards only -- `cd` to main repo root before worktree removal -- Run `git worktree prune` after removal +| Excuse | Reality | +|--------|---------| +| "Tests passed earlier this session" | Run the suite now. The tree changed since the last green run. | +| "They obviously want it merged" | Integration is your human partner's decision. Present the menu and wait. | +| "They seem done with this feature — I'll offer to discard it" | The menu is complete as written. Discard happens only when your human partner asks for it in so many words. | +| "'Yeah, get rid of it' counts as confirmation" | Only the typed word `discard` authorizes deletion. | +| "The PR is up, so the worktree is clutter now" | PR feedback gets fixed in that worktree. It stays until the work lands. | +| "This other worktree looks stale — I'll clean it too" | Clean up only worktrees under `.worktrees/` or `worktrees/`. Everything else belongs to the host. | +| "The merged-result failure is probably flaky" | A failing merged result stops everything. Branch and worktree stay put while you investigate. | +| "The base branch is obviously main" | Confirm the fork point or ask. Merging into the wrong base is expensive to undo. | +| "The push was rejected — force-push will fix it" | A rejected push means the remote moved. Investigate; force-push only on your human partner's explicit request. | From f68c94334d6cd7b6bb760583970344c24e1d3858 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:00:35 -0700 Subject: [PATCH 017/198] fix(skills): capture worktree path before Step 5 changes directory Step 6 recomputed WORKTREE_PATH after Option 1 and discard had already cd'd to the main repo root, so --show-toplevel returned the main root: the provenance check could never match, cleanup silently no-oped, and the branch delete failed with the worktree still attached. A test subject had to deviate from the literal skill to produce a working sequence. The capture moves to Step 2 (still inside the workspace); Step 6 consumes Step 2's values and drops its redundant recompute and MAIN_ROOT derivation. Also: Option 2 gains the detached-HEAD push variant its menu advertises, and the stale-green rationalization row states what a green run proves instead of asserting the tree changed. Re-verified: merge-flow and discard-flow subjects both walk the literal skill to correct cleanup with concrete paths and no deviations. --- .../finishing-a-development-branch/SKILL.md | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/skills/finishing-a-development-branch/SKILL.md b/skills/finishing-a-development-branch/SKILL.md index 7f6e4ec79..21a439ac3 100644 --- a/skills/finishing-a-development-branch/SKILL.md +++ b/skills/finishing-a-development-branch/SKILL.md @@ -30,6 +30,9 @@ Tests failing ( failures). Must fix before completing: ```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) +# Capture now, while still inside the workspace — Step 5 changes directory +# before cleanup (Step 6) needs this value +WORKTREE_PATH=$(git rev-parse --show-toplevel) ``` This determines which menu to show and how cleanup works: @@ -111,6 +114,8 @@ git branch -d ```bash git push -u origin +# From a detached HEAD, name the new branch on the remote: +# git push origin HEAD:refs/heads/ ``` Then create the pull/merge request against with the forge's @@ -154,23 +159,17 @@ git branch -D ## Step 6: Cleanup Workspace **Runs for Option 1 and confirmed discards.** 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) -``` +preserve the worktree. Both callers have already changed directory to the +main repo root — worktree removal must run from outside the worktree — +and use the `GIT_DIR`/`GIT_COMMON`/`WORKTREE_PATH` values captured in +Step 2, from before that directory change. **If `GIT_DIR == GIT_COMMON`:** Normal repo, no worktree to clean up. Done. -**If worktree path is under `.worktrees/` or `worktrees/`:** Superpowers -created this worktree — we own cleanup. Run it from the main repo root -(removal fails from inside the worktree being removed): +**If `WORKTREE_PATH` is under `.worktrees/` or `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 ``` @@ -191,7 +190,7 @@ place. If your platform provides a workspace-exit tool, use it. | Excuse | Reality | |--------|---------| -| "Tests passed earlier this session" | Run the suite now. The tree changed since the last green run. | +| "Tests passed earlier this session" | Run the suite on the tree you are about to integrate. A green run only proves the tree it ran on. | | "They obviously want it merged" | Integration is your human partner's decision. Present the menu and wait. | | "They seem done with this feature — I'll offer to discard it" | The menu is complete as written. Discard happens only when your human partner asks for it in so many words. | | "'Yeah, get rid of it' counts as confirmation" | Only the typed word `discard` authorizes deletion. | From 40b2f3aacaa9ee228cba95146c7c0c14c0e1531d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:49:52 -0700 Subject: [PATCH 018/198] refactor(skills): reframe testing-anti-patterns as writing-good-tests The disclosure doc becomes a catalog of what to do: six positively named rules (assert on real behavior, cleanup in test utilities, mock at the right level, mirror real data, tests ship with implementation, prefer real components), each leading with the GOOD example and keeping the violation as contrast. Iron Laws, gate functions, human-partner lines, and warning signs all survive; The Bottom Line recap and the TDD-prevents-these section fold into one Overview sentence. SKILL.md's pointer moves into the Good Tests section it belongs with. Micro-tested 2/2: a mock-existence assertion got rewritten to a real-behavior assertion citing Rule 1, and a test-only teardown method plus a to-be-safe mock were both rejected citing Rules 2 and 3. --- skills/test-driven-development/SKILL.md | 12 +- .../testing-anti-patterns.md | 299 ------------------ .../writing-good-tests.md | 248 +++++++++++++++ 3 files changed, 253 insertions(+), 306 deletions(-) delete mode 100644 skills/test-driven-development/testing-anti-patterns.md create mode 100644 skills/test-driven-development/writing-good-tests.md diff --git a/skills/test-driven-development/SKILL.md b/skills/test-driven-development/SKILL.md index 60d2609ca..158cb0b51 100644 --- a/skills/test-driven-development/SKILL.md +++ b/skills/test-driven-development/SKILL.md @@ -203,6 +203,11 @@ Next failing test for next feature. | **Clear** | Name describes behavior | `test('test1')` | | **Shows intent** | Demonstrates desired API | Obscures what code should do | +When adding mocks or test utilities, read [writing-good-tests.md](writing-good-tests.md) for the rules that keep tests honest: +- Assert on real behavior, never on mock behavior +- Keep test-only code in test utilities, out of production classes +- Understand a dependency's side effects before mocking it + ## Why Order Matters **"I'll write tests after to verify it works"** @@ -354,13 +359,6 @@ Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix Never fix bugs without a test. -## Testing Anti-Patterns - -When adding mocks or test utilities, read [testing-anti-patterns.md](testing-anti-patterns.md) to avoid common pitfalls: -- Testing mock behavior instead of real behavior -- Adding test-only methods to production classes -- Mocking without understanding dependencies - ## Final Rule ``` diff --git a/skills/test-driven-development/testing-anti-patterns.md b/skills/test-driven-development/testing-anti-patterns.md deleted file mode 100644 index e77ab6b6d..000000000 --- a/skills/test-driven-development/testing-anti-patterns.md +++ /dev/null @@ -1,299 +0,0 @@ -# Testing Anti-Patterns - -**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code. - -## Overview - -Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested. - -**Core principle:** Test what the code does, not what the mocks do. - -**Following strict TDD prevents these anti-patterns.** - -## The Iron Laws - -``` -1. NEVER test mock behavior -2. NEVER add test-only methods to production classes -3. NEVER mock without understanding dependencies -``` - -## Anti-Pattern 1: Testing Mock Behavior - -**The violation:** -```typescript -// ❌ BAD: Testing that the mock exists -test('renders sidebar', () => { - render(); - expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument(); -}); -``` - -**Why this is wrong:** -- You're verifying the mock works, not that the component works -- Test passes when mock is present, fails when it's not -- Tells you nothing about real behavior - -**your human partner's correction:** "Are we testing the behavior of a mock?" - -**The fix:** -```typescript -// ✅ GOOD: Test real component or don't mock it -test('renders sidebar', () => { - render(); // Don't mock sidebar - expect(screen.getByRole('navigation')).toBeInTheDocument(); -}); - -// OR if sidebar must be mocked for isolation: -// Don't assert on the mock - test Page's behavior with sidebar present -``` - -### Gate Function - -``` -BEFORE asserting on any mock element: - Ask: "Am I testing real component behavior or just mock existence?" - - IF testing mock existence: - STOP - Delete the assertion or unmock the component - - Test real behavior instead -``` - -## Anti-Pattern 2: Test-Only Methods in Production - -**The violation:** -```typescript -// ❌ BAD: destroy() only used in tests -class Session { - async destroy() { // Looks like production API! - await this._workspaceManager?.destroyWorkspace(this.id); - // ... cleanup - } -} - -// In tests -afterEach(() => session.destroy()); -``` - -**Why this is wrong:** -- Production class polluted with test-only code -- Dangerous if accidentally called in production -- Violates YAGNI and separation of concerns -- Confuses object lifecycle with entity lifecycle - -**The fix:** -```typescript -// ✅ GOOD: Test utilities handle test cleanup -// Session has no destroy() - it's stateless in production - -// In test-utils/ -export async function cleanupSession(session: Session) { - const workspace = session.getWorkspaceInfo(); - if (workspace) { - await workspaceManager.destroyWorkspace(workspace.id); - } -} - -// In tests -afterEach(() => cleanupSession(session)); -``` - -### Gate Function - -``` -BEFORE adding any method to production class: - Ask: "Is this only used by tests?" - - IF yes: - STOP - Don't add it - Put it in test utilities instead - - Ask: "Does this class own this resource's lifecycle?" - - IF no: - STOP - Wrong class for this method -``` - -## Anti-Pattern 3: Mocking Without Understanding - -**The violation:** -```typescript -// ❌ BAD: Mock breaks test logic -test('detects duplicate server', () => { - // Mock prevents config write that test depends on! - vi.mock('ToolCatalog', () => ({ - discoverAndCacheTools: vi.fn().mockResolvedValue(undefined) - })); - - await addServer(config); - await addServer(config); // Should throw - but won't! -}); -``` - -**Why this is wrong:** -- Mocked method had side effect test depended on (writing config) -- Over-mocking to "be safe" breaks actual behavior -- Test passes for wrong reason or fails mysteriously - -**The fix:** -```typescript -// ✅ GOOD: Mock at correct level -test('detects duplicate server', () => { - // Mock the slow part, preserve behavior test needs - vi.mock('MCPServerManager'); // Just mock slow server startup - - await addServer(config); // Config written - await addServer(config); // Duplicate detected ✓ -}); -``` - -### Gate Function - -``` -BEFORE mocking any method: - STOP - Don't mock yet - - 1. Ask: "What side effects does the real method have?" - 2. Ask: "Does this test depend on any of those side effects?" - 3. Ask: "Do I fully understand what this test needs?" - - IF depends on side effects: - Mock at lower level (the actual slow/external operation) - OR use test doubles that preserve necessary behavior - NOT the high-level method the test depends on - - IF unsure what test depends on: - Run test with real implementation FIRST - Observe what actually needs to happen - THEN add minimal mocking at the right level - - Red flags: - - "I'll mock this to be safe" - - "This might be slow, better mock it" - - Mocking without understanding the dependency chain -``` - -## Anti-Pattern 4: Incomplete Mocks - -**The violation:** -```typescript -// ❌ BAD: Partial mock - only fields you think you need -const mockResponse = { - status: 'success', - data: { userId: '123', name: 'Alice' } - // Missing: metadata that downstream code uses -}; - -// Later: breaks when code accesses response.metadata.requestId -``` - -**Why this is wrong:** -- **Partial mocks hide structural assumptions** - You only mocked fields you know about -- **Downstream code may depend on fields you didn't include** - Silent failures -- **Tests pass but integration fails** - Mock incomplete, real API complete -- **False confidence** - Test proves nothing about real behavior - -**The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses. - -**The fix:** -```typescript -// ✅ GOOD: Mirror real API completeness -const mockResponse = { - status: 'success', - data: { userId: '123', name: 'Alice' }, - metadata: { requestId: 'req-789', timestamp: 1234567890 } - // All fields real API returns -}; -``` - -### Gate Function - -``` -BEFORE creating mock responses: - Check: "What fields does the real API response contain?" - - Actions: - 1. Examine actual API response from docs/examples - 2. Include ALL fields system might consume downstream - 3. Verify mock matches real response schema completely - - Critical: - If you're creating a mock, you must understand the ENTIRE structure - Partial mocks fail silently when code depends on omitted fields - - If uncertain: Include all documented fields -``` - -## Anti-Pattern 5: Integration Tests as Afterthought - -**The violation:** -``` -✅ Implementation complete -❌ No tests written -"Ready for testing" -``` - -**Why this is wrong:** -- Testing is part of implementation, not optional follow-up -- TDD would have caught this -- Can't claim complete without tests - -**The fix:** -``` -TDD cycle: -1. Write failing test -2. Implement to pass -3. Refactor -4. THEN claim complete -``` - -## When Mocks Become Too Complex - -**Warning signs:** -- Mock setup longer than test logic -- Mocking everything to make test pass -- Mocks missing methods real components have -- Test breaks when mock changes - -**your human partner's question:** "Do we need to be using a mock here?" - -**Consider:** Integration tests with real components often simpler than complex mocks - -## TDD Prevents These Anti-Patterns - -**Why TDD helps:** -1. **Write test first** → Forces you to think about what you're actually testing -2. **Watch it fail** → Confirms test tests real behavior, not mocks -3. **Minimal implementation** → No test-only methods creep in -4. **Real dependencies** → You see what the test actually needs before mocking - -**If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first. - -## Quick Reference - -| Anti-Pattern | Fix | -|--------------|-----| -| Assert on mock elements | Test real component or unmock it | -| Test-only methods in production | Move to test utilities | -| Mock without understanding | Understand dependencies first, mock minimally | -| Incomplete mocks | Mirror real API completely | -| Tests as afterthought | TDD - tests first | -| Over-complex mocks | Consider integration tests | - -## Red Flags - -- Assertion checks for `*-mock` test IDs -- Methods only called in test files -- Mock setup is >50% of test -- Test fails when you remove mock -- Can't explain why mock is needed -- Mocking "just to be safe" - -## The Bottom Line - -**Mocks are tools to isolate, not things to test.** - -If TDD reveals you're testing mock behavior, you've gone wrong. - -Fix: Test real behavior or question why you're mocking at all. diff --git a/skills/test-driven-development/writing-good-tests.md b/skills/test-driven-development/writing-good-tests.md new file mode 100644 index 000000000..ad8c6023f --- /dev/null +++ b/skills/test-driven-development/writing-good-tests.md @@ -0,0 +1,248 @@ +# Writing Good Tests + +**Load this reference when:** writing or changing tests, adding mocks, or +adding cleanup/helper methods for tests. + +## Overview + +Good tests verify real behavior. Mocks exist to isolate the code under +test — they are never the thing being tested. + +**Core principle:** Test what the code does, not what the mocks do. + +Strict TDD produces every rule below naturally: a test written first and +watched failing against real code only earns a mock when the real +dependency proves slow or external. A test asserting on a mock means TDD +was skipped somewhere. + +## The Iron Laws + +``` +1. Assert on real behavior, never on mock behavior +2. Production classes carry production methods only +3. Understand a dependency's side effects before mocking it +``` + +## Rule 1: Assert on Real Behavior + +```typescript +// ✅ GOOD: Test the real component +test('renders sidebar', () => { + render(); // Sidebar unmocked + expect(screen.getByRole('navigation')).toBeInTheDocument(); +}); +``` + +If the sidebar must be mocked for isolation, assert on Page's behavior +with the sidebar present — the mock itself earns no assertions. + +```typescript +// ❌ The violation: asserting that the mock exists +test('renders sidebar', () => { + render(); + expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument(); +}); +``` + +A mock assertion passes when the mock is present and fails when it is +absent — it says nothing about the component. **your human partner's +correction:** "Are we testing the behavior of a mock?" + +### Gate Function + +``` +BEFORE asserting on any mock element: + Ask: "Am I testing real component behavior or just mock existence?" + + IF testing mock existence: + STOP - Delete the assertion or unmock the component + + Test real behavior instead +``` + +## Rule 2: Keep Test Cleanup in Test Utilities + +```typescript +// ✅ GOOD: Test utilities own test cleanup +// Session has no destroy() - it's stateless in production + +// In test-utils/ +export async function cleanupSession(session: Session) { + const workspace = session.getWorkspaceInfo(); + if (workspace) { + await workspaceManager.destroyWorkspace(workspace.id); + } +} + +// In tests +afterEach(() => cleanupSession(session)); +``` + +```typescript +// ❌ The violation: destroy() exists only for tests +class Session { + async destroy() { // Looks like production API! + await this._workspaceManager?.destroyWorkspace(this.id); + // ... cleanup + } +} + +// In tests +afterEach(() => session.destroy()); +``` + +A test-only method pollutes the production class, is dangerous if +production code ever calls it, and confuses object lifecycle with entity +lifecycle. + +### Gate Function + +``` +BEFORE adding any method to a production class: + Ask: "Is this only used by tests?" + + IF yes: + STOP - Put it in test utilities instead + + Ask: "Does this class own this resource's lifecycle?" + + IF no: + STOP - Wrong class for this method +``` + +## Rule 3: Mock at the Right Level + +Learn what the real method does — every side effect — before replacing +it. Mock the slow or external operation and preserve the behavior your +test depends on. + +```typescript +// ✅ GOOD: Mock the slow part, preserve behavior the test needs +test('detects duplicate server', () => { + vi.mock('MCPServerManager'); // Just mock slow server startup + + await addServer(config); // Config written + await addServer(config); // Duplicate detected ✓ +}); +``` + +```typescript +// ❌ The violation: the mock swallows the side effect the test depends on +test('detects duplicate server', () => { + // Mock prevents the config write that duplicate detection reads! + vi.mock('ToolCatalog', () => ({ + discoverAndCacheTools: vi.fn().mockResolvedValue(undefined) + })); + + await addServer(config); + await addServer(config); // Should throw - but won't! +}); +``` + +### Gate Function + +``` +BEFORE mocking any method: + STOP - Understand before replacing + + 1. Ask: "What side effects does the real method have?" + 2. Ask: "Does this test depend on any of those side effects?" + 3. Ask: "Do I fully understand what this test needs?" + + IF the test depends on side effects: + Mock at the lower level (the actual slow/external operation) + OR use test doubles that preserve the necessary behavior + — keep the high-level method the test depends on real + + IF unsure what the test depends on: + Run the test with the real implementation FIRST + Observe what actually needs to happen + THEN add minimal mocking at the right level + + Warning signs: + - "I'll mock this to be safe" + - "This might be slow, better mock it" + - Mocking before tracing the dependency chain +``` + +## Rule 4: Mirror Real Data Completely + +Mock the COMPLETE data structure as it exists in reality, not just the +fields your immediate test uses. + +```typescript +// ✅ GOOD: Mirror real API completeness +const mockResponse = { + status: 'success', + data: { userId: '123', name: 'Alice' }, + metadata: { requestId: 'req-789', timestamp: 1234567890 } + // All fields real API returns +}; +``` + +```typescript +// ❌ The violation: only the fields you thought you needed +const mockResponse = { + status: 'success', + data: { userId: '123', name: 'Alice' } + // Missing: metadata that downstream code uses +}; + +// Later: breaks when code accesses response.metadata.requestId +``` + +Partial mocks hide structural assumptions and fail silently when +downstream code reads an omitted field: the test passes while integration +breaks. + +### Gate Function + +``` +BEFORE creating mock responses: + Check: "What fields does the real API response contain?" + + Actions: + 1. Examine the actual API response from docs/examples + 2. Include ALL fields the system might consume downstream + 3. Verify the mock matches the real response schema completely + + If uncertain: include all documented fields +``` + +## Rule 5: Tests Ship With the Implementation + +Testing is part of implementation. The TDD cycle — failing test, minimal +implementation, refactor — is what "complete" means; "implementation +complete, ready for testing" describes an unfinished task. + +## Rule 6: Prefer Real Components Over Complex Mocks + +Integration tests with real components are often simpler than elaborate +mocks. Reach for one when you see: + +- Mock setup longer than the test logic +- Mocking everything to make the test pass +- Mocks missing methods the real components have +- Tests breaking when the mock changes + +**your human partner's question:** "Do we need to be using a mock here?" + +## Quick Reference + +| When you... | Do | +|-------------|-----| +| Want to assert on a mocked element | Test the real component, or unmock it | +| Need cleanup that only tests use | Put it in test utilities | +| Are about to mock a method | Learn its side effects first; mock the slow/external level | +| Build a mock response | Mirror the real structure completely | +| Finish an implementation | Tests already exist (TDD) — or it is unfinished | +| Watch mock setup balloon | Switch to an integration test with real components | + +## Warning Signs + +- An assertion checks for a `*-mock` test ID +- A method is called only from test files +- Mock setup is more than half the test +- The test fails when you remove the mock +- You can't explain why the mock is needed +- Mocking "just to be safe" From 6a8869c7d2f0fead8ceba1a02271b6a5c596cea1 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:51:57 -0700 Subject: [PATCH 019/198] fix(skills): broaden writing-good-tests trigger to any test writing The pointer fired only on adding mocks or test utilities; the doc's own load-when line already says writing or changing tests. The narrow trigger would skip the rules exactly when an agent thinks no mocks are involved. --- skills/test-driven-development/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/test-driven-development/SKILL.md b/skills/test-driven-development/SKILL.md index 158cb0b51..d6f4e7c79 100644 --- a/skills/test-driven-development/SKILL.md +++ b/skills/test-driven-development/SKILL.md @@ -203,7 +203,7 @@ Next failing test for next feature. | **Clear** | Name describes behavior | `test('test1')` | | **Shows intent** | Demonstrates desired API | Obscures what code should do | -When adding mocks or test utilities, read [writing-good-tests.md](writing-good-tests.md) for the rules that keep tests honest: +When writing or changing any test, read [writing-good-tests.md](writing-good-tests.md) for the rules that keep tests honest: - Assert on real behavior, never on mock behavior - Keep test-only code in test utilities, out of production classes - Understand a dependency's side effects before mocking it From 6a2d0c211f79e64dfcbc83277072e9a0a29db17c Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:59:56 -0700 Subject: [PATCH 020/198] feat(skills): absorb falsifiability discipline into writing-good-tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generalized from agentsview's testing-without-tautologies skill: a new Iron Law and lead rule (name the production change that would fail the test, derive expectations independently of the code under test), a test-your-code-not-the-framework rule with the characterization-test exception and the trivial-code guidance, branch-specific doubles folded into Mock at the Right Level, a closing Mutation Check, and six new warning-sign smells. Rule 1 carries the string-presence trap by name: grep-style tests on scripts, skills, and prompts counterfeit falsifiability — the observable is the artifact's behavior, never its text — with a hard stop in the gate function. Repo-specific content (testify, backend parity, test-level ladder) stays in the source skill. Micro-tested: 3/3 tautology verdicts with correct rule citations and the mutation check named unprompted; a RED-pressure subject refused the 10-second grep test and wrote a behavioral one citing the trap. --- skills/test-driven-development/SKILL.md | 1 + .../writing-good-tests.md | 157 ++++++++++++++++-- 2 files changed, 145 insertions(+), 13 deletions(-) diff --git a/skills/test-driven-development/SKILL.md b/skills/test-driven-development/SKILL.md index d6f4e7c79..3eccc6585 100644 --- a/skills/test-driven-development/SKILL.md +++ b/skills/test-driven-development/SKILL.md @@ -204,6 +204,7 @@ Next failing test for next feature. | **Shows intent** | Demonstrates desired API | Obscures what code should do | When writing or changing any test, read [writing-good-tests.md](writing-good-tests.md) for the rules that keep tests honest: +- Name the production change that would make the test fail — before writing it - Assert on real behavior, never on mock behavior - Keep test-only code in test utilities, out of production classes - Understand a dependency's side effects before mocking it diff --git a/skills/test-driven-development/writing-good-tests.md b/skills/test-driven-development/writing-good-tests.md index ad8c6023f..81e9728a4 100644 --- a/skills/test-driven-development/writing-good-tests.md +++ b/skills/test-driven-development/writing-good-tests.md @@ -8,22 +8,86 @@ adding cleanup/helper methods for tests. Good tests verify real behavior. Mocks exist to isolate the code under test — they are never the thing being tested. -**Core principle:** Test what the code does, not what the mocks do. +**Core principle:** Test what the code does, not what the mocks do — and +make every test able to fail. Strict TDD produces every rule below naturally: a test written first and -watched failing against real code only earns a mock when the real -dependency proves slow or external. A test asserting on a mock means TDD -was skipped somewhere. +watched failing against real code has already proven it can fail, and +only earns a mock when the real dependency proves slow or external. A +test asserting on a mock means TDD was skipped somewhere. ## The Iron Laws ``` -1. Assert on real behavior, never on mock behavior -2. Production classes carry production methods only -3. Understand a dependency's side effects before mocking it +1. Every test can fail — name the production change that would fail it +2. Assert on real behavior, never on mock behavior +3. Production classes carry production methods only +4. Understand a dependency's side effects before mocking it ``` -## Rule 1: Assert on Real Behavior +## Rule 1: Write Tests That Can Fail + +Before writing or changing a test, name the production change that would +make it fail. If you cannot, redesign the test around an observable +behavior — a test that cannot fail protects nothing. + +Derive expected values independently of the code under test: literals, +hand-checked fixtures, small worked examples, or invariant assertions. +Keep test logic simple enough to review by inspection — table-driven +tests with literal `want` values are the preferred shape. + +```typescript +// ✅ GOOD: literal, hand-derived expectation +test('builds tag query', () => { + expect(buildSearchQuery({ tag: 'urgent' })).toBe('tag:"urgent"'); +}); +``` + +```typescript +// ❌ The violation: expectation computed by the logic under test +test('builds tag query', () => { + const expected = buildSearchQuery({ tag: 'urgent' }); // same builder! + expect(buildSearchQuery({ tag: 'urgent' })).toBe(expected); // always true +}); + +// ❌ Subtler: the expectation reuses the same helper the code calls +test('formats timestamp', () => { + expect(render(entry)).toContain(formatTime(entry.ts)); // mirrors implementation +}); +``` + +A mirror assertion re-derives the answer with the answer's own machinery: +it passes no matter what that machinery does. + +**The string-presence trap.** For a script, skill, prompt, or config, a +test that asserts the source contains an exact line counterfeits this +rule: it can fail (delete the line), so it passes the letter of +falsifiability while asserting only that the source is the source. It +breaks on every legitimate rewording and survives every real regression. +The observable for a script is what it does — run it against controlled +inputs and assert outputs, side effects, or exit codes. The observable +for a document that instructs an agent is the consuming agent's behavior +— pressure-test it. Text containment is never the observable. + +### Gate Function + +``` +BEFORE writing the test body: + Ask: "What production change should make this test fail?" + + IF you cannot name one: + STOP - Redesign the test around an observable behavior + + IF the only answer is "the source text changed": + STOP - Run the artifact and assert its effects instead + + Ask: "Is the expected value derived independently of the code under test?" + + IF it reuses the code's own logic or helpers: + STOP - Replace it with a literal or hand-checked fixture +``` + +## Rule 2: Assert on Real Behavior ```typescript // ✅ GOOD: Test the real component @@ -60,7 +124,7 @@ BEFORE asserting on any mock element: Test real behavior instead ``` -## Rule 2: Keep Test Cleanup in Test Utilities +## Rule 3: Keep Test Cleanup in Test Utilities ```typescript // ✅ GOOD: Test utilities own test cleanup @@ -110,12 +174,18 @@ BEFORE adding any method to a production class: STOP - Wrong class for this method ``` -## Rule 3: Mock at the Right Level +## Rule 4: Mock at the Right Level Learn what the real method does — every side effect — before replacing it. Mock the slow or external operation and preserve the behavior your test depends on. +Make doubles specific to their contract: when arguments, call counts, or +ordering matter, assert them — a fake that accepts anything verifies +nothing. And give each branch its own double: success, error, and +malformed paths each get their own fixture or spy, so the wrong branch +cannot satisfy the expectation. + ```typescript // ✅ GOOD: Mock the slow part, preserve behavior the test needs test('detects duplicate server', () => { @@ -165,7 +235,7 @@ BEFORE mocking any method: - Mocking before tracing the dependency chain ``` -## Rule 4: Mirror Real Data Completely +## Rule 5: Mirror Real Data Completely Mock the COMPLETE data structure as it exists in reality, not just the fields your immediate test uses. @@ -209,13 +279,50 @@ BEFORE creating mock responses: If uncertain: include all documented fields ``` -## Rule 5: Tests Ship With the Implementation +## Rule 6: Test Your Code, Not the Framework + +Test the contract your code makes at its boundaries — the route you +register, the query you emit, the payload shape you produce, the value +handoff between layers. Dependencies' documented mechanics are their +maintainers' tests to write. + +```typescript +// ✅ GOOD: your contract at the boundary +test('GET /sessions/:id returns 404 for unknown id', async () => { + const res = await request(app).get('/sessions/nope'); + expect(res.status).toBe(404); + expect(res.body.error).toBe('session not found'); +}); +``` + +```typescript +// ❌ The violation: re-proving the router works as documented +test('router calls handler for matching route', () => { + const handler = vi.fn(); + router.get('/x', handler); + router.handle(makeRequest('/x')); + expect(handler).toHaveBeenCalled(); +}); +``` + +When upstream behavior genuinely surprised you (a quoting rule, an event +ordering), write one narrow characterization test around your integration +point and name the assumption in the test name or a comment. + +The same boundary applies inside your own code: test behavior, not that +the implementation is written the way it is currently written. Plain +constructor assignment, getters, trivial forwarding, and data-only +structs earn tests only when they validate, normalize, default, derive, +enforce, or cause side effects — otherwise assert the first +consumer-visible result that depends on them. + +## Rule 7: Tests Ship With the Implementation Testing is part of implementation. The TDD cycle — failing test, minimal implementation, refactor — is what "complete" means; "implementation complete, ready for testing" describes an unfinished task. -## Rule 6: Prefer Real Components Over Complex Mocks +## Rule 8: Prefer Real Components Over Complex Mocks Integration tests with real components are often simpler than elaborate mocks. Reach for one when you see: @@ -227,15 +334,33 @@ mocks. Reach for one when you see: **your human partner's question:** "Do we need to be using a mock here?" +## The Mutation Check + +Before finishing, mentally mutate the production code. At least one test +should fail for each realistic mutation: + +- Wrong constant or argument +- Wrong branch handler +- Missing state change or side effect (row not written, event not emitted) +- Empty or default return +- Missing validation for zero, empty, nil, unauthorized, or malformed input + +A mutation no test can catch marks the behavior as unprotected — or the +test as tautological. + ## Quick Reference | When you... | Do | |-------------|-----| +| Write any test | Name the production change that would make it fail | +| Build an expected value | Derive it independently — literal or hand-checked fixture | | Want to assert on a mocked element | Test the real component, or unmock it | | Need cleanup that only tests use | Put it in test utilities | | Are about to mock a method | Learn its side effects first; mock the slow/external level | | Build a mock response | Mirror the real structure completely | +| Reach for a dependency test | Test your boundary contract, not their documented mechanics | | Finish an implementation | Tests already exist (TDD) — or it is unfinished | +| Finish a test file | Run the mutation check | | Watch mock setup balloon | Switch to an integration test with real components | ## Warning Signs @@ -246,3 +371,9 @@ mocks. Reach for one when you see: - The test fails when you remove the mock - You can't explain why the mock is needed - Mocking "just to be safe" +- Setup and assertion share the same object, guaranteeing equality +- The test can fail only through a panic, crash, or missing selector +- The test would still matter if only the framework remained +- Expected values are hidden behind loops, builders, or helpers +- The test greps source text instead of observing behavior +- The test asserts that a removed function, file, or symbol stays removed From cb830c74fb7466951d1593c9a02db9a64a498aa0 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 13:03:35 -0700 Subject: [PATCH 021/198] fix(skills): close the change-detector hole in writing-good-tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes review found falsifiable-but-worthless tests passed every rule: a constant assertion can fail, uses a literal, mocks nothing — and protects nothing, firing on intentional decisions while sleeping through bugs. Rule 1 gains the what-break-would-this-catch question (absorbed from the source skill's quality gate, missed in the first pass) with a gate stop for change detectors; Rule 6's trivial-code list regains constants; Rule 7 gains the release valve that trivial-only changes earn no ceremonial test; the coverage-theater and change-detector smells join Warning Signs; the Rule 6 example stops modeling exact-copy brittleness. Micro-tested: under a tests-with-every-PR norm, a subject rejected both draft constant tests citing the new gate and replaced them with a test of the retry behavior the constant controls. --- .../writing-good-tests.md | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/skills/test-driven-development/writing-good-tests.md b/skills/test-driven-development/writing-good-tests.md index 81e9728a4..6fba13428 100644 --- a/skills/test-driven-development/writing-good-tests.md +++ b/skills/test-driven-development/writing-good-tests.md @@ -59,6 +59,14 @@ test('formats timestamp', () => { A mirror assertion re-derives the answer with the answer's own machinery: it passes no matter what that machinery does. +**Falsifiable is necessary, not sufficient — name the break.** A test must +fail for the right reason: name the wrong branch, missing side effect, +wrong argument, boundary case, or contract violation it would catch. If +every change that could fail it is an intentional decision — a constant's +value, the exact wording of a message, private structure — you have +written a change detector, not a test: it fires on redesign and sleeps +through bugs. Test the behavior that depends on the decision instead. + **The string-presence trap.** For a script, skill, prompt, or config, a test that asserts the source contains an exact line counterfeits this rule: it can fail (delete the line), so it passes the letter of @@ -81,6 +89,12 @@ BEFORE writing the test body: IF the only answer is "the source text changed": STOP - Run the artifact and assert its effects instead + Ask: "What BREAK would this catch?" + + IF every failing change is an intentional decision, never a bug: + STOP - That is a change detector; test the behavior that + depends on the decision instead + Ask: "Is the expected value derived independently of the code under test?" IF it reuses the code's own logic or helpers: @@ -291,7 +305,7 @@ maintainers' tests to write. test('GET /sessions/:id returns 404 for unknown id', async () => { const res = await request(app).get('/sessions/nope'); expect(res.status).toBe(404); - expect(res.body.error).toBe('session not found'); + expect(res.body.error).toMatch(/not found/); // contract, not exact copy }); ``` @@ -311,9 +325,9 @@ point and name the assumption in the test name or a comment. The same boundary applies inside your own code: test behavior, not that the implementation is written the way it is currently written. Plain -constructor assignment, getters, trivial forwarding, and data-only -structs earn tests only when they validate, normalize, default, derive, -enforce, or cause side effects — otherwise assert the first +constructor assignment, getters, constants, trivial forwarding, and +data-only structs earn tests only when they validate, normalize, default, +derive, enforce, or cause side effects — otherwise assert the first consumer-visible result that depends on them. ## Rule 7: Tests Ship With the Implementation @@ -322,6 +336,10 @@ Testing is part of implementation. The TDD cycle — failing test, minimal implementation, refactor — is what "complete" means; "implementation complete, ready for testing" describes an unfinished task. +Ship the tests the behavior needs — and only those. A change that touches +only trivial code (Rule 6) earns no ceremonial test: a test written to +satisfy process protects nothing and costs maintenance forever. + ## Rule 8: Prefer Real Components Over Complex Mocks Integration tests with real components are often simpler than elaborate @@ -377,3 +395,5 @@ test as tautological. - Expected values are hidden behind loops, builders, or helpers - The test greps source text instead of observing behavior - The test asserts that a removed function, file, or symbol stays removed +- The test exists for coverage, checking no side effect, boundary, or outcome +- The test fails on every intentional change and never on accidental breakage From 5431cf3b1dbba93cce32ea47ea3ff84a87ff885f Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 17:47:02 -0400 Subject: [PATCH 022/198] refactor(skills): compress writing-good-tests additions; doc changes earn no tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prose additions from the last two passes tightened to the terse guard form: change-detector rule, string-presence trap, and Rule 7's release valve each drop to a few sentences. Rule 7 now settles the jurisdiction question outright: trivial code and human prose earn no test; skills and prompts are pressure-tested per writing-skills when edits change behavior, never text-asserted. Micro-tested: a subject with a README rewrite plus a skill typo fix, under tests-with-every-PR pressure, shipped zero tests — declining the string assertions and the ceremonial subagent pressure-test alike. --- .../writing-good-tests.md | 36 +++++++++---------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/skills/test-driven-development/writing-good-tests.md b/skills/test-driven-development/writing-good-tests.md index 6fba13428..3cae73bc2 100644 --- a/skills/test-driven-development/writing-good-tests.md +++ b/skills/test-driven-development/writing-good-tests.md @@ -59,23 +59,18 @@ test('formats timestamp', () => { A mirror assertion re-derives the answer with the answer's own machinery: it passes no matter what that machinery does. -**Falsifiable is necessary, not sufficient — name the break.** A test must -fail for the right reason: name the wrong branch, missing side effect, -wrong argument, boundary case, or contract violation it would catch. If -every change that could fail it is an intentional decision — a constant's -value, the exact wording of a message, private structure — you have -written a change detector, not a test: it fires on redesign and sleeps -through bugs. Test the behavior that depends on the decision instead. +**Name the break, not just the change.** A test earns its place by +catching a wrong branch, missing side effect, wrong argument, boundary, +or broken contract. If only intentional decisions can fail it — a +constant's value, exact message wording — it is a change detector: it +fires on redesign and sleeps through bugs. -**The string-presence trap.** For a script, skill, prompt, or config, a -test that asserts the source contains an exact line counterfeits this -rule: it can fail (delete the line), so it passes the letter of -falsifiability while asserting only that the source is the source. It -breaks on every legitimate rewording and survives every real regression. -The observable for a script is what it does — run it against controlled -inputs and assert outputs, side effects, or exit codes. The observable -for a document that instructs an agent is the consuming agent's behavior -— pressure-test it. Text containment is never the observable. +**The string-presence trap.** Asserting that a script, skill, or config +contains an exact line counterfeits falsifiability: it proves only that +the source is the source, breaking on every rewording and surviving every +real regression. Run scripts and assert outputs, side effects, or exit +codes; test agent-instructing documents by their consumer's behavior. +Text containment is never the observable. ### Gate Function @@ -336,9 +331,12 @@ Testing is part of implementation. The TDD cycle — failing test, minimal implementation, refactor — is what "complete" means; "implementation complete, ready for testing" describes an unfinished task. -Ship the tests the behavior needs — and only those. A change that touches -only trivial code (Rule 6) earns no ceremonial test: a test written to -satisfy process protects nothing and costs maintenance forever. +Ship the tests the behavior needs — and only those. Trivial-code changes +(Rule 6) and prose for humans (READMEs, comments, docs) earn no test: +there is no behavior to protect, and a test written to satisfy process +costs maintenance forever. Skills and prompts follow their own discipline +— pressure-test the consuming agent when an edit changes behavior +(superpowers:writing-skills) — never their text. ## Rule 8: Prefer Real Components Over Complex Mocks From 92164e2d1a1eb8aa78113202030191e499f0590d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 18:47:55 -0400 Subject: [PATCH 023/198] experiment: ground-up two-principle rewrite of writing-good-tests Re-derived from scratch: every rule becomes a corollary of two principles (every test names the break it catches; every test exercises the real thing), one consolidated gate per principle, four example pairs kept, the rest carried by prose. Scratch branch for comparison against the accreted eight-rule version. --- .../writing-good-tests.md | 457 +++++------------- 1 file changed, 129 insertions(+), 328 deletions(-) diff --git a/skills/test-driven-development/writing-good-tests.md b/skills/test-driven-development/writing-good-tests.md index 3cae73bc2..d3c4482fd 100644 --- a/skills/test-driven-development/writing-good-tests.md +++ b/skills/test-driven-development/writing-good-tests.md @@ -5,393 +5,194 @@ adding cleanup/helper methods for tests. ## Overview -Good tests verify real behavior. Mocks exist to isolate the code under -test — they are never the thing being tested. - -**Core principle:** Test what the code does, not what the mocks do — and -make every test able to fail. - -Strict TDD produces every rule below naturally: a test written first and -watched failing against real code has already proven it can fail, and -only earns a mock when the real dependency proves slow or external. A -test asserting on a mock means TDD was skipped somewhere. - -## The Iron Laws +A test exists to catch a specific break. Two principles govern everything +here: ``` -1. Every test can fail — name the production change that would fail it -2. Assert on real behavior, never on mock behavior -3. Production classes carry production methods only -4. Understand a dependency's side effects before mocking it +1. Every test names the break it catches +2. Every test exercises the real thing ``` -## Rule 1: Write Tests That Can Fail +Strict TDD produces both naturally: a test written first and watched +failing against real code has already proven it can fail, and only earns +a mock when the real dependency proves slow or external. -Before writing or changing a test, name the production change that would -make it fail. If you cannot, redesign the test around an observable -behavior — a test that cannot fail protects nothing. +## Principle 1: Name the Break -Derive expected values independently of the code under test: literals, -hand-checked fixtures, small worked examples, or invariant assertions. -Keep test logic simple enough to review by inspection — table-driven -tests with literal `want` values are the preferred shape. +Before writing the test body, answer: **what production change should +make this test fail — and is that change a bug or a decision?** A test +earns its place by catching a wrong branch, missing side effect, wrong +argument, boundary case, or broken contract. + +**Derive expectations independently.** Use literals and hand-checked +fixtures; table-driven tests with literal `want` values are the preferred +shape. An expectation computed by the code under test — or its helpers — +passes no matter what that code does: ```typescript -// ✅ GOOD: literal, hand-derived expectation -test('builds tag query', () => { - expect(buildSearchQuery({ tag: 'urgent' })).toBe('tag:"urgent"'); -}); +// ❌ Mirror assertion: the same builder computes both sides — always true +const expected = buildSearchQuery({ tag: 'urgent' }); +expect(buildSearchQuery({ tag: 'urgent' })).toBe(expected); + +// ✅ Hand-derived literal +expect(buildSearchQuery({ tag: 'urgent' })).toBe('tag:"urgent"'); ``` -```typescript -// ❌ The violation: expectation computed by the logic under test -test('builds tag query', () => { - const expected = buildSearchQuery({ tag: 'urgent' }); // same builder! - expect(buildSearchQuery({ tag: 'urgent' })).toBe(expected); // always true -}); +**No change detectors.** If only intentional decisions can fail a test — +a constant's value, exact message wording, private structure — it fires +on redesign and sleeps through bugs. Test the behavior that depends on +the decision: not `expect(MAX_RETRIES).toBe(5)` but "a failing call is +retried 5 times and the 6th attempt never happens." -// ❌ Subtler: the expectation reuses the same helper the code calls -test('formats timestamp', () => { - expect(render(entry)).toContain(formatTime(entry.ts)); // mirrors implementation -}); -``` +**Behavior, not text.** Asserting that a script, skill, or config +contains an exact line proves only that the source is the source. Run +scripts against controlled inputs and assert outputs, side effects, or +exit codes. Documents that instruct agents are tested by the consuming +agent's behavior (superpowers:writing-skills); prose for humans earns no +test at all. -A mirror assertion re-derives the answer with the answer's own machinery: -it passes no matter what that machinery does. - -**Name the break, not just the change.** A test earns its place by -catching a wrong branch, missing side effect, wrong argument, boundary, -or broken contract. If only intentional decisions can fail it — a -constant's value, exact message wording — it is a change detector: it -fires on redesign and sleeps through bugs. - -**The string-presence trap.** Asserting that a script, skill, or config -contains an exact line counterfeits falsifiability: it proves only that -the source is the source, breaking on every rewording and surviving every -real regression. Run scripts and assert outputs, side effects, or exit -codes; test agent-instructing documents by their consumer's behavior. -Text containment is never the observable. +**Your code, not the framework.** Test the contract your code makes at +its boundaries — the route you register, the query you emit, the payload +you produce. Upstream mechanics are their maintainers' tests to write +(the classic: asserting your router invokes a registered handler — that +is the framework's test, not yours). When upstream behavior genuinely +surprised you, write one narrow characterization test naming the +assumption. The same boundary applies inside your code: constructors, +getters, constants, and trivial forwarding earn tests only when they +validate, normalize, default, derive, enforce, or cause side effects — +otherwise assert the first consumer-visible result that depends on them. ### Gate Function ``` BEFORE writing the test body: - Ask: "What production change should make this test fail?" + Name the production change that would make this test fail. - IF you cannot name one: - STOP - Redesign the test around an observable behavior + Cannot name one → redesign around an observable behavior + "The source text changed" → run the artifact and assert its effects + Only intentional decisions → change detector; test the behavior + that depends on the decision - IF the only answer is "the source text changed": - STOP - Run the artifact and assert its effects instead - - Ask: "What BREAK would this catch?" - - IF every failing change is an intentional decision, never a bug: - STOP - That is a change detector; test the behavior that - depends on the decision instead - - Ask: "Is the expected value derived independently of the code under test?" - - IF it reuses the code's own logic or helpers: - STOP - Replace it with a literal or hand-checked fixture + Confirm the expected value is derived without the code under test. + IF it reuses the code's logic or helpers: + Replace it with a literal or hand-checked fixture ``` -## Rule 2: Assert on Real Behavior +## Principle 2: Exercise the Real Thing + +**The mock earns no assertions.** A mock assertion passes when the mock +is present and fails when it is absent — it says nothing about the +component. Assert the real component's behavior; if the mock is what you +are checking, unmock it or delete the assertion. ```typescript -// ✅ GOOD: Test the real component -test('renders sidebar', () => { - render(); // Sidebar unmocked - expect(screen.getByRole('navigation')).toBeInTheDocument(); -}); +// ✅ Real behavior +expect(screen.getByRole('navigation')).toBeInTheDocument(); + +// ❌ Mock existence +expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument(); ``` -If the sidebar must be mocked for isolation, assert on Page's behavior -with the sidebar present — the mock itself earns no assertions. +**your human partner's correction:** "Are we testing the behavior of a +mock?" + +**Mock at the right level.** Learn every side effect of the real method +before replacing it; mock the slow or external operation and keep what +the test depends on real. When unsure, run the test against the real +implementation first and observe what actually needs to happen. ```typescript -// ❌ The violation: asserting that the mock exists -test('renders sidebar', () => { - render(); - expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument(); -}); +// ❌ The mock swallows the config write that duplicate detection reads +vi.mock('ToolCatalog', () => ({ + discoverAndCacheTools: vi.fn().mockResolvedValue(undefined) +})); + +// ✅ Mock only the slow server startup; the config write stays real +vi.mock('MCPServerManager'); ``` -A mock assertion passes when the mock is present and fails when it is -absent — it says nothing about the component. **your human partner's -correction:** "Are we testing the behavior of a mock?" +**Make doubles specific.** When arguments, call counts, or ordering are +part of the contract, assert them — a fake that accepts anything verifies +nothing. Give each branch (success, error, malformed) its own fixture or +spy, so the wrong branch cannot satisfy the expectation. + +**Mirror real data completely.** Mock the complete structure as it exists +in reality — all documented fields — not just the ones your test reads. +Partial mocks fail silently when downstream code reads an omitted field: +the test passes while integration breaks. + +**Production classes carry production methods only.** Cleanup that only +tests need lives in test utilities, never as a `destroy()` on the +production class. Ask: is this method called only from tests? Does this +class own this resource's lifecycle? Wrong answers → test utility. + +**Prefer real components over complex mocks.** When mock setup outgrows +the test logic, mocks miss methods the real components have, or tests +break when the mock changes, switch to an integration test with real +components. **your human partner's question:** "Do we need to be using a +mock here?" ### Gate Function ``` -BEFORE asserting on any mock element: - Ask: "Am I testing real component behavior or just mock existence?" +BEFORE adding a mock or test helper: + List the real method's side effects; keep the ones the test + depends on real — mock the slow/external level below them. - IF testing mock existence: - STOP - Delete the assertion or unmock the component + Mock responses mirror the complete real structure. - Test real behavior instead + A method only tests call lives in test utilities, not production. + + About to assert on the mock itself? + Unmock it or delete the assertion. ``` -## Rule 3: Keep Test Cleanup in Test Utilities +## Tests Ship With the Implementation -```typescript -// ✅ GOOD: Test utilities own test cleanup -// Session has no destroy() - it's stateless in production - -// In test-utils/ -export async function cleanupSession(session: Session) { - const workspace = session.getWorkspaceInfo(); - if (workspace) { - await workspaceManager.destroyWorkspace(workspace.id); - } -} - -// In tests -afterEach(() => cleanupSession(session)); -``` - -```typescript -// ❌ The violation: destroy() exists only for tests -class Session { - async destroy() { // Looks like production API! - await this._workspaceManager?.destroyWorkspace(this.id); - // ... cleanup - } -} - -// In tests -afterEach(() => session.destroy()); -``` - -A test-only method pollutes the production class, is dangerous if -production code ever calls it, and confuses object lifecycle with entity -lifecycle. - -### Gate Function - -``` -BEFORE adding any method to a production class: - Ask: "Is this only used by tests?" - - IF yes: - STOP - Put it in test utilities instead - - Ask: "Does this class own this resource's lifecycle?" - - IF no: - STOP - Wrong class for this method -``` - -## Rule 4: Mock at the Right Level - -Learn what the real method does — every side effect — before replacing -it. Mock the slow or external operation and preserve the behavior your -test depends on. - -Make doubles specific to their contract: when arguments, call counts, or -ordering matter, assert them — a fake that accepts anything verifies -nothing. And give each branch its own double: success, error, and -malformed paths each get their own fixture or spy, so the wrong branch -cannot satisfy the expectation. - -```typescript -// ✅ GOOD: Mock the slow part, preserve behavior the test needs -test('detects duplicate server', () => { - vi.mock('MCPServerManager'); // Just mock slow server startup - - await addServer(config); // Config written - await addServer(config); // Duplicate detected ✓ -}); -``` - -```typescript -// ❌ The violation: the mock swallows the side effect the test depends on -test('detects duplicate server', () => { - // Mock prevents the config write that duplicate detection reads! - vi.mock('ToolCatalog', () => ({ - discoverAndCacheTools: vi.fn().mockResolvedValue(undefined) - })); - - await addServer(config); - await addServer(config); // Should throw - but won't! -}); -``` - -### Gate Function - -``` -BEFORE mocking any method: - STOP - Understand before replacing - - 1. Ask: "What side effects does the real method have?" - 2. Ask: "Does this test depend on any of those side effects?" - 3. Ask: "Do I fully understand what this test needs?" - - IF the test depends on side effects: - Mock at the lower level (the actual slow/external operation) - OR use test doubles that preserve the necessary behavior - — keep the high-level method the test depends on real - - IF unsure what the test depends on: - Run the test with the real implementation FIRST - Observe what actually needs to happen - THEN add minimal mocking at the right level - - Warning signs: - - "I'll mock this to be safe" - - "This might be slow, better mock it" - - Mocking before tracing the dependency chain -``` - -## Rule 5: Mirror Real Data Completely - -Mock the COMPLETE data structure as it exists in reality, not just the -fields your immediate test uses. - -```typescript -// ✅ GOOD: Mirror real API completeness -const mockResponse = { - status: 'success', - data: { userId: '123', name: 'Alice' }, - metadata: { requestId: 'req-789', timestamp: 1234567890 } - // All fields real API returns -}; -``` - -```typescript -// ❌ The violation: only the fields you thought you needed -const mockResponse = { - status: 'success', - data: { userId: '123', name: 'Alice' } - // Missing: metadata that downstream code uses -}; - -// Later: breaks when code accesses response.metadata.requestId -``` - -Partial mocks hide structural assumptions and fail silently when -downstream code reads an omitted field: the test passes while integration -breaks. - -### Gate Function - -``` -BEFORE creating mock responses: - Check: "What fields does the real API response contain?" - - Actions: - 1. Examine the actual API response from docs/examples - 2. Include ALL fields the system might consume downstream - 3. Verify the mock matches the real response schema completely - - If uncertain: include all documented fields -``` - -## Rule 6: Test Your Code, Not the Framework - -Test the contract your code makes at its boundaries — the route you -register, the query you emit, the payload shape you produce, the value -handoff between layers. Dependencies' documented mechanics are their -maintainers' tests to write. - -```typescript -// ✅ GOOD: your contract at the boundary -test('GET /sessions/:id returns 404 for unknown id', async () => { - const res = await request(app).get('/sessions/nope'); - expect(res.status).toBe(404); - expect(res.body.error).toMatch(/not found/); // contract, not exact copy -}); -``` - -```typescript -// ❌ The violation: re-proving the router works as documented -test('router calls handler for matching route', () => { - const handler = vi.fn(); - router.get('/x', handler); - router.handle(makeRequest('/x')); - expect(handler).toHaveBeenCalled(); -}); -``` - -When upstream behavior genuinely surprised you (a quoting rule, an event -ordering), write one narrow characterization test around your integration -point and name the assumption in the test name or a comment. - -The same boundary applies inside your own code: test behavior, not that -the implementation is written the way it is currently written. Plain -constructor assignment, getters, constants, trivial forwarding, and -data-only structs earn tests only when they validate, normalize, default, -derive, enforce, or cause side effects — otherwise assert the first -consumer-visible result that depends on them. - -## Rule 7: Tests Ship With the Implementation - -Testing is part of implementation. The TDD cycle — failing test, minimal -implementation, refactor — is what "complete" means; "implementation -complete, ready for testing" describes an unfinished task. - -Ship the tests the behavior needs — and only those. Trivial-code changes -(Rule 6) and prose for humans (READMEs, comments, docs) earn no test: -there is no behavior to protect, and a test written to satisfy process -costs maintenance forever. Skills and prompts follow their own discipline -— pressure-test the consuming agent when an edit changes behavior -(superpowers:writing-skills) — never their text. - -## Rule 8: Prefer Real Components Over Complex Mocks - -Integration tests with real components are often simpler than elaborate -mocks. Reach for one when you see: - -- Mock setup longer than the test logic -- Mocking everything to make the test pass -- Mocks missing methods the real components have -- Tests breaking when the mock changes - -**your human partner's question:** "Do we need to be using a mock here?" +The TDD cycle — failing test, minimal implementation, refactor — is what +"complete" means. Ship the tests the behavior needs and only those: +trivial code and human prose earn none, and a test written to satisfy +process costs maintenance forever. ## The Mutation Check -Before finishing, mentally mutate the production code. At least one test +Before finishing, mentally mutate the production code; at least one test should fail for each realistic mutation: - Wrong constant or argument - Wrong branch handler -- Missing state change or side effect (row not written, event not emitted) +- Missing state change or side effect - Empty or default return - Missing validation for zero, empty, nil, unauthorized, or malformed input -A mutation no test can catch marks the behavior as unprotected — or the +A mutation nothing catches marks the behavior as unprotected — or the test as tautological. ## Quick Reference | When you... | Do | |-------------|-----| -| Write any test | Name the production change that would make it fail | -| Build an expected value | Derive it independently — literal or hand-checked fixture | -| Want to assert on a mocked element | Test the real component, or unmock it | -| Need cleanup that only tests use | Put it in test utilities | -| Are about to mock a method | Learn its side effects first; mock the slow/external level | -| Build a mock response | Mirror the real structure completely | +| Write any test | Name the break it catches — a bug, not a decision | +| Build an expected value | Derive it by hand; never with the code under test | +| Test a script or document | Run it / pressure-test its consumer; never grep its text | | Reach for a dependency test | Test your boundary contract, not their documented mechanics | -| Finish an implementation | Tests already exist (TDD) — or it is unfinished | -| Finish a test file | Run the mutation check | +| Want to assert on a mocked element | Test the real component, or unmock it | +| Are about to mock a method | Learn its side effects; mock the slow/external level | +| Build a mock response | Mirror the real structure completely | +| Need cleanup only tests use | Put it in test utilities | | Watch mock setup balloon | Switch to an integration test with real components | +| Finish a test file | Run the mutation check | ## Warning Signs -- An assertion checks for a `*-mock` test ID -- A method is called only from test files -- Mock setup is more than half the test -- The test fails when you remove the mock -- You can't explain why the mock is needed -- Mocking "just to be safe" - Setup and assertion share the same object, guaranteeing equality - The test can fail only through a panic, crash, or missing selector -- The test would still matter if only the framework remained +- The test fails on every intentional change, never on accidental breakage - Expected values are hidden behind loops, builders, or helpers -- The test greps source text instead of observing behavior -- The test asserts that a removed function, file, or symbol stays removed -- The test exists for coverage, checking no side effect, boundary, or outcome -- The test fails on every intentional change and never on accidental breakage +- The test greps source text, or asserts a removed symbol stays removed +- The test would still matter if only the framework remained +- The test exists for coverage, checking no side effect or outcome +- An assertion checks a `*-mock` test ID, or fails if you remove the mock +- A method is called only from test files +- Mock setup is more than half the test, or you can't explain why the mock is needed +- Mocking "just to be safe" From 5e046b3db28108ba287402a7550a3674d3f88e44 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:22:52 -0700 Subject: [PATCH 024/198] refactor(skills): drop social proof from dispatching-parallel-agents Real-World Impact restated the Real Example from Session as statistics; Key Benefits and the time-saved line sold the skill to a reader already executing it. Instructions unchanged. --- skills/dispatching-parallel-agents/SKILL.md | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/skills/dispatching-parallel-agents/SKILL.md b/skills/dispatching-parallel-agents/SKILL.md index 75e7e22ce..3fa091b34 100644 --- a/skills/dispatching-parallel-agents/SKILL.md +++ b/skills/dispatching-parallel-agents/SKILL.md @@ -158,15 +158,6 @@ Agent 3 → Fix tool-approval-race-conditions.test.ts **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: @@ -174,12 +165,3 @@ After agents return: 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 From c81f29fc6ba94323064a2b002ba38953c0264d17 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:23:39 -0700 Subject: [PATCH 025/198] refactor(skills): drop social proof from systematic-debugging Real-World Impact was statistics; the Overview opener restated the core principle as motivation. The 95%-of-no-root-cause line stays: it guards the bail-out point, which is rationalization control, not social proof. Supporting Techniques/Related skills untouched (PR #1932 owns that). --- skills/systematic-debugging/SKILL.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/skills/systematic-debugging/SKILL.md b/skills/systematic-debugging/SKILL.md index 1c0be5723..095d194ac 100644 --- a/skills/systematic-debugging/SKILL.md +++ b/skills/systematic-debugging/SKILL.md @@ -7,8 +7,6 @@ description: Use when encountering any bug, test failure, or unexpected behavior ## Overview -Random fixes waste time and create new bugs. Quick patches mask underlying issues. - **Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure. **Violating the letter of this process is violating the spirit of debugging.** @@ -283,11 +281,3 @@ These techniques are part of systematic debugging and available in this director - **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger - **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause - **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling - -## Real-World Impact - -From debugging sessions: -- Systematic approach: 15-30 minutes to fix -- Random fixes approach: 2-3 hours of thrashing -- First-time fix rate: 95% vs 40% -- New bugs introduced: Near zero vs common From 43d87baeed4524284f8b995b419e5febe169f8a4 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:24:18 -0700 Subject: [PATCH 026/198] refactor(skills): drop persuasion sections from verification-before-completion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why This Matters (failure-memory testimonials), the dishonesty reframing in the Overview, and The Bottom Line recap all restate stakes the Iron Law, gate function, and rationalization table already enforce. This is the eval-gated class: the bet is that discipline holds without the persuasion prose — evals on this branch decide. --- .../verification-before-completion/SKILL.md | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/skills/verification-before-completion/SKILL.md b/skills/verification-before-completion/SKILL.md index 2f14076e5..7d45333cc 100644 --- a/skills/verification-before-completion/SKILL.md +++ b/skills/verification-before-completion/SKILL.md @@ -7,8 +7,6 @@ description: Use when about to claim work is complete, fixed, or passing, before ## 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.** @@ -105,15 +103,6 @@ Skip any step = lying, not verifying ❌ Trust agent report ``` -## Why This Matters - -From 24 failure memories: -- your human partner 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:** @@ -129,11 +118,3 @@ From 24 failure memories: - 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. From 9da6fec633c9d93107b678dc49f46fef2f9dc246 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:24:38 -0700 Subject: [PATCH 027/198] refactor(skills): trim quality claim from executing-plans subagent note The tell-your-partner directive and the prefer-SDD instruction stay; the significantly-higher-quality sentence restated them as a claim. Integration section untouched (PR #1932 owns it). --- skills/executing-plans/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/executing-plans/SKILL.md b/skills/executing-plans/SKILL.md index 8c9f339d9..b51d97d2c 100644 --- a/skills/executing-plans/SKILL.md +++ b/skills/executing-plans/SKILL.md @@ -11,7 +11,7 @@ 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:** Tell your human partner that Superpowers works much better with access to subagents. The quality of its work will be significantly higher if run on a platform with subagent support (Claude Code, Codex CLI, Codex App, Copilot CLI, and Gemini CLI all qualify; see the per-platform tool refs in `../using-superpowers/references/`). If subagents are available, use superpowers:subagent-driven-development instead of this skill. +**Note:** Tell your human partner that Superpowers works much better with access to subagents (Claude Code, Codex CLI, Codex App, Copilot CLI, and Gemini CLI all qualify; see the per-platform tool refs in `../using-superpowers/references/`). If subagents are available, use superpowers:subagent-driven-development instead of this skill. ## The Process From 9d941bec3b1e633c017233772f0998f69f663105 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:25:44 -0700 Subject: [PATCH 028/198] refactor(skills): drop Advantages section from subagent-driven-development Five blocks of benefits and cost/benefit selling aimed at a reader who has already invoked the skill; the vs-Executing-Plans comparison also duplicates the one under When to Use. Integration section untouched (PR #1932 owns it). --- skills/subagent-driven-development/SKILL.md | 32 --------------------- 1 file changed, 32 deletions(-) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index ebbb10024..b1d360264 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -335,38 +335,6 @@ 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:** -- Controller curates exactly what context is needed; bulk artifacts move - as files, not pasted text -- Subagent gets complete information upfront -- Questions surfaced before work begins (not after) - -**Quality gates:** -- Self-review catches issues before handoff -- Task review carries two verdicts: spec compliance and 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 + reviewer 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:** From 22d65cf8f01f69f4fe2019bd6cc2a944f711e4c9 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:26:14 -0700 Subject: [PATCH 029/198] refactor(skills): trim requesting-code-review, keep review guards as a table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Integration with Workflows restated the When to Request Review triggers grouped by caller (each-task / before-merge / when-stuck all appear at point of use) — detritus, so it goes. The intro's crafted-context sentence guarded two things at once, so keep both as Common Rationalizations rows (house Excuse/Reality form) rather than deleting the sentence. The skill's reader is the coordinator, not the code's author: - Don't review the diff inline — that burns the coordinator's context window; dispatch a subagent so the diff and evaluation live in its context and only findings return. ("preserves your own context for continued work") - Don't hand the reviewer your session history — crafted context keeps it on the work product, not your thought process. --- skills/requesting-code-review/SKILL.md | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/skills/requesting-code-review/SKILL.md b/skills/requesting-code-review/SKILL.md index 4b8aa605f..fa4f2f996 100644 --- a/skills/requesting-code-review/SKILL.md +++ b/skills/requesting-code-review/SKILL.md @@ -5,7 +5,7 @@ description: Use when completing tasks, implementing major features, or before m # 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. +Dispatch a code reviewer subagent to catch issues before they cascade. The reviewer gets precisely crafted context for evaluation — never your session's history. **Core principle:** Review early, review often. @@ -72,20 +72,12 @@ You: [Fix progress indicators] [Continue to Task 3] ``` -## Integration with Workflows +## Common Rationalizations -**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 +| Excuse | Reality | +|--------|---------| +| "I'll just review the diff myself instead of dispatching a reviewer" | You're the coordinator — reviewing the diff inline burns the context window you need to keep driving the work. Dispatch a reviewer subagent: the diff and the evaluation live in its context, and only the findings come back to you. | +| "The reviewer needs my whole session history to understand the change" | Hand it precisely crafted context, never your session's history. That keeps the reviewer on the work product, not your thought process. | ## Red Flags From 8489d22016e3b36f3bce51e53b5fc0d0444f3ec5 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:26:53 -0700 Subject: [PATCH 030/198] refactor(skills): convert using-git-worktrees guard sections to rationalization table Common Mistakes and Red Flags restated Steps 0-3 wholesale; both fold into one Common Rationalizations table (house Excuse/Reality form) whose five rows carry the tempting-thought version of each rule, including the #1-mistake emphasis on bypassing native tools. Quick Reference stays as the compact decision aid. --- skills/using-git-worktrees/SKILL.md | 51 +++++------------------------ 1 file changed, 8 insertions(+), 43 deletions(-) diff --git a/skills/using-git-worktrees/SKILL.md b/skills/using-git-worktrees/SKILL.md index 212c56926..1381dacb3 100644 --- a/skills/using-git-worktrees/SKILL.md +++ b/skills/using-git-worktrees/SKILL.md @@ -156,47 +156,12 @@ Ready to implement | Tests fail during baseline | Report failures + ask | | No package.json/Cargo.toml | Skip dependency install | -## Common Mistakes +## Common Rationalizations -### 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: explicit instructions > existing project-local directory > 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: explicit instructions > existing project-local directory > default -- Verify directory is ignored for project-local -- Auto-detect and run project setup -- Verify clean test baseline +| Excuse | Reality | +|--------|---------| +| "I'm obviously not in a worktree — no need to check" | Run Step 0. Harness-created isolation and submodules both fool eyeballing; the detection commands settle it. | +| "`git worktree add` is quicker than hunting for a native tool" | A native tool (e.g. `EnterWorktree`) owns placement, branching, and cleanup. Bypassing it is the #1 mistake — it creates phantom state your harness can't see or manage. | +| "The worktree directory is surely ignored already" | Run `git check-ignore`. An unignored worktree directory commits the whole tree into the repo. | +| "Any directory name works" | Explicit instructions beat an existing project-local directory, which beats the `.worktrees/` default. | +| "The workspace is fresh — baseline tests can wait" | A dirty baseline makes every later failure ambiguous. Run the tests now; proceeding past failures is your human partner's call. | From 3550dd05cd41e1da429b13193a88155f8eea5941 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:27:58 -0700 Subject: [PATCH 031/198] refactor(skills): fold brainstorming Key Principles into points of use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five of six principles restated the Checklist and Process sections verbatim-in-spirit. The sixth, YAGNI, appeared nowhere else — it moves to the Exploring approaches list where designs get shaped; the recap section goes. --- skills/brainstorming/SKILL.md | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/skills/brainstorming/SKILL.md b/skills/brainstorming/SKILL.md index b0d52b258..789c3a199 100644 --- a/skills/brainstorming/SKILL.md +++ b/skills/brainstorming/SKILL.md @@ -77,6 +77,7 @@ digraph brainstorming { - Propose 2-3 different approaches with trade-offs - Present options conversationally with your recommendation and reasoning - Lead with your recommended option and explain why +- YAGNI ruthlessly - remove unnecessary features from every approach and design **Presenting the design:** @@ -130,15 +131,6 @@ Wait for the user's response. If they request changes, make them and re-run the - 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. From d74653cf748949a52ddb90f773b6a459b5d8494c Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:28:36 -0700 Subject: [PATCH 032/198] refactor(skills): drop Remember recap from writing-plans All four lines restate the Overview (DRY/YAGNI/TDD/frequent commits), Task Structure (exact paths, commands with expected output), and No Placeholders (complete code in every step). --- skills/writing-plans/SKILL.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/skills/writing-plans/SKILL.md b/skills/writing-plans/SKILL.md index b1613eb05..dd2702b8b 100644 --- a/skills/writing-plans/SKILL.md +++ b/skills/writing-plans/SKILL.md @@ -135,12 +135,6 @@ Every step must contain the actual content an engineer needs. These are **plan f - 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. From 019e79cc461dd1af097e1bf30eee9d7875b18732 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:29:10 -0700 Subject: [PATCH 033/198] refactor(skills): drop The Bottom Line recap from writing-skills Restates the Iron Law, the RED-GREEN-REFACTOR mapping, and the TDD-for-docs framing, all stated in full earlier in the file. --- skills/writing-skills/SKILL.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/skills/writing-skills/SKILL.md b/skills/writing-skills/SKILL.md index 8928d449f..dbb04bc65 100644 --- a/skills/writing-skills/SKILL.md +++ b/skills/writing-skills/SKILL.md @@ -677,13 +677,3 @@ How future agents find your skill: 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. From 14603727c895aae3e855074c0a44c9fbfa6e9ced Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:29:40 -0700 Subject: [PATCH 034/198] refactor(skills): drop The Bottom Line recap from receiving-code-review Restates the evaluate-don't-obey frame, verification rule, and no-performative-agreement rule, each detailed earlier at point of use. The Common Mistakes table stays: it is the skill's one compact guard table, the class this cleanup standardizes toward rather than deletes. --- skills/receiving-code-review/SKILL.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/skills/receiving-code-review/SKILL.md b/skills/receiving-code-review/SKILL.md index 4c77a10ee..950da7b74 100644 --- a/skills/receiving-code-review/SKILL.md +++ b/skills/receiving-code-review/SKILL.md @@ -203,11 +203,3 @@ You understand 1,2,3,6. Unclear on 4,5. ## 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. From 4562d18dcfc1ff7c65ec9aae5848539532724a1d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 5 Jul 2026 12:30:21 -0700 Subject: [PATCH 035/198] refactor(skills): fold TDD Why Order Matters rebuttals into rationalization table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The eval verdict on this cut: deleting Why Order Matters and trusting the compressed one-line table rows measurably degrades test-first behavior under the exact pressure the section rebutted ("just write it, tests after") — control 8/10 → treatment 5/10 at n=10, corroborated on both Claude and Codex. Normal TDD triggering did not move (PPPPP → PPPPP both arms); the damage is purely the pressure case. So instead of trusting the compressed rows, fold the section's five prose rebuttals into their Common Rationalizations rows so each row carries the argument, not just the excuse label: - "I'll test after" — passing immediately proves nothing (wrong thing / implementation-not-behavior / missed edge; you never saw it fail). - "Already manually tested" — ad-hoc, no record, can't re-run, forgotten under pressure. - "Deleting X hours is wasteful" — sunk cost; rewrite-high-confidence vs bolt-tests-on-after-low-confidence. - "TDD will slow me down" — TDD is the pragmatic path; shortcuts mean debugging in production. - "Tests after achieve same goals (spirit not ritual)" — what-does vs what-should; biased by the code you wrote; coverage without proof. Still removes the 50-line section (~200 words / 45 lines net); the arguments survive where an agent hits them mid-rationalization. Revalidate with the tdd-holds-under-tests-later-pressure probe before merge. --- skills/test-driven-development/SKILL.md | 60 +++---------------------- 1 file changed, 5 insertions(+), 55 deletions(-) diff --git a/skills/test-driven-development/SKILL.md b/skills/test-driven-development/SKILL.md index 3eccc6585..4320d8879 100644 --- a/skills/test-driven-development/SKILL.md +++ b/skills/test-driven-development/SKILL.md @@ -209,69 +209,19 @@ When writing or changing any test, read [writing-good-tests.md](writing-good-tes - Keep test-only code in test utilities, out of production classes - Understand a dependency's side effects before mocking it -## Why Order Matters - -**"I'll write tests after to verify it works"** - -Tests written after code pass immediately. Passing immediately proves nothing: -- Might test wrong thing -- Might test implementation, not behavior -- Might miss edge cases you forgot -- You never saw it catch the bug - -Test-first forces you to see the test fail, proving it actually tests something. - -**"I already manually tested all the edge cases"** - -Manual testing is ad-hoc. You think you tested everything but: -- No record of what you tested -- Can't re-run when code changes -- Easy to forget cases under pressure -- "It worked when I tried it" ≠ comprehensive - -Automated tests are systematic. They run the same way every time. - -**"Deleting X hours of work is wasteful"** - -Sunk cost fallacy. The time is already gone. Your choice now: -- Delete and rewrite with TDD (X more hours, high confidence) -- Keep it and add tests after (30 min, low confidence, likely bugs) - -The "waste" is keeping code you can't trust. Working code without real tests is technical debt. - -**"TDD is dogmatic, being pragmatic means adapting"** - -TDD IS pragmatic: -- Finds bugs before commit (faster than debugging after) -- Prevents regressions (tests catch breaks immediately) -- Documents behavior (tests show how to use code) -- Enables refactoring (change freely, tests catch breaks) - -"Pragmatic" shortcuts = debugging in production = slower. - -**"Tests after achieve the same goals - it's spirit not ritual"** - -No. Tests-after answer "What does this do?" Tests-first answer "What should this do?" - -Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones. - -Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't). - -30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work. - ## Common Rationalizations | 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?" | -| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. | -| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. | +| "I'll test after" | Tests written after pass immediately — which proves nothing. They may test the wrong thing, test the implementation instead of the behavior, or miss the edge case you forgot. You never watched it fail, so you never proved it can catch the bug. Test-first forces that failure. | +| "Tests after achieve same goals (spirit not ritual)" | Tests-after answer "what does this do?"; tests-first answer "what should this do?" Tests written after are biased by the code you already wrote — you verify the cases you remembered, not the ones you'd have discovered. Coverage without proof the tests work. | +| "Already manually tested" | Manual testing is ad-hoc: no record of what you covered, no way to re-run it when the code changes, easy to forget cases under pressure. "Worked when I tried it" ≠ comprehensive. Automated tests run the same way every time. | +| "Deleting X hours is wasteful" | Sunk cost fallacy — that time is already spent either way. The real choice: rewrite with TDD (high confidence) vs. keep it and bolt tests on after (low confidence, likely bugs). Keeping code you can't trust is the waste. | | "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. | | "Need to explore first" | Fine. Throw away exploration, start with TDD. | | "Test hard = design unclear" | Listen to test. Hard to test = hard to use. | -| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. | +| "TDD will slow me down" | TDD IS the pragmatic path: catches bugs before commit, prevents regressions, lets you refactor without fear. "Pragmatic" shortcuts mean debugging in production — slower, not faster. | | "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. | | "Existing code has no tests" | You're improving it. Add tests for existing code. | From 2b1c06a849535517ef8b32c35f4df33288a0fe87 Mon Sep 17 00:00:00 2001 From: Gaurav Dubey Date: Sun, 12 Jul 2026 19:54:51 +0530 Subject: [PATCH 036/198] test: realign antigravity + pi mapping assertions with pruned references Commit e7ddc25 ('Prune per-harness tool-mapping boilerplate') deliberately removed the skill-loading explainers and generic action->tool tables from antigravity-tools.md and pi-tools.md, keeping only the harness-specific notes (subagent dispatch, task tracking). It did not touch tests/, so two content-assertion tests kept asserting the removed tokens and now fail on both dev and main: - tests/antigravity/test-antigravity-tools.sh: asserted view_file, IsSkillFile, run_command, grep_search (all pruned) - tests/pi/test-pi-extension.mjs: asserted read/write/edit/bash (pruned) Update both to assert only the surviving harness-specific mappings. No reference or skill content is changed; only the stale test assertions. --- tests/antigravity/test-antigravity-tools.sh | 17 +++++------------ tests/pi/test-pi-extension.mjs | 2 +- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/tests/antigravity/test-antigravity-tools.sh b/tests/antigravity/test-antigravity-tools.sh index e370ac06f..e10edd42c 100755 --- a/tests/antigravity/test-antigravity-tools.sh +++ b/tests/antigravity/test-antigravity-tools.sh @@ -2,8 +2,9 @@ # Validate the Antigravity (agy) integration. agy installs the existing plugin # directly (`agy plugin install `): it loads the bundled skills and # runs the SessionStart hook for bootstrap, so there is no agy-specific scaffold -# to test. What IS agy-specific is the tool mapping — agy has no `Skill` tool and -# loads skills by reading SKILL.md with view_file — and SKILL.md pointing at it. +# to test. What IS agy-specific is the tool mapping — subagent dispatch via +# invoke_subagent (self/research types) and task tracking via a task artifact — +# and SKILL.md pointing at it. # # Mirrors tests/pi/test-pi-extension.mjs's "tools reference documents # harness-specific mappings" check. CI-safe: does not require `agy` installed. @@ -22,16 +23,8 @@ echo "test-antigravity-tools: checking Antigravity tool mapping" # --- Mapping exists --------------------------------------------------------- [ -f "$MAPPING" ] || fail "tool mapping missing at $MAPPING" -# --- Skill-load mechanism: view_file on SKILL.md (IsSkillFile), no Skill tool - -grep -qiE "view_file" "$MAPPING" \ - || fail "mapping does not document view_file as the file/skill-read tool" -grep -qiE "SKILL\.md" "$MAPPING" \ - || fail "mapping does not document reading SKILL.md as the skill-load path" -grep -q "IsSkillFile" "$MAPPING" \ - || fail "mapping does not document setting IsSkillFile when loading a skill" - # --- Core action→tool mappings are documented ------------------------------- -for tool in write_to_file replace_file_content run_command grep_search invoke_subagent; do +for tool in write_to_file replace_file_content invoke_subagent; do grep -q "$tool" "$MAPPING" \ || fail "mapping does not document the '$tool' tool" done @@ -50,4 +43,4 @@ grep -qE 'ArtifactType.*task|task. artifact' "$MAPPING" \ grep -q "antigravity-tools.md" "$SKILL" \ || fail "SKILL.md Platform Adaptation does not reference antigravity-tools.md" -echo "PASS: Antigravity tool mapping valid (view_file skill-load, agy tools, SKILL.md link)" +echo "PASS: Antigravity tool mapping valid (subagent dispatch, task artifact, SKILL.md link)" diff --git a/tests/pi/test-pi-extension.mjs b/tests/pi/test-pi-extension.mjs index 196e97593..14380e428 100644 --- a/tests/pi/test-pi-extension.mjs +++ b/tests/pi/test-pi-extension.mjs @@ -122,7 +122,7 @@ test('pi tools reference documents pi-specific mappings', async () => { assert.equal(existsSync(piToolsPath), true, 'pi-tools.md should exist'); const text = await readFile(piToolsPath, 'utf8'); - for (const expected of ['Skill', 'Task', 'TodoWrite', 'read', 'write', 'edit', 'bash']) { + for (const expected of ['subagent', 'pi-subagents', 'Task', 'TODO.md']) { assert.match(text, new RegExp(expected)); } }); From 7a81eb71774fc430b9eb0bd17d042ba659a4c8ca Mon Sep 17 00:00:00 2001 From: Gaurav Dubey Date: Tue, 14 Jul 2026 17:36:57 +0530 Subject: [PATCH 037/198] test(pi): scope mapping assertions to the table, not whole file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pi tokens (subagent, pi-subagents, Task, TODO.md) also appear in the surrounding prose, so matching the whole file passed even with the mapping table deleted — the exact regression this test exists to catch. Filter to table rows (lines starting with '|') so the assertion fails when the table is gone and passes on dev. Reported by @muunkky on #1987 (approach from #1983); verified failing-first by stripping the table rows from pi-tools.md. --- tests/pi/test-pi-extension.mjs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/pi/test-pi-extension.mjs b/tests/pi/test-pi-extension.mjs index 14380e428..d7af9cb2a 100644 --- a/tests/pi/test-pi-extension.mjs +++ b/tests/pi/test-pi-extension.mjs @@ -122,7 +122,16 @@ test('pi tools reference documents pi-specific mappings', async () => { assert.equal(existsSync(piToolsPath), true, 'pi-tools.md should exist'); const text = await readFile(piToolsPath, 'utf8'); - for (const expected of ['subagent', 'pi-subagents', 'Task', 'TODO.md']) { - assert.match(text, new RegExp(expected)); - } + // Assert against the mapping-table rows only. The surrounding prose mentions + // these same tokens, so matching the whole file would still pass if the table + // were deleted — the exact regression this test exists to catch. + const rows = text.split('\n').filter((line) => line.startsWith('|')); + assert.ok( + rows.some((row) => /subagent/i.test(row)), + 'mapping table documents subagent dispatch', + ); + assert.ok( + rows.some((row) => /todo|task/i.test(row)), + 'mapping table documents task tracking', + ); }); From fb7b07088ed03da76508b8a70a87bf4f15b2412a Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 15 Jul 2026 19:12:54 +0000 Subject: [PATCH 038/198] docs: fix dead references to pruned claude-code-tools.md/copilot-tools.md e7ddc25 deleted claude-code-tools.md and copilot-tools.md but left writing-skills and the porting guide's reference-integration table pointing at them. State the current architecture instead: Claude Code's personal-skills path inline, and "no adapter file needed" for the harnesses that ride the Claude Code-compatible tool surface. Reported by @rasibintang (#1969, with a fix proposed in #1970). Fixes #1969 --- docs/porting-to-a-new-harness.md | 6 +++--- skills/writing-skills/SKILL.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/porting-to-a-new-harness.md b/docs/porting-to-a-new-harness.md index d288c6b07..4ae9603de 100644 --- a/docs/porting-to-a-new-harness.md +++ b/docs/porting-to-a-new-harness.md @@ -784,10 +784,10 @@ Use this as the live index; when in doubt, read the files, not this table. | Harness | Entry point | Bootstrap mechanism | Tool mapping | Tests | Distribution | |---|---|---|---|---|---| -| Claude Code | `.claude-plugin/plugin.json` + `hooks/hooks.json` | shell hook → `hooks/session-start` (`hookSpecificOutput.additionalContext`) | native `Skill` tool; `references/claude-code-tools.md` | `tests/hooks/` | marketplace | +| Claude Code | `.claude-plugin/plugin.json` + `hooks/hooks.json` | shell hook → `hooks/session-start` (`hookSpecificOutput.additionalContext`) | native `Skill` tool; no adapter file needed | `tests/hooks/` | marketplace | | Codex | `.codex-plugin/plugin.json` (declares empty `hooks`) | native skill discovery (no session-start hook) | `references/codex-tools.md` | `tests/codex/`, `tests/codex-plugin-sync/` | fork sync (`scripts/sync-to-codex-plugin.sh`) | -| Cursor | `.cursor-plugin/plugin.json` + `hooks/hooks-cursor.json` | shell hook → `hooks/session-start` (`additional_context`) | `references/claude-code-tools.md` | `tests/hooks/` | hand-authored | -| Copilot CLI | (shares Claude Code hook path; `COPILOT_CLI` env) | shell hook → `hooks/session-start` (`additionalContext`) | `references/copilot-tools.md` | `tests/hooks/` | — | +| Cursor | `.cursor-plugin/plugin.json` + `hooks/hooks-cursor.json` | shell hook → `hooks/session-start` (`additional_context`) | none needed (Claude Code–compatible tool surface) | `tests/hooks/` | hand-authored | +| Copilot CLI | (shares Claude Code hook path; `COPILOT_CLI` env) | shell hook → `hooks/session-start` (`additionalContext`) | none needed (Claude Code–compatible tool surface) | `tests/hooks/` | — | | Gemini CLI | `gemini-extension.json` + `GEMINI.md` | instructions file `@`-includes bootstrap + mapping | `references/gemini-tools.md` | — | `gemini extensions install` | | Kimi Code | `.kimi-plugin/plugin.json` | manifest `sessionStart.skill` loads `using-superpowers` | inline `skillInstructions` in manifest | `tests/kimi/` | marketplace or `/plugins install` GitHub URL | | OpenCode | `.opencode/plugins/superpowers.js` (declared via root `package.json` `main`) | in-process: `config` hook registers skills dir; `experimental.chat.messages.transform` injects user message | inline in `superpowers.js` | `tests/opencode/` | `opencode.json` plugin git URL | diff --git a/skills/writing-skills/SKILL.md b/skills/writing-skills/SKILL.md index dbb04bc65..f33f39f52 100644 --- a/skills/writing-skills/SKILL.md +++ b/skills/writing-skills/SKILL.md @@ -9,7 +9,7 @@ description: Use when creating new skills, editing existing skills, or verifying **Writing skills IS Test-Driven Development applied to process documentation.** -**Personal skills live in your runtime's skills directory** — see [claude-code-tools.md](../using-superpowers/references/claude-code-tools.md), [codex-tools.md](../using-superpowers/references/codex-tools.md), [copilot-tools.md](../using-superpowers/references/copilot-tools.md), or [gemini-tools.md](../using-superpowers/references/gemini-tools.md) for the path on your runtime. Codex, Copilot CLI, and Gemini CLI all also recognize `~/.agents/skills/` as a cross-runtime alias. +**Personal skills live in your runtime's skills directory** (`~/.claude/skills/` on Claude Code) — see [codex-tools.md](../using-superpowers/references/codex-tools.md) or [gemini-tools.md](../using-superpowers/references/gemini-tools.md) for the path on those runtimes. Codex, Copilot CLI, and Gemini CLI all also recognize `~/.agents/skills/` as a cross-runtime alias. 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). From 262ed021037d5b189931f143157d77df2a76bb43 Mon Sep 17 00:00:00 2001 From: arimu1 <19286898+arimu1@users.noreply.github.com> Date: Sun, 19 Jul 2026 06:15:54 +0700 Subject: [PATCH 039/198] docs(brainstorming): correct Copilot CLI backgrounding guidance for Windows --- skills/brainstorming/visual-companion.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/skills/brainstorming/visual-companion.md b/skills/brainstorming/visual-companion.md index 906c9ac87..c145e6438 100644 --- a/skills/brainstorming/visual-companion.md +++ b/skills/brainstorming/visual-companion.md @@ -83,10 +83,11 @@ scripts/start-server.sh --project-dir /path/to/project --open --foreground **Copilot CLI:** ```bash -# Use --foreground and start the server via the bash tool with mode: "async" -# so the process survives across turns. Capture the returned shellId for -# read_bash / stop_bash if you need to interact with it later. -scripts/start-server.sh --project-dir /path/to/project --open --foreground +# Start it with Copilot CLI's non-blocking/background shell mechanism so the +# server survives across turns. Keep --foreground so the harness, not the +# script, owns backgrounding. The launcher is a .sh, so invoke it via bash +# (on Windows, call Git Bash's bash.exe from the PowerShell tool). +bash scripts/start-server.sh --project-dir /path/to/project --open --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. From 20940deae86d367acedac0ac2554f77dbf86f139 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 11:06:10 -0700 Subject: [PATCH 040/198] docs(specs): SDD plan-scoped workspace design The .superpowers/sdd workspace has no plan identity and no end-of-life: follow-up plans in the same worktree read the previous plan's ledger as their own progress, and artifacts leak into git (observed in serf, three contamination rounds and ad-hoc progress-p2/p3 workarounds). Structural fix: per-plan workspace subdirs, ledger names its plan, delete the workspace when the final review is clean. --- .../2026-07-06-sdd-plan-scoped-workspace.md | 185 ++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md diff --git a/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md new file mode 100644 index 000000000..a1aef4d13 --- /dev/null +++ b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md @@ -0,0 +1,185 @@ +# SDD plan-scoped workspace — design + +- **Date:** 2026-07-06 +- **Status:** approved direction (Jesse, 2026-07-06); this spec captures the investigation's recommended fix +- **Problem owner:** subagent-driven-development skill (`skills/subagent-driven-development/`) + +## Problem + +SDD's durable-progress workspace (`.superpowers/sdd/`, introduced v6.0.0/v6.0.3) has +no plan identity and no end-of-life. Every artifact is keyed by bare task number +(`progress.md`, `task-N-brief.md`, `task-N-report.md`), and SKILL.md instructs a +starting controller to treat whatever ledger it finds as its own progress: + +> At skill start, check for a ledger: +> `cat "$(git rev-parse --show-toplevel)/.superpowers/sdd/progress.md"`. Tasks listed there +> as complete are DONE — do not re-dispatch them; resume at the first task +> not marked complete. + +A fresh session executing a **follow-up plan** in the same worktree reads the +previous plan's ledger as its own. A straight-line reading of the skill tells it +to skip tasks. Nothing ever deletes the workspace, so the stale state persists +indefinitely and accumulates. + +### Observed failures (serf repo, 2026-06-22 → 2026-07-05) + +- **Cross-plan collisions, worked around ad hoc:** `cc-plugin-marketplaces` + worktree accumulated 68 files across three plans. The P2 controller had to + invent `progress-p2.md` and `p2-task-N-report.md` to dodge P1's ledger; P2's + briefs silently overwrote P1's at the default paths; an abandoned + `progress-p3.md` stub remains. +- **Git contamination, three times over:** SDD scratch was committed and needed + two cleanup commits (`8305e340d`, `c966261a5`); three artifacts are tracked on + serf main today, including a report authored on a different machine that now + materializes in every fresh worktree. A follow-up plan's task-1 report + overwrote an unrelated tracked one, leaving permanent `git status` noise. +- The self-ignoring `.gitignore` is written only when a script runs. Controllers + that hand-append the ledger (observed) never create it, and gitignore is + powerless once a file is tracked. + +### Root cause + +Identity lives nowhere in the data; correctness relies on cleanup that has no +trigger. Any fix that relies on end-of-plan cleanup alone fails exactly in the +crash/compaction cases the ledger exists to survive. Identity must be +structural. + +## Design + +### 1. Per-plan workspace directory (structural identity) + +The workspace becomes `.superpowers/sdd//`, where `` is +the plan file's basename without its `.md` extension (plan filenames are +already dated kebab-case, e.g. `2026-07-04-plugin-marketplaces-p1-backend-core`). +Artifacts from different plans can no longer collide; a stale sibling directory +is inert because no instruction ever points at it. + +Script interface (all in `skills/subagent-driven-development/scripts/`): + +- `sdd-workspace PLAN_FILE` — resolves and creates + `/.superpowers/sdd//`, maintains the self-ignoring + `.gitignore` at `.superpowers/sdd/.gitignore` (parent level, content `*`), + prints the plan directory's absolute path. Errors (exit 2) on missing + argument or nonexistent plan file. Slug must be non-empty after stripping. +- `task-brief PLAN_FILE N [OUTFILE]` — signature unchanged; default OUTFILE + moves to `/task-N-brief.md` via `sdd-workspace PLAN_FILE`. +- `review-package PLAN_FILE BASE HEAD [OUTFILE]` — gains PLAN_FILE as first + argument; default OUTFILE moves to `/review-...diff`. + +No compatibility path for the old flat layout: the scripts and SKILL.md ship +together in one plugin release, and nothing else invokes the scripts. +(Explicitly confirmed: no backward-compatibility handling.) + +### 2. Ledger names its plan (belt for hand-rolled ledgers) + +The ledger stays `/progress.md`. When created, its first line MUST +be: + +``` +# SDD ledger — plan: docs/superpowers/plans/.md +``` + +SKILL.md's start-of-skill check becomes plan-scoped and carries a conditional +guard keyed to that observable line, phrased positively (recipe, not +prohibition): resolve your plan's workspace with `sdd-workspace PLAN_FILE`, +read `progress.md` there; a ledger whose plan line names a different plan file +is another plan's progress — leave it in place and use your own plan's +workspace. This covers controllers that hand-write ledgers without running the +scripts (observed in the serf ask_user session) and pre-upgrade litter at the +old flat path. + +The exact wording of the guard is subordinate to eval results (see Evaluation); +counters are added only for failures actually observed in the RED baseline. + +### 3. Workspace end-of-life (hygiene, not correctness) + +When the final whole-branch review is clean and its fix wave (if any) is +merged — immediately before handing off to +`superpowers:finishing-a-development-branch` — the controller deletes its +plan's workspace directory (`rm -rf "$WORKSPACE"`). The record of the work is +the git history; the ledger's job (mid-plan compaction recovery) is over. +Sibling directories are never touched: crashed or parallel plans own their own +dirs, and deliberately parked cross-plan artifacts (observed pattern: +`WAVE1-HANDOFF.md`) live directly under `.superpowers/sdd/` untouched by any +plan's cleanup. + +### 4. SKILL.md touch points + +- **Durable Progress** section: workspace resolution via `sdd-workspace + PLAN_FILE`; ledger check scoped to the plan's own workspace; ledger-creation + format including the plan line; the mismatch guard; completion deletion; the + `git clean -fdx` hazard note updated to the new path. +- **Handling Implementer Status / Constructing Reviewer Prompts / File + Handoffs / Red Flags / Example Workflow**: update script invocations to the + new signatures (`review-package PLAN_FILE BASE HEAD`) and any path mentions. + `implementer-prompt.md` and `task-reviewer-prompt.md` contain no workspace + paths (verified) and need no changes. +- Red Flags additions only if the RED baseline shows a failure the structural + fix plus guard text does not close. + +## Out of scope (deliberate) + +- No changes to `finishing-a-development-branch` or any other skill. +- No git-level guards against committing `.superpowers/` beyond the existing + parent `.gitignore`. +- No retroactive cleanup of the serf repo (separate follow-up). +- No legacy-layout migration or fallback reads. + +## Testing + +### Deterministic shell tests (`tests/claude-code/test-sdd-workspace.sh`, extended) + +- `sdd-workspace PLAN` prints `/.superpowers/sdd/` and creates it; + errors without a plan arg; errors on missing plan file. +- Two different plan files resolve to two distinct directories; artifacts + written via `task-brief` land in their own plan's directory. +- `review-package PLAN BASE HEAD` writes under the plan's directory. +- Parent `.gitignore` self-ignores: workspace invisible to `git status` and + `git add -A` (existing assertions, re-anchored). +- Linked-worktree distinctness (existing assertion, re-anchored). +- Existing suites `test-subagent-driven-development.sh` / + `-integration.sh` audited for old-path expectations (none found in initial + grep; audit is a task gate anyway). + +### Evaluation (writing-skills RED → GREEN, the "basic eval") + +Pressure scenarios run as fresh subagent sessions against a fixture repo in a +temp directory (never inside this worktree). Fixture: git repo with plan A +(17-task backend plan) and plan B (5-task follow-up), plus SDD workspace state +as each scenario dictates. The agent under test is pointed at a specific +SKILL.md text (old = `git show` of the released text; new = this branch's) and +plan B, and asked to state concretely which task it starts with and what it +does about existing ledger state. No real implementer dispatches — the measured +output is the controller's resume decision. + +- **S1 — stale ledger from a different plan (the reported bug):** + workspace contains plan A's completed ledger in the layout the skill text + under test prescribes. PASS = starts plan B at Task 1 (or explicitly + identifies the ledger as another plan's); FAIL = resumes past plan B tasks, + claims tasks complete, or adopts plan A's ledger. +- **S2 — same-plan resume (regression guard):** ledger for plan B marks Tasks + 1–2 complete. PASS = resumes at Task 3 without re-dispatching 1–2. This + protects the ledger's original purpose; the fix must not break it. + +Reps: 5 per scenario per arm (RED = current released text, GREEN = new text), +every response read and scored by hand against the PASS/FAIL criteria above; +verbatim failure rationalizations captured. Expected: S1 RED fails ≥1/5 and +plausibly most runs (any failure validates the bug; if S1 RED passes 5/5, STOP +and reassess with Jesse before editing skill text — per writing-skills, no +skill change without a failing test). S1 GREEN and S2 both arms must pass 5/5. +Results land in `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` +and are summarized in the PR. + +## Risks + +- **Slug collisions between distinct plans with identical basenames** in + different directories: accepted; plan filenames are date-prefixed by + convention, and same-basename means same plan in practice (resume is then the + desired behavior). +- **Controllers skipping the scripts entirely** (hand-rolled everything): the + ledger plan-line guard is the mitigation; the eval's S1 measures whether the + text actually binds. +- **Re-running a completed plan from scratch after its workspace survived a + crash**: the ledger legitimately belongs to the same plan; resume-not-restart + is the designed behavior and `git log` cross-checking (existing skill text) + covers the divergence case. From 0da87665c8423bd5100991ecee0e738bbfa3433f Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 11:14:53 -0700 Subject: [PATCH 041/198] docs(plans): SDD plan-scoped workspace implementation plan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five tasks: RED baseline eval (writing-skills Iron Law — before any skill edit), plan-scoped scripts via TDD, SKILL.md durable-progress rewrite with mismatch guard and end-of-plan cleanup, GREEN eval with refinement loop, consistency sweep. Eval = 5 fresh sonnet subagents per scenario per arm, hand-scored. --- .../2026-07-06-sdd-plan-scoped-workspace.md | 987 ++++++++++++++++++ 1 file changed, 987 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md diff --git a/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md b/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md new file mode 100644 index 000000000..850cd37a6 --- /dev/null +++ b/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md @@ -0,0 +1,987 @@ +# SDD Plan-Scoped Workspace 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:** Make SDD's durable-progress workspace plan-scoped (`.superpowers/sdd//`) with a self-identifying ledger and end-of-plan cleanup, so a follow-up plan can never mistake a previous plan's ledger for its own progress. + +**Architecture:** Three shell scripts in `skills/subagent-driven-development/scripts/` gain plan awareness (`sdd-workspace PLAN_FILE` becomes the single source of truth for the per-plan directory); SKILL.md's Durable Progress section is rewritten around the plan-scoped workspace with a mismatch guard keyed to the ledger's first line; a RED→GREEN pressure-test eval (writing-skills methodology) proves the old text fails and the new text binds. Spec: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md`. + +**Tech Stack:** bash, shellcheck (via `scripts/lint-shell.sh`), repo shell-test conventions (`tests/claude-code/test-sdd-workspace.sh`), subagent pressure-test evals. + +## Global Constraints + +- Execute tasks in order 1 → 5. Task 1 (RED baseline) MUST complete before Task 3 touches SKILL.md — no skill edit without a captured failing baseline (writing-skills Iron Law). +- No backward-compatibility code paths: no legacy-layout reads, no dual-signature support in scripts. Scripts and SKILL.md ship together. +- Eval fixtures and scenario workdirs live under `mktemp -d` and are deleted afterward; they are NEVER committed and NEVER created inside this repository checkout. +- Eval scenario subagents: model `sonnet`, subagent_type `general-purpose`, one fresh subagent per rep, prompt used VERBATIM as given (fill only the `` paths). Do not add hints about ledgers, staleness, or the fix. +- Every shell file you create or modify must pass `bash scripts/lint-shell.sh ` (shellcheck 0.11.0 is installed). +- Match SKILL.md's existing prose conventions: two-space bullet continuation indent, em-dashes (`—`), sentence-per-line wrapping style. +- Commit at the end of every task with the message given in the task. + +--- + +### Task 1: RED baseline eval — capture the failure with the released skill text + +**Files:** +- Create (temp only, not committed): `$EVAL_ROOT/make-fixture.sh`, `$EVAL_ROOT/red/` working files +- Create: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` (interim RED evidence; folded into the final results doc in Task 4) + +**Interfaces:** +- Consumes: `skills/subagent-driven-development/` at current HEAD (pre-edit text). +- Produces: RED scoring table + verbatim failure quotes that Task 3 uses to tune wording and Task 4 folds into the final results doc. Also the fixture generator script content, reused verbatim in Task 4. + +- [ ] **Step 1: Create the eval root and the fixture generator** + +```bash +EVAL_ROOT=$(mktemp -d) +echo "$EVAL_ROOT" > /tmp/sdd-eval-root.path # so later steps/tasks can find it +mkdir -p "$EVAL_ROOT/red" +cat > "$EVAL_ROOT/make-fixture.sh" <<'FIXTURE' +#!/usr/bin/env bash +# Build a throwaway git repo simulating a project where SDD ran plan A to +# completion and a controller is now starting follow-up plan B. +# +# Usage: make-fixture.sh SCENARIO LAYOUT DEST +# SCENARIO: s1 (stale ledger from a different plan) | s2 (same-plan resume) +# LAYOUT: flat (released layout: .superpowers/sdd/progress.md) +# scoped (new layout: .superpowers/sdd//progress.md, +# PLUS leftover flat + sibling litter for s1) +# DEST: directory to create the repo in +set -euo pipefail +scenario=$1 layout=$2 dest=$3 + +git init -q -b main "$dest" +cd "$dest" +git config user.email eval@example.com +git config user.name eval +git config commit.gpgsign false + +mkdir -p docs/plans src +cat > src/inventory.py <<'EOF' +"""Inventory service (fixture).""" +def list_items(): + return [] +EOF + +cat > docs/plans/2026-07-01-inventory-backend.md <<'EOF' +# Inventory Backend Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. + +**Goal:** Build the inventory backend core. + +## Task 1: Storage schema +## Task 2: Atomic writes +## Task 3: File locking +## Task 4: Registry load/save +## Task 5: Git fetcher +## Task 6: Source model +## Task 7: Marketplace refresh +## Task 8: Catalog parsing +## Task 9: Version comparison +## Task 10: Validation +## Task 11: Source fetch +## Task 12: Install +## Task 13: Upgrade +## Task 14: Remove and enable +## Task 15: List and update-all +## Task 16: Lint gate +## Task 17: Integration pass +EOF + +cat > docs/plans/2026-07-06-widget-export.md <<'EOF' +# Widget Export Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. + +**Goal:** Add CSV and JSON export of widgets to the inventory backend. + +## Task 1: Export data model + +Define `ExportRow` with fields `id`, `name`, `count`. + +## Task 2: CSV serializer + +`to_csv(rows) -> str`, header row + one line per widget. + +## Task 3: JSON serializer + +`to_json(rows) -> str`, list of objects, stable key order. + +## Task 4: CLI flag + +`inventory export --format csv|json` writing to stdout. + +## Task 5: End-to-end test + +Round-trip: list -> export -> parse -> compare. +EOF + +git add -A +git commit -qm "fixture: inventory project with completed plan A and new plan B" + +plan_a_ledger_lines() { + local i + for i in $(seq 1 17); do + printf 'Task %d: complete (commits aaa%04d..bbb%04d, review clean)\n' "$i" "$i" "$i" + done + printf '\n## Final whole-branch review — DONE\nNo Critical/Important findings.\n' +} + +case "$scenario/$layout" in + s1/flat) + mkdir -p .superpowers/sdd + plan_a_ledger_lines > .superpowers/sdd/progress.md + ;; + s1/scoped) + # Post-upgrade worst case: legacy flat ledger litter AND plan A's own + # completed scoped workspace both present. + mkdir -p .superpowers/sdd/2026-07-01-inventory-backend + printf '*\n' > .superpowers/sdd/.gitignore + plan_a_ledger_lines > .superpowers/sdd/progress.md + { + printf '# SDD ledger — plan: docs/plans/2026-07-01-inventory-backend.md\n\n' + plan_a_ledger_lines + } > .superpowers/sdd/2026-07-01-inventory-backend/progress.md + ;; + s2/flat) + mkdir -p .superpowers/sdd + { + printf 'Task 1: complete (commits ccc0001..ddd0001, review clean)\n' + printf 'Task 2: complete (commits ccc0002..ddd0002, review clean)\n' + } > .superpowers/sdd/progress.md + ;; + s2/scoped) + mkdir -p .superpowers/sdd/2026-07-06-widget-export + printf '*\n' > .superpowers/sdd/.gitignore + { + printf '# SDD ledger — plan: docs/plans/2026-07-06-widget-export.md\n\n' + printf 'Task 1: complete (commits ccc0001..ddd0001, review clean)\n' + printf 'Task 2: complete (commits ccc0002..ddd0002, review clean)\n' + } > .superpowers/sdd/2026-07-06-widget-export/progress.md + ;; + *) + echo "unknown scenario/layout: $scenario/$layout" >&2 + exit 2 + ;; +esac +FIXTURE +chmod +x "$EVAL_ROOT/make-fixture.sh" +``` + +- [ ] **Step 2: Extract the pre-edit skill directory (the text under test)** + +```bash +EVAL_ROOT=$(cat /tmp/sdd-eval-root.path) +mkdir -p "$EVAL_ROOT/red/skill" +git archive HEAD -- skills/subagent-driven-development | tar -x -C "$EVAL_ROOT/red/skill" +ls "$EVAL_ROOT/red/skill/skills/subagent-driven-development/SKILL.md" +``` + +Expected: the SKILL.md path prints (file exists). This snapshot is the RELEASED behavior baseline; Task 3 has not run yet so HEAD's copy is the released text. + +- [ ] **Step 3: Build 10 RED fixtures (5 reps × scenarios S1, S2, `flat` layout)** + +```bash +EVAL_ROOT=$(cat /tmp/sdd-eval-root.path) +for i in 1 2 3 4 5; do + "$EVAL_ROOT/make-fixture.sh" s1 flat "$EVAL_ROOT/red/s1-rep$i" + "$EVAL_ROOT/make-fixture.sh" s2 flat "$EVAL_ROOT/red/s2-rep$i" +done +ls "$EVAL_ROOT/red" +``` + +Expected: directories `s1-rep1..5`, `s2-rep1..5`, plus `skill/`. + +- [ ] **Step 4: Run the 10 scenario reps as fresh subagents** + +Dispatch one fresh subagent per rep (model `sonnet`, subagent_type `general-purpose`). Use this prompt VERBATIM, substituting only `` = `$EVAL_ROOT/red/skill/skills/subagent-driven-development` and `` = the rep's fixture path. The S1 and S2 prompts are identical — only the fixture differs. + +``` +You are a controller about to execute an implementation plan using the +Subagent-Driven Development skill. The complete skill (SKILL.md plus its +scripts/ directory) is at: +Read /SKILL.md first and follow its process exactly. + +The repository you are working in: +Your plan: docs/plans/2026-07-06-widget-export.md (relative to that repo) + +Scope limit for this run: you may read anything, run git commands, and run +the skill's scripts. Do NOT dispatch any subagents and do NOT implement any +tasks. Work only up to the point where you know your execution state, then +STOP and reply with exactly this report: + +1. LEDGERS CHECKED: each progress/ledger file path you looked at, and what + you concluded from it. +2. TASKS ALREADY COMPLETE: which of YOUR plan's tasks (if any) are already + done. +3. FIRST DISPATCH: which task you will dispatch first. + +Be concrete and terse. That report is your entire deliverable. +``` + +Save each subagent's reply verbatim to `$EVAL_ROOT/red/s1-repN.reply.md` / `$EVAL_ROOT/red/s2-repN.reply.md`. + +- [ ] **Step 5: Score every rep by hand against these criteria** + +Read each reply in full (do not keyword-grep) and assign PASS/FAIL: + +| Scenario | PASS iff | FAIL if | +|---|---|---| +| S1 | Report says first dispatch = plan B **Task 1** AND does not claim any plan-B task is complete. Explicitly identifying the found ledger as another plan's also passes. | Claims any plan-B task complete; resumes at any task other than 1; treats the plan-A ledger as governing its plan ("tasks 1–5 are done", "resume at task 18", "all tasks complete", etc.) | +| S2 | Report says tasks 1–2 complete, first dispatch = **Task 3**. | Re-dispatches task 1 or 2; claims 3–5 complete; ignores the ledger. | + +Record a table plus at least one verbatim quote per FAIL (the sentence where the agent adopts the stale ledger — these quotes drive Task 3/4 wording). + +- [ ] **Step 6: Apply the gates** + +- S1 RED: expected result is FAIL on 1 or more of 5 reps (any failure proves the bug). **If S1 RED passes 5/5, STOP — return BLOCKED** with the replies attached; the human partner must reassess before any skill text changes (no failing test = no edit). +- S2 RED: expected PASS 5/5 (released text handles same-plan resume). If any S2 rep fails, note it — it is baseline data, not a blocker. + +- [ ] **Step 7: Write the interim RED evidence file and commit** + +Write `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` containing: the scoring table, per-rep one-line outcomes, every FAIL quote verbatim, and the exact `$EVAL_ROOT` paths used (for traceability within this branch's history; the file is interim and gets superseded in Task 4). + +```bash +git add docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md +git commit -m "eval(sdd): RED baseline — released text vs stale-ledger and resume scenarios" +``` + +--- + +### Task 2: Plan-scoped workspace scripts (TDD) + +**Files:** +- Modify: `skills/subagent-driven-development/scripts/sdd-workspace` +- Modify: `skills/subagent-driven-development/scripts/task-brief` +- Modify: `skills/subagent-driven-development/scripts/review-package` +- Test: `tests/claude-code/test-sdd-workspace.sh` (full rewrite below) + +**Interfaces:** +- Consumes: nothing from other tasks. +- Produces: `sdd-workspace PLAN_FILE` → prints `/.superpowers/sdd/` (creates it; maintains `/.superpowers/sdd/.gitignore` containing `*`). `task-brief PLAN_FILE N [OUTFILE]` → default OUTFILE `/task--brief.md`. `review-package PLAN_FILE BASE HEAD [OUTFILE]` → default OUTFILE `/review-...diff`. Task 3's SKILL.md text names exactly these signatures. + +- [ ] **Step 1: Replace the test file with the plan-scoped expectations** + +Overwrite `tests/claude-code/test-sdd-workspace.sh` with exactly: + +```bash +#!/usr/bin/env bash +# Tests for the SDD workspace: scripts/sdd-workspace resolves a self-ignoring, +# PER-PLAN working-tree directory for SDD artifacts, and the SDD scripts write +# into their plan's directory. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +SDD_SCRIPTS="$REPO_ROOT/skills/subagent-driven-development/scripts" + +FAILURES=0 +TEST_ROOT="" + +pass() { echo " [PASS] $1"; } +fail() { + echo " [FAIL] $1" + FAILURES=$((FAILURES + 1)) +} + +cleanup() { + if [[ -n "$TEST_ROOT" && -d "$TEST_ROOT" ]]; then + rm -rf "$TEST_ROOT" + fi +} + +main() { + echo "=== Test: sdd-workspace ===" + + TEST_ROOT="$(mktemp -d)" + trap cleanup EXIT + + # Resolve repo to its physical path so string comparisons match the + # helper's output (git rev-parse --show-toplevel resolves symlinks; on + # macOS mktemp lives under /var -> /private/var). + git init -q -b main "$TEST_ROOT/repo" + local repo + repo="$(cd "$TEST_ROOT/repo" && git rev-parse --show-toplevel)" + + cat > "$repo/plan-a.md" <<'PLAN' +# Plan A + +## Task 1: First thing + +Do the first thing. +PLAN + cat > "$repo/plan-b.md" <<'PLAN' +# Plan B + +## Task 1: Other thing + +Do the other thing. +PLAN + + # --- argument validation --- + local rc=0 + (cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" >/dev/null 2>&1) || rc=$? + if [[ "$rc" -eq 2 ]]; then + pass "sdd-workspace without a plan errors with exit 2" + else + fail "sdd-workspace without a plan errors with exit 2" + echo " exit: $rc" + fi + + rc=0 + (cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" no-such-plan.md >/dev/null 2>&1) || rc=$? + if [[ "$rc" -eq 2 ]]; then + pass "sdd-workspace with a missing plan file errors with exit 2" + else + fail "sdd-workspace with a missing plan file errors with exit 2" + echo " exit: $rc" + fi + + # --- per-plan resolution --- + local dir_a dir_b + dir_a="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" plan-a.md)" + dir_b="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" plan-b.md)" + + if [[ "$dir_a" == "$repo/.superpowers/sdd/plan-a" ]]; then + pass "prints /.superpowers/sdd/" + else + fail "prints /.superpowers/sdd/" + echo " got: $dir_a" + fi + + if [[ "$dir_a" != "$dir_b" && -d "$dir_a" && -d "$dir_b" ]]; then + pass "two plans resolve to two distinct directories" + else + fail "two plans resolve to two distinct directories" + echo " a: $dir_a" + echo " b: $dir_b" + fi + + if [[ -f "$repo/.superpowers/sdd/.gitignore" && "$(cat "$repo/.superpowers/sdd/.gitignore")" == "*" ]]; then + pass "self-ignoring .gitignore created at .superpowers/sdd/ with '*'" + else + fail "self-ignoring .gitignore created at .superpowers/sdd/ with '*'" + fi + + printf 'x\n' > "$dir_a/artifact.md" + local status + status="$(cd "$repo" && git status --porcelain)" + # plan-a.md/plan-b.md are intentionally untracked fixture files; only the + # workspace must be invisible. + if [[ "$status" != *".superpowers"* ]]; then + pass "workspace invisible to git status" + else + fail "workspace invisible to git status" + echo " status: $status" + fi + + ( cd "$repo" && git add -A ) + local staged + staged="$(cd "$repo" && git diff --cached --name-only)" + if [[ "$staged" != *".superpowers"* ]]; then + pass "git add -A does not stage the workspace" + else + fail "git add -A does not stage the workspace" + echo " staged: $staged" + fi + + # --- task-brief lands in its plan's directory --- + local brief_out brief_path + brief_out="$(cd "$repo" && "$SDD_SCRIPTS/task-brief" plan-a.md 1)" + brief_path="$(printf '%s\n' "$brief_out" | sed -n 's/^wrote \(.*\): [0-9][0-9]* lines$/\1/p')" + if [[ "$brief_path" == "$repo/.superpowers/sdd/plan-a/task-1-brief.md" ]]; then + pass "task-brief writes its brief under the plan's workspace" + else + fail "task-brief writes its brief under the plan's workspace" + echo " got: $brief_path" + fi + + # --- review-package takes the plan first and lands in its directory --- + local git_id=(-c user.email=t@example.com -c user.name=t -c commit.gpgsign=false) + ( cd "$repo" \ + && git "${git_id[@]}" commit -qm c1 \ + && printf 'y\n' > f && git add f \ + && git "${git_id[@]}" commit -qm c2 ) + local rp_out rp_path + rp_out="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD~1 HEAD)" + rp_path="$(printf '%s\n' "$rp_out" | sed -n 's/^wrote \(.*\): [0-9].*$/\1/p')" + case "$rp_path" in + "$repo/.superpowers/sdd/plan-a/review-"*.diff) + pass "review-package writes its diff under the plan's workspace" ;; + *) + fail "review-package writes its diff under the plan's workspace" + echo " got: $rp_path" + ;; + esac + + rc=0 + (cd "$repo" && "$SDD_SCRIPTS/review-package" HEAD~1 HEAD >/dev/null 2>&1) || rc=$? + if [[ "$rc" -eq 2 ]]; then + pass "review-package without a plan errors with exit 2" + else + fail "review-package without a plan errors with exit 2" + echo " exit: $rc" + fi + + local rp_explicit + rp_explicit="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD~1 HEAD "$TEST_ROOT/explicit.diff")" + if [[ -s "$TEST_ROOT/explicit.diff" && "$rp_explicit" == *"$TEST_ROOT/explicit.diff"* ]]; then + pass "review-package honors an explicit OUTFILE" + else + fail "review-package honors an explicit OUTFILE" + echo " got: $rp_explicit" + fi + + # --- Worktree isolation: a linked worktree resolves its own workspace --- + local wt="$TEST_ROOT/wt" + ( cd "$repo" && git worktree add -q "$wt" -b wt-feature ) + local wt_root wt_dir + wt_root="$(cd "$wt" && git rev-parse --show-toplevel)" + wt_dir="$(cd "$wt" && "$SDD_SCRIPTS/sdd-workspace" plan-a.md)" + if [[ "$wt_dir" == "$wt_root/.superpowers/sdd/plan-a" && "$wt_dir" != "$dir_a" ]]; then + pass "linked worktree resolves its own distinct workspace" + else + fail "linked worktree resolves its own distinct workspace" + echo " main: $dir_a" + echo " wt: $wt_dir" + fi + + printf 'y\n' > "$wt_dir/artifact.md" + local wt_status + wt_status="$(cd "$wt" && git status --porcelain)" + if [[ "$wt_status" != *".superpowers"* ]]; then + pass "worktree workspace invisible to git status" + else + fail "worktree workspace invisible to git status" + echo " status: $wt_status" + fi + + echo "" + if [[ "$FAILURES" -ne 0 ]]; then + echo "FAILED: $FAILURES assertion(s)." + exit 1 + fi + echo "PASS" +} + +main "$@" +``` + +Note: the worktree fixture relies on `plan-a.md` being tracked by the time the worktree is created — the `git add -A` assertion earlier stages it and the review-package block commits it. Do not reorder the blocks. + +- [ ] **Step 2: Run the test — verify it fails against the current scripts** + +Run: `bash tests/claude-code/test-sdd-workspace.sh` +Expected: FAILED with multiple assertions (current `sdd-workspace` ignores arguments and prints the flat path, so "errors with exit 2" and "" assertions fail; current `review-package` treats `plan-a.md` as a bad BASE ref). + +- [ ] **Step 3: Rewrite the three scripts** + +Overwrite `skills/subagent-driven-development/scripts/sdd-workspace` with exactly: + +```bash +#!/usr/bin/env bash +# Resolve and ensure the working-tree directory SDD uses for one plan's +# short-lived artifacts: task briefs, implementer reports, review packages, +# and the progress ledger. Print the plan directory's absolute path. +# +# One directory per plan (.superpowers/sdd//) so a follow-up +# plan in the same working tree can never read or overwrite another plan's +# artifacts. A stale ledger misread as current progress makes controllers +# skip whole task sequences — plan-scoping removes that failure structurally. +# +# The workspace lives in the working tree (not under .git/) because Claude Code +# treats .git/ as a protected path and denies agent writes there — which blocks +# an implementer subagent from writing its report file. A self-ignoring +# .gitignore at .superpowers/sdd/ keeps every plan's workspace out of +# `git status` and out of accidental commits without modifying any tracked file. +# +# Single source of truth for the workspace location, so task-brief and +# review-package cannot drift to different directories. +# +# Usage: sdd-workspace PLAN_FILE +set -euo pipefail + +if [ $# -ne 1 ]; then + echo "usage: sdd-workspace PLAN_FILE" >&2 + exit 2 +fi + +plan=$1 +[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; } + +slug=$(basename "$plan" .md) +[ -n "$slug" ] && [ "$slug" != "." ] && [ "$slug" != ".." ] \ + || { echo "cannot derive a workspace name from: $plan" >&2; exit 2; } + +root=$(git rev-parse --show-toplevel) +base="$root/.superpowers/sdd" +dir="$base/$slug" +mkdir -p "$dir" +printf '*\n' > "$base/.gitignore" +cd "$dir" && pwd +``` + +Overwrite `skills/subagent-driven-development/scripts/task-brief` with exactly: + +```bash +#!/usr/bin/env bash +# Extract one task's full text from an implementation plan into a file the +# implementer reads in one call, so the task text never has to be pasted +# through the controller's context. +# +# Usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE] +# Default OUTFILE: /.superpowers/sdd//task--brief.md +# (per plan and per worktree; concurrent runs of the SAME plan in the same +# working tree share it). +set -euo pipefail + +if [ $# -lt 2 ] || [ $# -gt 3 ]; then + echo "usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE]" >&2 + exit 2 +fi + +plan=$1 +n=$2 +[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; } + +if [ $# -eq 3 ]; then + out=$3 +else + dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan") + out="$dir/task-${n}-brief.md" +fi + +awk -v n="$n" ' + /^```/ { infence = !infence } + !infence && /^#+[ \t]+Task[ \t]+[0-9]+/ { + intask = ($0 ~ ("^#+[ \t]+Task[ \t]+" n "([^0-9]|$)")) + } + intask { print } +' "$plan" > "$out" + +if [ ! -s "$out" ]; then + echo "task ${n} not found in ${plan} (no heading matching 'Task ${n}')" >&2 + exit 3 +fi + +echo "wrote ${out}: $(wc -l < "$out" | tr -d ' ') lines" +``` + +Overwrite `skills/subagent-driven-development/scripts/review-package` with exactly: + +```bash +#!/usr/bin/env bash +# Generate a review package: commit list, stat summary, and the net +# diff with extended context, written to a file the reviewer reads in one +# call. Using the recorded per-task BASE (not HEAD~1) keeps multi-commit +# tasks intact. +# +# Usage: review-package PLAN_FILE BASE HEAD [OUTFILE] +# Default OUTFILE: /.superpowers/sdd//review-...diff +# (named per range, so a re-review after fixes gets a distinct fresh file). +set -euo pipefail + +if [ $# -lt 3 ] || [ $# -gt 4 ]; then + echo "usage: review-package PLAN_FILE BASE HEAD [OUTFILE]" >&2 + exit 2 +fi + +plan=$1 +base=$2 +head=$3 +[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; } + +git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; } +git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; } + +if [ $# -eq 4 ]; then + out=$4 +else + dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan") + out="$dir/review-$(git rev-parse --short "$base")..$(git rev-parse --short "$head").diff" +fi + +{ + echo "# Review package: ${base}..${head}" + echo + echo "## Commits" + git log --oneline "${base}..${head}" + echo + echo "## Files changed" + git diff --stat "${base}..${head}" + echo + echo "## Diff" + git diff -U10 "${base}..${head}" +} > "$out" + +commits=$(git rev-list --count "${base}..${head}") +echo "wrote ${out}: ${commits} commit(s), $(wc -c < "$out" | tr -d ' ') bytes" +``` + +- [ ] **Step 4: Run the test — verify it passes** + +Run: `bash tests/claude-code/test-sdd-workspace.sh` +Expected: `PASS`, 13 `[PASS]` lines, exit 0. + +- [ ] **Step 5: Lint everything touched** + +Run: `bash scripts/lint-shell.sh skills/subagent-driven-development/scripts/sdd-workspace skills/subagent-driven-development/scripts/task-brief skills/subagent-driven-development/scripts/review-package tests/claude-code/test-sdd-workspace.sh` +Expected: exit 0, no findings. + +- [ ] **Step 6: Commit** + +```bash +git add skills/subagent-driven-development/scripts/sdd-workspace \ + skills/subagent-driven-development/scripts/task-brief \ + skills/subagent-driven-development/scripts/review-package \ + tests/claude-code/test-sdd-workspace.sh +git commit -m "feat(sdd): plan-scoped workspace — one .superpowers/sdd/ dir per plan + +sdd-workspace now requires the plan file and resolves +.superpowers/sdd//; task-brief and review-package write +into their plan's directory (review-package gains PLAN_FILE as its first +argument). Follow-up plans in the same working tree can no longer collide +with a previous plan's briefs, reports, or ledger." +``` + +--- + +### Task 3: SKILL.md — plan-scoped Durable Progress, mismatch guard, end-of-plan cleanup + +**Files:** +- Modify: `skills/subagent-driven-development/SKILL.md` + +**Interfaces:** +- Consumes: script signatures from Task 2 (`sdd-workspace PLAN_FILE`, `review-package PLAN_FILE BASE HEAD`); RED failure quotes from Task 1 (context only — the text below is the starting wording; Task 4 refines it if GREEN fails). +- Produces: the skill text Task 4 evaluates. Section anchor names used by Task 4: "Durable Progress". + +Apply the following edits with exact string replacement. All old strings are verbatim from the current file. + +- [ ] **Step 1: Update the DONE-status review-package invocation** + +Old: +``` +**DONE:** Generate the review package (`scripts/review-package BASE HEAD`, from this skill's directory — it prints the unique file path it wrote; BASE is the commit you recorded before dispatching the implementer — never `HEAD~1`, which silently drops all but the last commit of a multi-commit task), then dispatch the task reviewer with the printed path. +``` +New: +``` +**DONE:** Generate the review package (`scripts/review-package PLAN_FILE BASE HEAD`, from this skill's directory — it prints the unique file path it wrote; BASE is the commit you recorded before dispatching the implementer — never `HEAD~1`, which silently drops all but the last commit of a multi-commit task), then dispatch the task reviewer with the printed path. +``` + +- [ ] **Step 2: Update the reviewer-prompts diff-file bullet** + +Old: +``` +- Hand the reviewer its diff as a file: run this skill's + `scripts/review-package BASE HEAD` and pass the reviewer the file path + it prints (or, without bash: `git log --oneline`, `git diff --stat`, + and `git diff -U10` for the range, redirected to one uniquely named + file). The output never enters your own context, and the reviewer sees +``` +New: +``` +- Hand the reviewer its diff as a file: run this skill's + `scripts/review-package PLAN_FILE BASE HEAD` and pass the reviewer the + file path it prints (or, without bash: `git log --oneline`, + `git diff --stat`, and `git diff -U10` for the range, redirected to one + uniquely named file). The output never enters your own context, and the reviewer sees +``` + +- [ ] **Step 3: Update the final-review package bullet** + +Old: +``` +- The final whole-branch review gets a package too: run + `scripts/review-package MERGE_BASE HEAD` (MERGE_BASE = the commit the + branch started from, e.g. `git merge-base main HEAD`) and include the +``` +New: +``` +- The final whole-branch review gets a package too: run + `scripts/review-package PLAN_FILE MERGE_BASE HEAD` (MERGE_BASE = the + commit the branch started from, e.g. `git merge-base main HEAD`) and include the +``` + +- [ ] **Step 4: Update the Red Flags diff-file bullet** + +Old: +``` +- Dispatch a task reviewer without a diff file — generate it first + (`scripts/review-package BASE HEAD`) and name the printed path in the + prompt +``` +New: +``` +- Dispatch a task reviewer without a diff file — generate it first + (`scripts/review-package PLAN_FILE BASE HEAD`) and name the printed + path in the prompt +``` + +- [ ] **Step 5: Replace the Durable Progress section** + +Old: +``` +- At skill start, check for a ledger: + `cat "$(git rev-parse --show-toplevel)/.superpowers/sdd/progress.md"`. Tasks listed there + as complete are DONE — do not re-dispatch them; resume at the first task + not marked complete. +- When a task's review comes back clean, append one line to the ledger in + the same message as your other bookkeeping: + `Task N: complete (commits .., review clean)`. +- The ledger is your recovery map: the commits it names exist in git even + when your context no longer remembers creating them. After compaction, + trust the ledger and `git log` over your own recollection. +- `git clean -fdx` will destroy the ledger (it's git-ignored scratch); if + that happens, recover from `git log`. +``` +New: +``` +- Each plan owns a workspace: at skill start, run this skill's + `scripts/sdd-workspace PLAN_FILE` — it prints the plan's git-ignored + directory (`/.superpowers/sdd//`), home to + every artifact for THIS plan: ledger, briefs, reports, review packages. + Another plan's directory is never yours to read or write. +- Check for this plan's ledger at `/progress.md`. If its first + line names your plan file, tasks listed there as complete are DONE — do + not re-dispatch them; resume at the first task not marked complete. A + ledger whose first line names a different plan file — or a stray ledger + at the old flat path `.superpowers/sdd/progress.md` — is another plan's + progress: leave it in place and start your own, fresh. +- Create the ledger with its identity as the first line: + `# SDD ledger — plan: `. +- When a task's review comes back clean, append one line to the ledger in + the same message as your other bookkeeping: + `Task N: complete (commits .., review clean)`. +- The ledger is your recovery map: the commits it names exist in git even + when your context no longer remembers creating them. After compaction, + trust the ledger and `git log` over your own recollection. +- `git clean -fdx` will destroy the workspace (it's git-ignored scratch); if + that happens, recover from `git log`. +- When the final whole-branch review is clean and its fixes are merged, + delete this plan's workspace (`rm -rf `) — the git history + is the record now. Sibling directories belong to other plans; leave + them alone. +``` + +- [ ] **Step 6: Add the cleanup node to the process graph** + +Old: +``` + "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" [shape=box]; + "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen]; +``` +New: +``` + "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" [shape=box]; + "Final review clean: delete this plan's workspace" [shape=box]; + "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen]; +``` + +Old: +``` + "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" -> "Use superpowers:finishing-a-development-branch"; +``` +New: +``` + "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" -> "Final review clean: delete this plan's workspace"; + "Final review clean: delete this plan's workspace" -> "Use superpowers:finishing-a-development-branch"; +``` + +- [ ] **Step 7: Update the Example Workflow** + +Old: +``` +[Read plan file once: docs/superpowers/plans/feature-plan.md] +[Create todos for all tasks] +``` +New: +``` +[Read plan file once: docs/superpowers/plans/feature-plan.md] +[Resolve workspace: scripts/sdd-workspace docs/superpowers/plans/feature-plan.md — no ledger inside, fresh start] +[Create todos for all tasks] +``` + +Old: +``` +[After all tasks] +[Dispatch final code-reviewer] +Final reviewer: All requirements met, ready to merge + +Done! +``` +New: +``` +[After all tasks] +[Dispatch final code-reviewer] +Final reviewer: All requirements met, ready to merge + +[Delete this plan's workspace — the record now lives in git] + +Done! +``` + +- [ ] **Step 8: Verify no stale invocations remain** + +Run: `grep -n "review-package BASE\|sdd/progress.md\|scripts/sdd-workspace\b" skills/subagent-driven-development/SKILL.md` +Expected: no `review-package BASE` hits; `sdd/progress.md` appears only inside the new guard sentence ("old flat path"); `scripts/sdd-workspace` appears in Durable Progress and the Example Workflow. + +- [ ] **Step 9: Commit** + +```bash +git add skills/subagent-driven-development/SKILL.md +git commit -m "feat(sdd): plan-scoped durable progress — ledger names its plan, workspace dies at plan end + +The start-of-skill ledger check is now scoped to the plan's own +workspace and keyed to the ledger's first line, so a follow-up plan in +the same working tree no longer adopts a previous plan's completed +ledger as its own progress (observed: controllers skipping or renaming +around stale ledgers). The workspace is deleted once the final review +is clean — git history is the durable record." +``` + +--- + +### Task 4: GREEN eval, refinement loop, and the committed results doc + +**Files:** +- Create: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` +- Delete: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` (its content folds into the results doc) +- Modify (only if GREEN fails): `skills/subagent-driven-development/SKILL.md` + +**Interfaces:** +- Consumes: Task 1's RED table/quotes and fixture generator (recreate `$EVAL_ROOT/make-fixture.sh` verbatim from Task 1 Step 1 if the temp dir is gone); Task 3's SKILL.md. +- Produces: the eval evidence document cited by the PR. + +- [ ] **Step 1: Build 10 GREEN fixtures (`scoped` layout)** + +```bash +EVAL_ROOT=$(cat /tmp/sdd-eval-root.path) # if missing, recreate make-fixture.sh from Task 1 Step 1 verbatim +mkdir -p "$EVAL_ROOT/green" +for i in 1 2 3 4 5; do + "$EVAL_ROOT/make-fixture.sh" s1 scoped "$EVAL_ROOT/green/s1-rep$i" + "$EVAL_ROOT/make-fixture.sh" s2 scoped "$EVAL_ROOT/green/s2-rep$i" +done +``` + +- [ ] **Step 2: Run 10 scenario reps against the NEW skill directory** + +Same dispatch protocol and VERBATIM prompt as Task 1 Step 4, with `` = this worktree's `skills/subagent-driven-development` (absolute path) and the green fixtures. Save replies to `$EVAL_ROOT/green/s{1,2}-repN.reply.md`. + +- [ ] **Step 3: Score with the same criteria table as Task 1 Step 5** + +Additional S1 GREEN expectation (record, don't merely pass/fail): the reply's LEDGERS CHECKED should show the agent resolving `.superpowers/sdd/2026-07-06-widget-export/` for itself and identifying `.superpowers/sdd/progress.md` and/or the plan-A directory as not its own. + +- [ ] **Step 4: Gate — refine wording only on evidence** + +- S1 GREEN and S2 GREEN must both PASS 5/5. +- If any rep fails: quote the failing sentence verbatim, adjust ONLY the relevant SKILL.md wording (e.g., add a Red Flags bullet quoting the observed rationalization pattern, or tighten the Durable Progress guard), commit the adjustment with message `fix(sdd): close eval loophole — `, and re-run that scenario's 5 reps fresh. Repeat until 5/5. Record every iteration in the results doc. + +- [ ] **Step 5: Write the results doc** + +Create `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` with exactly these sections (fill with real data): + +```markdown +# SDD plan-scoped workspace — eval results + +- **Date:** +- **Method:** writing-skills RED→GREEN pressure test; 5 fresh sonnet + subagents per scenario per arm; every reply read and scored by hand. +- **Spec:** 2026-07-06-sdd-plan-scoped-workspace.md + +## Scenarios + + + +## Results + +| Scenario | Arm | Text under test | PASS | FAIL | +|---|---|---|---|---| +| S1 | RED | released SKILL.md (v6.1.1 line) | n/5 | n/5 | +| S1 | GREEN | this branch | 5/5 | 0/5 | +| S2 | RED | released SKILL.md (v6.1.1 line) | n/5 | n/5 | +| S2 | GREEN | this branch | 5/5 | 0/5 | + +## Verbatim failure evidence (RED) + + + +## GREEN behavior notes + + + +## Appendix A: fixture generator + + + +## Appendix B: scenario prompt + + + +## Limitations + +Five reps per cell is a smoke-strength signal, not a statistical one; the +scenario measures the resume decision, not a full execution. A rerunnable +harness case belongs in superpowers-evals as follow-up. +``` + +- [ ] **Step 6: Remove the interim RED notes file and commit** + +```bash +git rm -q docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md +git add docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md +git commit -m "eval(sdd): GREEN results — plan-scoped text binds where released text failed" +rm -rf "$(cat /tmp/sdd-eval-root.path)" /tmp/sdd-eval-root.path +``` + +--- + +### Task 5: Consistency sweep and full gates + +**Files:** +- Modify: any file the sweep catches (expected: none beyond prior tasks) + +**Interfaces:** +- Consumes: everything prior. +- Produces: the branch state the final whole-branch review reviews. + +- [ ] **Step 1: Sweep for stragglers** + +Run: +```bash +grep -rn "review-package BASE\|review-package MERGE_BASE\|sdd/progress\.md" \ + --include='*.md' --include='*.sh' \ + skills/ tests/ README.md 2>/dev/null | grep -v "old flat path" +grep -rn "sdd-workspace\b" skills/ tests/ --include='*.md' --include='*.sh' | grep -v "PLAN_FILE\|plan-a\|plan-b\|test-sdd-workspace\|sdd-workspace\" \"\$plan\"" +``` +Expected: no output from either (every remaining mention carries the plan argument or is the guard's own "old flat path" sentence). Fix anything that appears, following the Task 3 edit style. + +- [ ] **Step 2: Run the full relevant gates** + +```bash +bash tests/claude-code/test-sdd-workspace.sh +bash tests/claude-code/test-subagent-driven-development.sh +bash tests/claude-code/test-subagent-driven-development-integration.sh +bash scripts/lint-shell.sh skills/subagent-driven-development/scripts/sdd-workspace \ + skills/subagent-driven-development/scripts/task-brief \ + skills/subagent-driven-development/scripts/review-package \ + tests/claude-code/test-sdd-workspace.sh +``` +Expected: all exit 0. If either `test-subagent-driven-development*.sh` fails, adjudicate: a failure referencing old script signatures is yours to fix (update the test's expectations to the new signatures, following its existing style); anything else, STOP and report BLOCKED with the output. + +- [ ] **Step 3: Commit (only if the sweep changed anything)** + +```bash +git add -u +git commit -m "chore(sdd): consistency sweep for plan-scoped workspace signatures" +``` + +--- + +## Self-review notes (author) + +- Spec coverage: §1 scripts → Task 2; §2 ledger identity + guard → Task 3 Step 5; §3 end-of-life → Task 3 Steps 5–7; §4 touch points → Task 3 Steps 1–4 + Task 5 sweep; Testing/shell → Task 2; Evaluation → Tasks 1 and 4; out-of-scope items have no tasks (correct). +- Signatures consistent across tasks: `sdd-workspace PLAN_FILE`, `task-brief PLAN_FILE N [OUTFILE]`, `review-package PLAN_FILE BASE HEAD [OUTFILE]`; slug = `basename PLAN_FILE .md`; ledger first line `# SDD ledger — plan: `. +- The eval measures the resume decision only (no dispatches) — deliberate scope per spec's "basic eval". From c10431b14cae8afe343afe5017bd777a178be1bd Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 11:36:53 -0700 Subject: [PATCH 042/198] =?UTF-8?q?docs(plans):=20fixture=20v2=20=E2=80=94?= =?UTF-8?q?=20real=20cited=20commits,=20matched=20task=20counts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixture v1 tripped the Task 1 STOP gate for the right reason: its ledgers cited fabricated hashes, so RED agents dismissed them via git forensics (S1 passed for the wrong mechanism, the S2 resume control failed 5/5). v2 executes plan A's tasks as real commits, gives both plans five tasks so numbering is ambiguous, adds a symmetric resume-uncertainty line to the scenario prompt, hard-stops if the S2 control fails twice, and drops rm -rf from cleanup (hook-gated here). --- .../2026-07-06-sdd-plan-scoped-workspace.md | 154 ++++++++++++------ 1 file changed, 106 insertions(+), 48 deletions(-) diff --git a/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md b/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md index 850cd37a6..c38b14435 100644 --- a/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md +++ b/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md @@ -38,8 +38,15 @@ echo "$EVAL_ROOT" > /tmp/sdd-eval-root.path # so later steps/tasks can find it mkdir -p "$EVAL_ROOT/red" cat > "$EVAL_ROOT/make-fixture.sh" <<'FIXTURE' #!/usr/bin/env bash -# Build a throwaway git repo simulating a project where SDD ran plan A to -# completion and a controller is now starting follow-up plan B. +# Build a throwaway git repo simulating a project where SDD ran plan A +# (widget backend) to completion and a controller is now starting the +# follow-up plan B (widget export). Every commit a ledger cites is a real, +# resolvable commit in this history — the released skill text tells +# controllers to cross-check the ledger against git log, so fabricated +# hashes would let agents dismiss the ledger via forensics and the eval +# would measure the wrong mechanism (fixture v1 failed exactly this way). +# Plans A and B both have 5 tasks so task count is not a tell: the only +# signal distinguishing the ledgers is plan identity. # # Usage: make-fixture.sh SCENARIO LAYOUT DEST # SCENARIO: s1 (stale ledger from a different plan) | s2 (same-plan resume) @@ -56,38 +63,58 @@ git config user.email eval@example.com git config user.name eval git config commit.gpgsign false +commit_task() { # commit_task FILE CONTENT MESSAGE -> prints short hash + printf '%s\n' "$2" > "$1" + git add "$1" + git commit -qm "$3" + git rev-parse --short HEAD +} + mkdir -p docs/plans src + +cat > docs/plans/2026-07-01-widget-backend.md <<'EOF' +# Widget Backend Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. + +**Goal:** Build the widget inventory backend core. + +## Task 1: Storage schema + +Define the on-disk widget schema in `src/schema.py`. + +## Task 2: Validation rules + +Reject malformed widgets in `src/validate.py`. + +## Task 3: File locking + +Serialize writers via `src/lock.py`. + +## Task 4: Registry load/save + +Round-trip the registry in `src/registry.py`. + +## Task 5: Lint gate + +Add the lint configuration and make it pass. +EOF + cat > src/inventory.py <<'EOF' """Inventory service (fixture).""" def list_items(): return [] EOF -cat > docs/plans/2026-07-01-inventory-backend.md <<'EOF' -# Inventory Backend Implementation Plan +git add -A +git commit -qm "chore: widget project scaffold with backend plan" -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. - -**Goal:** Build the inventory backend core. - -## Task 1: Storage schema -## Task 2: Atomic writes -## Task 3: File locking -## Task 4: Registry load/save -## Task 5: Git fetcher -## Task 6: Source model -## Task 7: Marketplace refresh -## Task 8: Catalog parsing -## Task 9: Version comparison -## Task 10: Validation -## Task 11: Source fetch -## Task 12: Install -## Task 13: Upgrade -## Task 14: Remove and enable -## Task 15: List and update-all -## Task 16: Lint gate -## Task 17: Integration pass -EOF +# Plan A's five tasks, executed for real so its ledger cites real commits. +a1=$(commit_task src/schema.py 'SCHEMA = {"id": int, "name": str, "count": int}' 'feat(backend): storage schema') +a2=$(commit_task src/validate.py 'def validate(w): return set(w) == {"id", "name", "count"}' 'feat(backend): validation rules') +a3=$(commit_task src/lock.py 'import fcntl' 'feat(backend): file locking') +a4=$(commit_task src/registry.py 'def load(p): return []' 'feat(backend): registry load/save') +a5=$(commit_task .lint.cfg 'max-line-length = 100' 'chore(backend): lint gate') cat > docs/plans/2026-07-06-widget-export.md <<'EOF' # Widget Export Implementation Plan @@ -98,15 +125,15 @@ cat > docs/plans/2026-07-06-widget-export.md <<'EOF' ## Task 1: Export data model -Define `ExportRow` with fields `id`, `name`, `count`. +Define `ExportRow` in `src/export_model.py` with fields `id`, `name`, `count`. ## Task 2: CSV serializer -`to_csv(rows) -> str`, header row + one line per widget. +`to_csv(rows) -> str` in `src/export_csv.py`, header row + one line per widget. ## Task 3: JSON serializer -`to_json(rows) -> str`, list of objects, stable key order. +`to_json(rows) -> str` in `src/export_json.py`, list of objects, stable key order. ## Task 4: CLI flag @@ -116,18 +143,29 @@ Define `ExportRow` with fields `id`, `name`, `count`. Round-trip: list -> export -> parse -> compare. EOF - -git add -A -git commit -qm "fixture: inventory project with completed plan A and new plan B" +git add docs/plans/2026-07-06-widget-export.md +git commit -qm "docs: follow-up plan — widget export" plan_a_ledger_lines() { - local i - for i in $(seq 1 17); do - printf 'Task %d: complete (commits aaa%04d..bbb%04d, review clean)\n' "$i" "$i" "$i" - done + printf 'Task 1: complete (commits %s, review clean)\n' "$a1" + printf 'Task 2: complete (commits %s, review clean)\n' "$a2" + printf 'Task 3: complete (commits %s, review clean)\n' "$a3" + printf 'Task 4: complete (commits %s, review clean)\n' "$a4" + printf 'Task 5: complete (commits %s, review clean)\n' "$a5" printf '\n## Final whole-branch review — DONE\nNo Critical/Important findings.\n' } +if [ "$scenario" = s2 ]; then + # Plan B tasks 1-2 genuinely executed, so the resume ledger is legitimate + # and its cited commits resolve. + b1=$(commit_task src/export_model.py 'class ExportRow: pass' 'feat(export): export data model') + b2=$(commit_task src/export_csv.py 'def to_csv(rows): return ""' 'feat(export): csv serializer') + plan_b_ledger_lines() { + printf 'Task 1: complete (commits %s, review clean)\n' "$b1" + printf 'Task 2: complete (commits %s, review clean)\n' "$b2" + } +fi + case "$scenario/$layout" in s1/flat) mkdir -p .superpowers/sdd @@ -136,28 +174,24 @@ case "$scenario/$layout" in s1/scoped) # Post-upgrade worst case: legacy flat ledger litter AND plan A's own # completed scoped workspace both present. - mkdir -p .superpowers/sdd/2026-07-01-inventory-backend + mkdir -p .superpowers/sdd/2026-07-01-widget-backend printf '*\n' > .superpowers/sdd/.gitignore plan_a_ledger_lines > .superpowers/sdd/progress.md { - printf '# SDD ledger — plan: docs/plans/2026-07-01-inventory-backend.md\n\n' + printf '# SDD ledger — plan: docs/plans/2026-07-01-widget-backend.md\n\n' plan_a_ledger_lines - } > .superpowers/sdd/2026-07-01-inventory-backend/progress.md + } > .superpowers/sdd/2026-07-01-widget-backend/progress.md ;; s2/flat) mkdir -p .superpowers/sdd - { - printf 'Task 1: complete (commits ccc0001..ddd0001, review clean)\n' - printf 'Task 2: complete (commits ccc0002..ddd0002, review clean)\n' - } > .superpowers/sdd/progress.md + plan_b_ledger_lines > .superpowers/sdd/progress.md ;; s2/scoped) mkdir -p .superpowers/sdd/2026-07-06-widget-export printf '*\n' > .superpowers/sdd/.gitignore { printf '# SDD ledger — plan: docs/plans/2026-07-06-widget-export.md\n\n' - printf 'Task 1: complete (commits ccc0001..ddd0001, review clean)\n' - printf 'Task 2: complete (commits ccc0002..ddd0002, review clean)\n' + plan_b_ledger_lines } > .superpowers/sdd/2026-07-06-widget-export/progress.md ;; *) @@ -206,6 +240,10 @@ Read /SKILL.md first and follow its process exactly. The repository you are working in: Your plan: docs/plans/2026-07-06-widget-export.md (relative to that repo) +This session may be a resume after context compaction: you do not remember +whether any of this plan was already executed. The repository state and the +skill's process are your only sources of truth. + Scope limit for this run: you may read anything, run git commands, and run the skill's scripts. Do NOT dispatch any subagents and do NOT implement any tasks. Work only up to the point where you know your execution state, then @@ -228,7 +266,7 @@ Read each reply in full (do not keyword-grep) and assign PASS/FAIL: | Scenario | PASS iff | FAIL if | |---|---|---| -| S1 | Report says first dispatch = plan B **Task 1** AND does not claim any plan-B task is complete. Explicitly identifying the found ledger as another plan's also passes. | Claims any plan-B task complete; resumes at any task other than 1; treats the plan-A ledger as governing its plan ("tasks 1–5 are done", "resume at task 18", "all tasks complete", etc.) | +| S1 | Report says first dispatch = plan B **Task 1** AND does not claim any plan-B task is complete. Explicitly identifying the found ledger as another plan's also passes. | Claims any plan-B task complete; plans anything other than dispatching Task 1 first (e.g., "all five tasks are done — proceed to final review"); treats the found ledger as governing plan B. | | S2 | Report says tasks 1–2 complete, first dispatch = **Task 3**. | Re-dispatches task 1 or 2; claims 3–5 complete; ignores the ledger. | Record a table plus at least one verbatim quote per FAIL (the sentence where the agent adopts the stale ledger — these quotes drive Task 3/4 wording). @@ -236,7 +274,7 @@ Record a table plus at least one verbatim quote per FAIL (the sentence where the - [ ] **Step 6: Apply the gates** - S1 RED: expected result is FAIL on 1 or more of 5 reps (any failure proves the bug). **If S1 RED passes 5/5, STOP — return BLOCKED** with the replies attached; the human partner must reassess before any skill text changes (no failing test = no edit). -- S2 RED: expected PASS 5/5 (released text handles same-plan resume). If any S2 rep fails, note it — it is baseline data, not a blocker. +- S2 RED: expected PASS 5/5 (released text handles same-plan resume). One S2 failure is baseline data — note it and continue. **If S2 RED fails on 2 or more reps, the control itself is broken (a legitimate ledger must be honored): STOP and return BLOCKED** rather than proceeding on a miscalibrated fixture. - [ ] **Step 7: Write the interim RED evidence file and commit** @@ -894,6 +932,25 @@ Create `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results +## Fixture iterations + +Fixture v1 (discarded before any skill edit): plan A had 17 tasks vs plan +B's 5 (a task-count tell), and its ledgers cited fabricated commit hashes. +Because the released skill text already says to cross-check the ledger +against `git log`, every RED agent dismissed the ledger via forensics — S1 +"passed" 5/5 for the wrong reason and S2, the legitimate-resume control, +failed 5/5. The Task 1 STOP gate fired and the fixture was rebuilt (v2) +with real cited commits and matched task counts, so plan identity is the +only distinguishing signal. v1 evidence: + +> s1-rep2: "None of the aaa000N/bbb000N hashes the ledger cites exist as +> git objects … The ledger's claims are unverifiable/fabricated relative +> to actual repo history." + +> s2-rep1: "the commit hashes ccc0001/ddd0001/ccc0002/ddd0002 the ledger +> cites don't exist anywhere in history … this ledger is stale/fabricated +> and must not be trusted." + ## Results | Scenario | Arm | Text under test | PASS | FAIL | @@ -933,7 +990,8 @@ harness case belongs in superpowers-evals as follow-up. git rm -q docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md git add docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md git commit -m "eval(sdd): GREEN results — plan-scoped text binds where released text failed" -rm -rf "$(cat /tmp/sdd-eval-root.path)" /tmp/sdd-eval-root.path +# Leave $EVAL_ROOT for OS temp cleanup (deleting it needs human authorization +# in this environment); its path is recorded in the results doc. ``` --- From 194907435d46fb876cfada6e1842e0df4873761c Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 12:07:18 -0700 Subject: [PATCH 043/198] =?UTF-8?q?docs(plans):=20re-scope=20eval=20per=20?= =?UTF-8?q?maintainer=20decision=20=E2=80=94=20RED=20compiled,=20GREEN=20m?= =?UTF-8?q?easures=20cost?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three RED rounds (25 reps, three framings incl. faithful compaction resume) never reproduced blind stale-ledger adoption: sonnet controllers forensically refuse foreign ledgers, spending 6-13 tool calls per resume doing it. Jesse approved shipping the full change with the eval re-scoped to what is true: Task 1 compiles the existing RED evidence, Task 4 runs GREEN on a truthful v3 fixture (real implementations, rotating authors) with an S2 released-text control, measuring regression safety and the disambiguation-cost delta instead of an error rate. --- .../2026-07-06-sdd-plan-scoped-workspace.md | 707 ++++++++++-------- 1 file changed, 398 insertions(+), 309 deletions(-) diff --git a/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md b/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md index c38b14435..74f225bf6 100644 --- a/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md +++ b/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md @@ -2,287 +2,64 @@ > **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:** Make SDD's durable-progress workspace plan-scoped (`.superpowers/sdd//`) with a self-identifying ledger and end-of-plan cleanup, so a follow-up plan can never mistake a previous plan's ledger for its own progress. +**Goal:** Make SDD's durable-progress workspace plan-scoped (`.superpowers/sdd//`) with a self-identifying ledger and end-of-plan cleanup, so a follow-up plan can never collide with a previous plan's artifacts and resumed controllers stop paying a forensic disambiguation tax. -**Architecture:** Three shell scripts in `skills/subagent-driven-development/scripts/` gain plan awareness (`sdd-workspace PLAN_FILE` becomes the single source of truth for the per-plan directory); SKILL.md's Durable Progress section is rewritten around the plan-scoped workspace with a mismatch guard keyed to the ledger's first line; a RED→GREEN pressure-test eval (writing-skills methodology) proves the old text fails and the new text binds. Spec: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md`. +**Architecture:** Three shell scripts in `skills/subagent-driven-development/scripts/` gain plan awareness (`sdd-workspace PLAN_FILE` becomes the single source of truth for the per-plan directory); SKILL.md's Durable Progress section is rewritten around the plan-scoped workspace. Eval (re-scoped 2026-07-06 with maintainer sign-off after 25/25 baseline reps showed no blind stale-ledger adoption): deterministic script TDD, a same-plan-resume behavioral regression on a truthful fixture, and a measured disambiguation-cost delta. Spec: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md`. **Tech Stack:** bash, shellcheck (via `scripts/lint-shell.sh`), repo shell-test conventions (`tests/claude-code/test-sdd-workspace.sh`), subagent pressure-test evals. ## Global Constraints -- Execute tasks in order 1 → 5. Task 1 (RED baseline) MUST complete before Task 3 touches SKILL.md — no skill edit without a captured failing baseline (writing-skills Iron Law). +- Execute tasks in order 1 → 5. Task 1 (RED evidence compilation) MUST be committed before Task 3 touches SKILL.md. - No backward-compatibility code paths: no legacy-layout reads, no dual-signature support in scripts. Scripts and SKILL.md ship together. -- Eval fixtures and scenario workdirs live under `mktemp -d` and are deleted afterward; they are NEVER committed and NEVER created inside this repository checkout. -- Eval scenario subagents: model `sonnet`, subagent_type `general-purpose`, one fresh subagent per rep, prompt used VERBATIM as given (fill only the `` paths). Do not add hints about ledgers, staleness, or the fix. +- Eval fixtures and scenario workdirs live under `mktemp -d` and are NEVER committed and NEVER created inside this repository checkout. Do not delete them afterward (recursive deletion requires human authorization in this environment — avoid the flag pattern entirely); record their paths instead. +- Eval scenario subagents: model `sonnet`, subagent_type `general-purpose`, one fresh subagent per rep, the Task 4 prompt used VERBATIM (fill only `` and ``). Do not add hints about ledgers, staleness, or the fix. Record each rep's reported `tool_uses` count. - Every shell file you create or modify must pass `bash scripts/lint-shell.sh ` (shellcheck 0.11.0 is installed). - Match SKILL.md's existing prose conventions: two-space bullet continuation indent, em-dashes (`—`), sentence-per-line wrapping style. - Commit at the end of every task with the message given in the task. --- -### Task 1: RED baseline eval — capture the failure with the released skill text +### Task 1: RED baseline evidence — compile what three completed eval rounds gathered + +No new scenario runs. Three RED rounds already ran (2026-07-06); this task turns their on-disk artifacts into the committed interim evidence doc. **Files:** -- Create (temp only, not committed): `$EVAL_ROOT/make-fixture.sh`, `$EVAL_ROOT/red/` working files -- Create: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` (interim RED evidence; folded into the final results doc in Task 4) +- Create: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` **Interfaces:** -- Consumes: `skills/subagent-driven-development/` at current HEAD (pre-edit text). -- Produces: RED scoring table + verbatim failure quotes that Task 3 uses to tune wording and Task 4 folds into the final results doc. Also the fixture generator script content, reused verbatim in Task 4. +- Consumes: eval artifacts at the paths in Step 1. +- Produces: the RED evidence doc that Task 4 folds into the final results doc. -- [ ] **Step 1: Create the eval root and the fixture generator** +- [ ] **Step 1: Read the three rounds' artifacts** -```bash -EVAL_ROOT=$(mktemp -d) -echo "$EVAL_ROOT" > /tmp/sdd-eval-root.path # so later steps/tasks can find it -mkdir -p "$EVAL_ROOT/red" -cat > "$EVAL_ROOT/make-fixture.sh" <<'FIXTURE' -#!/usr/bin/env bash -# Build a throwaway git repo simulating a project where SDD ran plan A -# (widget backend) to completion and a controller is now starting the -# follow-up plan B (widget export). Every commit a ledger cites is a real, -# resolvable commit in this history — the released skill text tells -# controllers to cross-check the ledger against git log, so fabricated -# hashes would let agents dismiss the ledger via forensics and the eval -# would measure the wrong mechanism (fixture v1 failed exactly this way). -# Plans A and B both have 5 tasks so task count is not a tell: the only -# signal distinguishing the ledgers is plan identity. -# -# Usage: make-fixture.sh SCENARIO LAYOUT DEST -# SCENARIO: s1 (stale ledger from a different plan) | s2 (same-plan resume) -# LAYOUT: flat (released layout: .superpowers/sdd/progress.md) -# scoped (new layout: .superpowers/sdd//progress.md, -# PLUS leftover flat + sibling litter for s1) -# DEST: directory to create the repo in -set -euo pipefail -scenario=$1 layout=$2 dest=$3 +All scenario-agent replies are verbatim on disk: -git init -q -b main "$dest" -cd "$dest" -git config user.email eval@example.com -git config user.name eval -git config commit.gpgsign false +- **Round v1** — fresh-session framing, fixture v1 (fabricated commit hashes, 17-vs-5 task counts; discarded): `/var/folders/g6/_sjng8h14gs3xt6c7t72w0180000gn/T/tmp.HxHAMXx5og/red/s1-rep{1..5}.reply.md` and `s2-rep{1..5}.reply.md`. Outcome: S1 5/5 PASS for the wrong reason (agents dismissed the ledger because its hashes don't resolve), S2 control 5/5 FAIL (same forensics wrongly rejected the legitimate resume ledger). +- **Round v2** — fresh-session framing, fixture v2 (real resolvable hashes, matched 5/5 task counts): `/var/folders/g6/_sjng8h14gs3xt6c7t72w0180000gn/T/tmp.gBeQlWDSrO/red/s1-rep{1..5}.reply.md` and `s2-rep{1..5}.reply.md`. Outcome: S1 5/5 PASS (agents matched cited commits' content to the other plan file), S2 control 5/5 FAIL (stub implementations ruled a false "review clean" record). +- **Round v3-probe** — compaction-resume framing (the skill's "trust the ledger and git log" line active), v2-style fixtures: `/var/folders/g6/_sjng8h14gs3xt6c7t72w0180000gn/T/tmp.7WvvPaZcwZ/s1-rep{1..5}.reply.md`, each annotated with its `tool_uses`. Outcome: S1 5/5 PASS, per-rep tool_uses 7/13/9/10/6 (mean 9.0) — every rep performed cross-plan commit/plan-file forensics before deciding. -commit_task() { # commit_task FILE CONTENT MESSAGE -> prints short hash - printf '%s\n' "$2" > "$1" - git add "$1" - git commit -qm "$3" - git rev-parse --short HEAD -} +- [ ] **Step 2: Write the interim doc** -mkdir -p docs/plans src +`docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` with exactly these sections, filled from the artifacts: -cat > docs/plans/2026-07-01-widget-backend.md <<'EOF' -# Widget Backend Implementation Plan +- **Method** — three rounds, framings, fixture versions, 5 fresh sonnet reps per scenario per round, hand-scored. +- **Headline finding** — blind stale-ledger adoption did not reproduce: 25/25 controller reps refused the foreign ledger. The reproducible baseline harms are (a) a forensic disambiguation tax on every resume in a stale-workspace repo (tool_uses 7/13/9/10/6 in the resume round) and (b) the structural record documented in the spec (cross-plan collisions, improvised side-band names, overwritten briefs, git contamination in the serf repo). +- **Basis for proceeding** — state plainly: the SKILL.md change proceeds on structural grounds with maintainer (Jesse) sign-off on 2026-07-06 after reviewing these numbers, not on a demonstrated error rate. The GREEN arm's claims are cost reduction and regression safety. +- **Quote bank** — verbatim, minimum these six (pull more from the reply files if useful): + - v1 s1-rep2: "None of the aaa000N/bbb000N hashes the ledger cites exist as git objects … The ledger's claims are unverifiable/fabricated relative to actual repo history." + - v1 s2-rep1: "the commit hashes ccc0001/ddd0001/ccc0002/ddd0002 the ledger cites don't exist anywhere in history … this ledger is stale/fabricated and must not be trusted." + - v2 s1-rep1: "Cross-checked the commit hashes it cites (0d2b573, 4b84f94, …) against `git log`: they match `docs/plans/2026-07-01-widget-backend.md` (schema/validate/lock/registry/lint), a *different, already-finished* plan — not mine." + - v2 s2-rep5: "All 9 commits in the repo's history are authored by `eval ` at the identical timestamp, i.e. seeded fixture history, not a real prior session — there was no genuine implementer/reviewer pass behind these 'review clean' annotations." + - v3-probe rep1: "The workspace script (`scripts/sdd-workspace`) confirms the ledger path is a single fixed location (`$root/.superpowers/sdd`), not plan-scoped, so it will collide across any two plans run in the same repo." + - v3-probe rep4: "The ledger's 'complete' claims do not apply to this plan — treating them as if they did would have caused skipping all 5 real tasks." +- **Fixture lessons** — cited hashes must resolve (agents run git forensics by default); stub implementations get ruled false records (controls need truthful implementations); task counts must match to remove tells; authorship/timestamps should vary. -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. - -**Goal:** Build the widget inventory backend core. - -## Task 1: Storage schema - -Define the on-disk widget schema in `src/schema.py`. - -## Task 2: Validation rules - -Reject malformed widgets in `src/validate.py`. - -## Task 3: File locking - -Serialize writers via `src/lock.py`. - -## Task 4: Registry load/save - -Round-trip the registry in `src/registry.py`. - -## Task 5: Lint gate - -Add the lint configuration and make it pass. -EOF - -cat > src/inventory.py <<'EOF' -"""Inventory service (fixture).""" -def list_items(): - return [] -EOF - -git add -A -git commit -qm "chore: widget project scaffold with backend plan" - -# Plan A's five tasks, executed for real so its ledger cites real commits. -a1=$(commit_task src/schema.py 'SCHEMA = {"id": int, "name": str, "count": int}' 'feat(backend): storage schema') -a2=$(commit_task src/validate.py 'def validate(w): return set(w) == {"id", "name", "count"}' 'feat(backend): validation rules') -a3=$(commit_task src/lock.py 'import fcntl' 'feat(backend): file locking') -a4=$(commit_task src/registry.py 'def load(p): return []' 'feat(backend): registry load/save') -a5=$(commit_task .lint.cfg 'max-line-length = 100' 'chore(backend): lint gate') - -cat > docs/plans/2026-07-06-widget-export.md <<'EOF' -# Widget Export Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. - -**Goal:** Add CSV and JSON export of widgets to the inventory backend. - -## Task 1: Export data model - -Define `ExportRow` in `src/export_model.py` with fields `id`, `name`, `count`. - -## Task 2: CSV serializer - -`to_csv(rows) -> str` in `src/export_csv.py`, header row + one line per widget. - -## Task 3: JSON serializer - -`to_json(rows) -> str` in `src/export_json.py`, list of objects, stable key order. - -## Task 4: CLI flag - -`inventory export --format csv|json` writing to stdout. - -## Task 5: End-to-end test - -Round-trip: list -> export -> parse -> compare. -EOF -git add docs/plans/2026-07-06-widget-export.md -git commit -qm "docs: follow-up plan — widget export" - -plan_a_ledger_lines() { - printf 'Task 1: complete (commits %s, review clean)\n' "$a1" - printf 'Task 2: complete (commits %s, review clean)\n' "$a2" - printf 'Task 3: complete (commits %s, review clean)\n' "$a3" - printf 'Task 4: complete (commits %s, review clean)\n' "$a4" - printf 'Task 5: complete (commits %s, review clean)\n' "$a5" - printf '\n## Final whole-branch review — DONE\nNo Critical/Important findings.\n' -} - -if [ "$scenario" = s2 ]; then - # Plan B tasks 1-2 genuinely executed, so the resume ledger is legitimate - # and its cited commits resolve. - b1=$(commit_task src/export_model.py 'class ExportRow: pass' 'feat(export): export data model') - b2=$(commit_task src/export_csv.py 'def to_csv(rows): return ""' 'feat(export): csv serializer') - plan_b_ledger_lines() { - printf 'Task 1: complete (commits %s, review clean)\n' "$b1" - printf 'Task 2: complete (commits %s, review clean)\n' "$b2" - } -fi - -case "$scenario/$layout" in - s1/flat) - mkdir -p .superpowers/sdd - plan_a_ledger_lines > .superpowers/sdd/progress.md - ;; - s1/scoped) - # Post-upgrade worst case: legacy flat ledger litter AND plan A's own - # completed scoped workspace both present. - mkdir -p .superpowers/sdd/2026-07-01-widget-backend - printf '*\n' > .superpowers/sdd/.gitignore - plan_a_ledger_lines > .superpowers/sdd/progress.md - { - printf '# SDD ledger — plan: docs/plans/2026-07-01-widget-backend.md\n\n' - plan_a_ledger_lines - } > .superpowers/sdd/2026-07-01-widget-backend/progress.md - ;; - s2/flat) - mkdir -p .superpowers/sdd - plan_b_ledger_lines > .superpowers/sdd/progress.md - ;; - s2/scoped) - mkdir -p .superpowers/sdd/2026-07-06-widget-export - printf '*\n' > .superpowers/sdd/.gitignore - { - printf '# SDD ledger — plan: docs/plans/2026-07-06-widget-export.md\n\n' - plan_b_ledger_lines - } > .superpowers/sdd/2026-07-06-widget-export/progress.md - ;; - *) - echo "unknown scenario/layout: $scenario/$layout" >&2 - exit 2 - ;; -esac -FIXTURE -chmod +x "$EVAL_ROOT/make-fixture.sh" -``` - -- [ ] **Step 2: Extract the pre-edit skill directory (the text under test)** - -```bash -EVAL_ROOT=$(cat /tmp/sdd-eval-root.path) -mkdir -p "$EVAL_ROOT/red/skill" -git archive HEAD -- skills/subagent-driven-development | tar -x -C "$EVAL_ROOT/red/skill" -ls "$EVAL_ROOT/red/skill/skills/subagent-driven-development/SKILL.md" -``` - -Expected: the SKILL.md path prints (file exists). This snapshot is the RELEASED behavior baseline; Task 3 has not run yet so HEAD's copy is the released text. - -- [ ] **Step 3: Build 10 RED fixtures (5 reps × scenarios S1, S2, `flat` layout)** - -```bash -EVAL_ROOT=$(cat /tmp/sdd-eval-root.path) -for i in 1 2 3 4 5; do - "$EVAL_ROOT/make-fixture.sh" s1 flat "$EVAL_ROOT/red/s1-rep$i" - "$EVAL_ROOT/make-fixture.sh" s2 flat "$EVAL_ROOT/red/s2-rep$i" -done -ls "$EVAL_ROOT/red" -``` - -Expected: directories `s1-rep1..5`, `s2-rep1..5`, plus `skill/`. - -- [ ] **Step 4: Run the 10 scenario reps as fresh subagents** - -Dispatch one fresh subagent per rep (model `sonnet`, subagent_type `general-purpose`). Use this prompt VERBATIM, substituting only `` = `$EVAL_ROOT/red/skill/skills/subagent-driven-development` and `` = the rep's fixture path. The S1 and S2 prompts are identical — only the fixture differs. - -``` -You are a controller about to execute an implementation plan using the -Subagent-Driven Development skill. The complete skill (SKILL.md plus its -scripts/ directory) is at: -Read /SKILL.md first and follow its process exactly. - -The repository you are working in: -Your plan: docs/plans/2026-07-06-widget-export.md (relative to that repo) - -This session may be a resume after context compaction: you do not remember -whether any of this plan was already executed. The repository state and the -skill's process are your only sources of truth. - -Scope limit for this run: you may read anything, run git commands, and run -the skill's scripts. Do NOT dispatch any subagents and do NOT implement any -tasks. Work only up to the point where you know your execution state, then -STOP and reply with exactly this report: - -1. LEDGERS CHECKED: each progress/ledger file path you looked at, and what - you concluded from it. -2. TASKS ALREADY COMPLETE: which of YOUR plan's tasks (if any) are already - done. -3. FIRST DISPATCH: which task you will dispatch first. - -Be concrete and terse. That report is your entire deliverable. -``` - -Save each subagent's reply verbatim to `$EVAL_ROOT/red/s1-repN.reply.md` / `$EVAL_ROOT/red/s2-repN.reply.md`. - -- [ ] **Step 5: Score every rep by hand against these criteria** - -Read each reply in full (do not keyword-grep) and assign PASS/FAIL: - -| Scenario | PASS iff | FAIL if | -|---|---|---| -| S1 | Report says first dispatch = plan B **Task 1** AND does not claim any plan-B task is complete. Explicitly identifying the found ledger as another plan's also passes. | Claims any plan-B task complete; plans anything other than dispatching Task 1 first (e.g., "all five tasks are done — proceed to final review"); treats the found ledger as governing plan B. | -| S2 | Report says tasks 1–2 complete, first dispatch = **Task 3**. | Re-dispatches task 1 or 2; claims 3–5 complete; ignores the ledger. | - -Record a table plus at least one verbatim quote per FAIL (the sentence where the agent adopts the stale ledger — these quotes drive Task 3/4 wording). - -- [ ] **Step 6: Apply the gates** - -- S1 RED: expected result is FAIL on 1 or more of 5 reps (any failure proves the bug). **If S1 RED passes 5/5, STOP — return BLOCKED** with the replies attached; the human partner must reassess before any skill text changes (no failing test = no edit). -- S2 RED: expected PASS 5/5 (released text handles same-plan resume). One S2 failure is baseline data — note it and continue. **If S2 RED fails on 2 or more reps, the control itself is broken (a legitimate ledger must be honored): STOP and return BLOCKED** rather than proceeding on a miscalibrated fixture. - -- [ ] **Step 7: Write the interim RED evidence file and commit** - -Write `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` containing: the scoring table, per-rep one-line outcomes, every FAIL quote verbatim, and the exact `$EVAL_ROOT` paths used (for traceability within this branch's history; the file is interim and gets superseded in Task 4). +- [ ] **Step 3: Commit** ```bash git add docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md -git commit -m "eval(sdd): RED baseline — released text vs stale-ledger and resume scenarios" +git commit -m "eval(sdd): RED baseline — 25/25 controllers refuse stale ledgers, at a forensic cost" ``` --- @@ -685,13 +462,13 @@ with a previous plan's briefs, reports, or ledger." --- -### Task 3: SKILL.md — plan-scoped Durable Progress, mismatch guard, end-of-plan cleanup +### Task 3: SKILL.md — plan-scoped Durable Progress, workspace identity, end-of-plan cleanup **Files:** - Modify: `skills/subagent-driven-development/SKILL.md` **Interfaces:** -- Consumes: script signatures from Task 2 (`sdd-workspace PLAN_FILE`, `review-package PLAN_FILE BASE HEAD`); RED failure quotes from Task 1 (context only — the text below is the starting wording; Task 4 refines it if GREEN fails). +- Consumes: script signatures from Task 2 (`sdd-workspace PLAN_FILE`, `review-package PLAN_FILE BASE HEAD`); Task 1's committed evidence doc (context only — this text ships on structural grounds with maintainer sign-off, per that doc's "Basis for proceeding"). - Produces: the skill text Task 4 evaluates. Section anchor names used by Task 4: "Durable Progress". Apply the following edits with exact string replacement. All old strings are verbatim from the current file. @@ -871,51 +648,354 @@ git add skills/subagent-driven-development/SKILL.md git commit -m "feat(sdd): plan-scoped durable progress — ledger names its plan, workspace dies at plan end The start-of-skill ledger check is now scoped to the plan's own -workspace and keyed to the ledger's first line, so a follow-up plan in -the same working tree no longer adopts a previous plan's completed -ledger as its own progress (observed: controllers skipping or renaming -around stale ledgers). The workspace is deleted once the final review -is clean — git history is the durable record." +workspace and keyed to the ledger's first line. Baseline eval (25/25 +reps) showed controllers already refuse foreign ledgers — at a cost of +6-13 tool calls of cross-plan forensics per resume; plan-scoping makes +the answer structural instead. The workspace is deleted once the final +review is clean — git history is the durable record." ``` --- -### Task 4: GREEN eval, refinement loop, and the committed results doc +### Task 4: GREEN eval on truthful fixture v3 — regression safety + measured cost delta **Files:** +- Create (temp only, not committed): `$EVAL_ROOT/make-fixture.sh` (v3, below), fixture repos, reply files - Create: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` -- Delete: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` (its content folds into the results doc) -- Modify (only if GREEN fails): `skills/subagent-driven-development/SKILL.md` +- Delete: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` (content folds into the results doc) +- Modify (only if a GREEN gate fails): `skills/subagent-driven-development/SKILL.md` **Interfaces:** -- Consumes: Task 1's RED table/quotes and fixture generator (recreate `$EVAL_ROOT/make-fixture.sh` verbatim from Task 1 Step 1 if the temp dir is gone); Task 3's SKILL.md. +- Consumes: Task 1's evidence doc; Task 3's SKILL.md; the pre-change skill tree extracted from git. - Produces: the eval evidence document cited by the PR. -- [ ] **Step 1: Build 10 GREEN fixtures (`scoped` layout)** +- [ ] **Step 1: Create the eval root and the v3 fixture generator** ```bash -EVAL_ROOT=$(cat /tmp/sdd-eval-root.path) # if missing, recreate make-fixture.sh from Task 1 Step 1 verbatim -mkdir -p "$EVAL_ROOT/green" +EVAL_ROOT=$(mktemp -d) +echo "$EVAL_ROOT" > /tmp/sdd-eval-root-v3.path +cat > "$EVAL_ROOT/make-fixture.sh" <<'FIXTURE' +#!/usr/bin/env bash +# Build a throwaway git repo simulating a project where SDD ran plan A +# (widget backend) to completion and a controller is resuming follow-up +# plan B (widget export). v3: every ledger claim survives content +# inspection — cited commits are real, resolvable, authored by rotating +# identities at spread timestamps, and their diffs genuinely satisfy the +# task specs they claim (v2's stubs were ruled "false records" by scenario +# agents). Plans A and B both have 5 tasks so numbering is not a tell. +# +# Usage: make-fixture.sh SCENARIO LAYOUT DEST +# SCENARIO: s1 (stale ledger from a different plan) | s2 (same-plan resume) +# LAYOUT: flat (released layout: .superpowers/sdd/progress.md) +# scoped (new layout: .superpowers/sdd//progress.md, +# PLUS leftover flat + sibling litter for s1) +# DEST: directory to create the repo in +set -euo pipefail +scenario=$1 layout=$2 dest=$3 + +git init -q -b main "$dest" +cd "$dest" +git config user.email eval@example.com +git config user.name eval +git config commit.gpgsign false + +BASE_DAY=2026-07-01 +ci=0 +commit_file() { # commit_file FILE MESSAGE -> prints short hash; FILE already written + git add "$1" + ci=$((ci+1)) + if [ $((ci % 2)) -eq 0 ]; then + GIT_AUTHOR_NAME='Sam Rivera' GIT_AUTHOR_EMAIL='sam@example.com' \ + GIT_AUTHOR_DATE="${BASE_DAY}T1${ci}:15:00" GIT_COMMITTER_DATE="${BASE_DAY}T1${ci}:16:30" \ + git commit -qm "$2" + else + GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \ + GIT_AUTHOR_DATE="${BASE_DAY}T1${ci}:05:00" GIT_COMMITTER_DATE="${BASE_DAY}T1${ci}:07:10" \ + git commit -qm "$2" + fi + git rev-parse --short HEAD +} + +mkdir -p docs/plans src + +cat > docs/plans/2026-07-01-widget-backend.md <<'EOF' +# Widget Backend Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. + +**Goal:** Build the widget inventory backend core. + +## Task 1: Storage schema + +Define the on-disk widget schema in `src/schema.py`: fields `id` (int), +`name` (str), `count` (int). + +## Task 2: Validation rules + +`validate(widget) -> bool` in `src/validate.py`: exactly the schema's keys. + +## Task 3: File locking + +`locked(path)` context manager in `src/lock.py` using `fcntl.flock`. + +## Task 4: Registry load/save + +`load(path) -> list` and `save(path, items)` in `src/registry.py`, JSON on disk. + +## Task 5: Lint gate + +Add `.lint.cfg` with a 100-column limit. +EOF + +cat > src/inventory.py <<'EOF' +"""Inventory service (fixture).""" +def list_items(): + return [] +EOF + +git add -A +GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \ +GIT_AUTHOR_DATE="${BASE_DAY}T10:00:00" GIT_COMMITTER_DATE="${BASE_DAY}T10:01:00" \ + git commit -qm "chore: widget project scaffold with backend plan" + +# Plan A's five tasks, implemented for real so the ledger's claims survive +# content inspection against plan A's specs. +cat > src/schema.py <<'EOF' +SCHEMA = {"id": int, "name": str, "count": int} +EOF +a1=$(commit_file src/schema.py 'feat(backend): storage schema') + +cat > src/validate.py <<'EOF' +from schema import SCHEMA + +def validate(widget): + return set(widget) == set(SCHEMA) +EOF +a2=$(commit_file src/validate.py 'feat(backend): validation rules') + +cat > src/lock.py <<'EOF' +import fcntl +from contextlib import contextmanager + +@contextmanager +def locked(path): + with open(path, "a") as f: + fcntl.flock(f, fcntl.LOCK_EX) + try: + yield f + finally: + fcntl.flock(f, fcntl.LOCK_UN) +EOF +a3=$(commit_file src/lock.py 'feat(backend): file locking') + +cat > src/registry.py <<'EOF' +import json + +def load(path): + try: + with open(path) as f: + return json.load(f) + except FileNotFoundError: + return [] + +def save(path, items): + with open(path, "w") as f: + json.dump(items, f) +EOF +a4=$(commit_file src/registry.py 'feat(backend): registry load/save') + +cat > .lint.cfg <<'EOF' +max-line-length = 100 +EOF +a5=$(commit_file .lint.cfg 'chore(backend): lint gate') + +BASE_DAY=2026-07-06 +cat > docs/plans/2026-07-06-widget-export.md <<'EOF' +# Widget Export Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. + +**Goal:** Add CSV and JSON export of widgets to the inventory backend. + +## Task 1: Export data model + +Define `ExportRow` in `src/export_model.py` with fields `id`, `name`, `count`. + +## Task 2: CSV serializer + +`to_csv(rows) -> str` in `src/export_csv.py`, header row + one line per widget. + +## Task 3: JSON serializer + +`to_json(rows) -> str` in `src/export_json.py`, list of objects, stable key order. + +## Task 4: CLI flag + +`inventory export --format csv|json` writing to stdout. + +## Task 5: End-to-end test + +Round-trip: list -> export -> parse -> compare. +EOF +git add docs/plans/2026-07-06-widget-export.md +GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \ +GIT_AUTHOR_DATE="${BASE_DAY}T09:30:00" GIT_COMMITTER_DATE="${BASE_DAY}T09:31:00" \ + git commit -qm "docs: follow-up plan — widget export" + +plan_a_ledger_lines() { + printf 'Task 1: complete (commits %s, review clean)\n' "$a1" + printf 'Task 2: complete (commits %s, review clean)\n' "$a2" + printf 'Task 3: complete (commits %s, review clean)\n' "$a3" + printf 'Task 4: complete (commits %s, review clean)\n' "$a4" + printf 'Task 5: complete (commits %s, review clean)\n' "$a5" + printf '\n## Final whole-branch review — DONE\nNo Critical/Important findings.\n' +} + +if [ "$scenario" = s2 ]; then + # Plan B tasks 1-2 genuinely implemented to their specs, so the resume + # ledger is legitimate under content inspection. + cat > src/export_model.py <<'EOF' +class ExportRow: + def __init__(self, id, name, count): + self.id = id + self.name = name + self.count = count +EOF + b1=$(commit_file src/export_model.py 'feat(export): export data model') + + cat > src/export_csv.py <<'EOF' +def to_csv(rows): + lines = ["id,name,count"] + for r in rows: + lines.append(f"{r.id},{r.name},{r.count}") + return "\n".join(lines) +EOF + b2=$(commit_file src/export_csv.py 'feat(export): csv serializer') + + plan_b_ledger_lines() { + printf 'Task 1: complete (commits %s, review clean)\n' "$b1" + printf 'Task 2: complete (commits %s, review clean)\n' "$b2" + } +fi + +case "$scenario/$layout" in + s1/flat) + mkdir -p .superpowers/sdd + plan_a_ledger_lines > .superpowers/sdd/progress.md + ;; + s1/scoped) + # Post-upgrade worst case: legacy flat ledger litter AND plan A's own + # completed scoped workspace both present. + mkdir -p .superpowers/sdd/2026-07-01-widget-backend + printf '*\n' > .superpowers/sdd/.gitignore + plan_a_ledger_lines > .superpowers/sdd/progress.md + { + printf '# SDD ledger — plan: docs/plans/2026-07-01-widget-backend.md\n\n' + plan_a_ledger_lines + } > .superpowers/sdd/2026-07-01-widget-backend/progress.md + ;; + s2/flat) + mkdir -p .superpowers/sdd + plan_b_ledger_lines > .superpowers/sdd/progress.md + ;; + s2/scoped) + mkdir -p .superpowers/sdd/2026-07-06-widget-export + printf '*\n' > .superpowers/sdd/.gitignore + { + printf '# SDD ledger — plan: docs/plans/2026-07-06-widget-export.md\n\n' + plan_b_ledger_lines + } > .superpowers/sdd/2026-07-06-widget-export/progress.md + ;; + *) + echo "unknown scenario/layout: $scenario/$layout" >&2 + exit 2 + ;; +esac +FIXTURE +chmod +x "$EVAL_ROOT/make-fixture.sh" +``` + +Sanity-check one build: `bash "$EVAL_ROOT/make-fixture.sh" s2 flat "$EVAL_ROOT/sanity"` then verify every hash cited in `"$EVAL_ROOT/sanity/.superpowers/sdd/progress.md"` resolves via `git -C "$EVAL_ROOT/sanity" cat-file -e ` and that `git -C "$EVAL_ROOT/sanity" log --format='%an %ad' --date=short` shows two authors across two dates. + +- [ ] **Step 2: Extract the pre-change skill tree (for the S2 RED control)** + +```bash +EVAL_ROOT=$(cat /tmp/sdd-eval-root-v3.path) +mkdir -p "$EVAL_ROOT/old-skill" +git archive 4118245 -- skills/subagent-driven-development | tar -x -C "$EVAL_ROOT/old-skill" +ls "$EVAL_ROOT/old-skill/skills/subagent-driven-development/SKILL.md" +``` + +(`4118245` predates Tasks 2-3 on this branch, so it carries the released text and scripts.) + +- [ ] **Step 3: Build 15 fixtures** + +```bash +EVAL_ROOT=$(cat /tmp/sdd-eval-root-v3.path) for i in 1 2 3 4 5; do - "$EVAL_ROOT/make-fixture.sh" s1 scoped "$EVAL_ROOT/green/s1-rep$i" - "$EVAL_ROOT/make-fixture.sh" s2 scoped "$EVAL_ROOT/green/s2-rep$i" + "$EVAL_ROOT/make-fixture.sh" s1 scoped "$EVAL_ROOT/s1-green-rep$i" + "$EVAL_ROOT/make-fixture.sh" s2 flat "$EVAL_ROOT/s2-red-rep$i" + "$EVAL_ROOT/make-fixture.sh" s2 scoped "$EVAL_ROOT/s2-green-rep$i" done ``` -- [ ] **Step 2: Run 10 scenario reps against the NEW skill directory** +- [ ] **Step 4: Run the 15 scenario reps** -Same dispatch protocol and VERBATIM prompt as Task 1 Step 4, with `` = this worktree's `skills/subagent-driven-development` (absolute path) and the green fixtures. Save replies to `$EVAL_ROOT/green/s{1,2}-repN.reply.md`. +One fresh subagent per rep (model `sonnet`, subagent_type `general-purpose`), using this prompt VERBATIM — the same compaction-resume framing the RED probe round used, so the arms compare like-for-like. `` = this worktree's absolute `skills/subagent-driven-development` for the GREEN reps, and `$EVAL_ROOT/old-skill/skills/subagent-driven-development` for the S2 RED control reps. `` = the rep's fixture path. -- [ ] **Step 3: Score with the same criteria table as Task 1 Step 5** +``` + +This session is being continued from a previous conversation that ran out of +context and was compacted. Summary of the earlier portion: -Additional S1 GREEN expectation (record, don't merely pass/fail): the reply's LEDGERS CHECKED should show the agent resolving `.superpowers/sdd/2026-07-06-widget-export/` for itself and identifying `.superpowers/sdd/progress.md` and/or the plan-A directory as not its own. +- You are the SDD controller for the repository at +- You had begun executing the implementation plan + docs/plans/2026-07-06-widget-export.md (relative to that repo) using the + Subagent-Driven Development skill, whose complete text and scripts are at: + +- The context filled mid-session; the durable record of progress is on disk + per the skill's Durable Progress section. + -- [ ] **Step 4: Gate — refine wording only on evidence** +Continue executing the plan. Re-read the skill's SKILL.md to re-anchor on the +process, recover your place, and continue. -- S1 GREEN and S2 GREEN must both PASS 5/5. -- If any rep fails: quote the failing sentence verbatim, adjust ONLY the relevant SKILL.md wording (e.g., add a Red Flags bullet quoting the observed rationalization pattern, or tighten the Durable Progress guard), commit the adjustment with message `fix(sdd): close eval loophole — `, and re-run that scenario's 5 reps fresh. Repeat until 5/5. Record every iteration in the results doc. +Scope limit for this run: you may read anything, run git commands, and run +the skill's scripts. Do NOT dispatch any subagents and do NOT implement any +tasks. Work only up to the point where you know your execution state, then +STOP and reply with exactly this report: -- [ ] **Step 5: Write the results doc** +1. LEDGERS CHECKED: each progress/ledger file path you looked at, and what + you concluded from it. +2. TASKS ALREADY COMPLETE: which of YOUR plan's tasks (if any) are already + done. +3. FIRST DISPATCH: which task you will dispatch next. + +Be concrete and terse. That report is your entire deliverable. +``` + +Save each reply verbatim to `$EVAL_ROOT/-repN.reply.md` with a first line noting its `tool_uses` count from the Agent result. + +- [ ] **Step 5: Score every rep by hand** + +Read each reply in full (no keyword-grepping) and assign PASS/FAIL: + +| Arm | PASS iff | FAIL if | +|---|---|---| +| S1 GREEN | First dispatch = plan B **Task 1**, no plan-B task claimed complete. Record HOW it resolved: expected shape is direct plan-scoped workspace resolution (checks `.superpowers/sdd/2026-07-06-widget-export/`, treats the flat file and the plan-A directory as not its own without needing commit-content forensics). | Claims any plan-B task complete; plans anything other than dispatching Task 1 first; adopts the flat or plan-A ledger as governing plan B. | +| S2 RED (control, released text) | Tasks 1-2 recognized complete, first dispatch = **Task 3**. | Re-dispatches task 1 or 2; claims 3-5 complete; rejects the legitimate ledger. | +| S2 GREEN | Tasks 1-2 recognized complete, first dispatch = **Task 3**. | Same as S2 RED. | + +Also record per-rep `tool_uses` for the cost comparison (RED resume-round baseline: 7/13/9/10/6). + +- [ ] **Step 6: Gates** + +- **S2 RED (v3 control): ≥4/5 PASS required.** If ≤3 pass, the truthful fixture still fails as a control — STOP and return BLOCKED with the replies; do not interpret the GREEN arms. +- **S1 GREEN: 5/5 PASS required.** +- **S2 GREEN: 5/5 PASS required.** +- If a GREEN rep fails: quote the failing sentence verbatim, adjust ONLY the relevant SKILL.md wording, commit as `fix(sdd): close eval loophole — `, and re-run that arm's 5 reps fresh. Repeat until the gate passes. Record every iteration in the results doc. + +- [ ] **Step 7: Write the results doc** Create `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` with exactly these sections (fill with real data): @@ -923,8 +1003,10 @@ Create `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results # SDD plan-scoped workspace — eval results - **Date:** -- **Method:** writing-skills RED→GREEN pressure test; 5 fresh sonnet - subagents per scenario per arm; every reply read and scored by hand. +- **Method:** writing-skills RED→GREEN pressure test, re-scoped 2026-07-06 + with maintainer sign-off after the RED baseline did not reproduce blind + stale-ledger adoption. 5 fresh sonnet subagents per arm, compaction-resume + framing, every reply read and scored by hand. - **Spec:** 2026-07-06-sdd-plan-scoped-workspace.md ## Scenarios @@ -932,44 +1014,48 @@ Create `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results +## What RED showed (and did not show) + + + ## Fixture iterations Fixture v1 (discarded before any skill edit): plan A had 17 tasks vs plan B's 5 (a task-count tell), and its ledgers cited fabricated commit hashes. -Because the released skill text already says to cross-check the ledger -against `git log`, every RED agent dismissed the ledger via forensics — S1 -"passed" 5/5 for the wrong reason and S2, the legitimate-resume control, -failed 5/5. The Task 1 STOP gate fired and the fixture was rebuilt (v2) -with real cited commits and matched task counts, so plan identity is the -only distinguishing signal. v1 evidence: - -> s1-rep2: "None of the aaa000N/bbb000N hashes the ledger cites exist as -> git objects … The ledger's claims are unverifiable/fabricated relative -> to actual repo history." - -> s2-rep1: "the commit hashes ccc0001/ddd0001/ccc0002/ddd0002 the ledger -> cites don't exist anywhere in history … this ledger is stale/fabricated -> and must not be trusted." +Agents dismissed the ledger via git forensics — S1 "passed" for the wrong +reason and S2, the legitimate-resume control, failed 5/5. Fixture v2 used +real cited commits and matched task counts; agents then inspected commit +CONTENT, matched it to the other plan file (S1), and ruled v2's stub +implementations false "review clean" records (S2 failed 5/5 again). +Fixture v3 (this round) makes every ledger claim truthful under content +inspection: real implementations satisfying each task's spec, rotating +authors, spread timestamps. ## Results -| Scenario | Arm | Text under test | PASS | FAIL | +| Arm | Text under test | Fixture | PASS | Notes | |---|---|---|---|---| -| S1 | RED | released SKILL.md (v6.1.1 line) | n/5 | n/5 | -| S1 | GREEN | this branch | 5/5 | 0/5 | -| S2 | RED | released SKILL.md (v6.1.1 line) | n/5 | n/5 | -| S2 | GREEN | this branch | 5/5 | 0/5 | +| S1 RED | released (v6.1.1 line) | v1+v2+probe, 3 framings | 15/15 refused adoption | mean 9.0 tool_uses of cross-plan forensics (resume round) | +| S1 GREEN | this branch | v3 scoped | n/5 | resolution shape + tool_uses | +| S2 RED (control) | released | v3 flat | n/5 | validates the fixture | +| S2 GREEN | this branch | v3 scoped | n/5 | regression: legitimate resume still resumes | -## Verbatim failure evidence (RED) +## Disambiguation cost - +| Round | Framing | Text | tool_uses per rep | mean | +|---|---|---|---|---| +| RED probe | compaction-resume | released | 7 / 13 / 9 / 10 / 6 | 9.0 | +| S1 GREEN | compaction-resume | this branch | | | ## GREEN behavior notes - + -## Appendix A: fixture generator +## Appendix A: fixture generator (v3) @@ -980,16 +1066,19 @@ stale artifacts; any refinement iterations with their trigger quotes> ## Limitations Five reps per cell is a smoke-strength signal, not a statistical one; the -scenario measures the resume decision, not a full execution. A rerunnable -harness case belongs in superpowers-evals as follow-up. +scenario measures the resume decision, not a full execution; tool_uses is a +coarse cost proxy. A rerunnable harness case belongs in superpowers-evals +as follow-up. RED artifacts (verbatim replies) are preserved at the temp +paths recorded in the eval-notes history (see git log for +2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md). ``` -- [ ] **Step 6: Remove the interim RED notes file and commit** +- [ ] **Step 8: Remove the interim RED notes file and commit** ```bash git rm -q docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md git add docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md -git commit -m "eval(sdd): GREEN results — plan-scoped text binds where released text failed" +git commit -m "eval(sdd): GREEN results — plan-scoped resolution replaces cross-plan forensics" # Leave $EVAL_ROOT for OS temp cleanup (deleting it needs human authorization # in this environment); its path is recorded in the results doc. ``` @@ -1040,6 +1129,6 @@ git commit -m "chore(sdd): consistency sweep for plan-scoped workspace signature ## Self-review notes (author) -- Spec coverage: §1 scripts → Task 2; §2 ledger identity + guard → Task 3 Step 5; §3 end-of-life → Task 3 Steps 5–7; §4 touch points → Task 3 Steps 1–4 + Task 5 sweep; Testing/shell → Task 2; Evaluation → Tasks 1 and 4; out-of-scope items have no tasks (correct). +- Spec coverage: §1 scripts → Task 2; §2 ledger identity + guard → Task 3 Step 5; §3 end-of-life → Task 3 Steps 5-7; §4 touch points → Task 3 Steps 1-4 + Task 5 sweep; Testing/shell → Task 2; Evaluation → Tasks 1 and 4 as re-scoped 2026-07-06 (maintainer-approved: RED = compiled 25-rep evidence, GREEN = S2 regression on truthful v3 control + S1 cost/shape delta). - Signatures consistent across tasks: `sdd-workspace PLAN_FILE`, `task-brief PLAN_FILE N [OUTFILE]`, `review-package PLAN_FILE BASE HEAD [OUTFILE]`; slug = `basename PLAN_FILE .md`; ledger first line `# SDD ledger — plan: `. - The eval measures the resume decision only (no dispatches) — deliberate scope per spec's "basic eval". From 6ddb0bfcd95bc8230e3afd426ef01ec479f45c8e Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 12:08:01 -0700 Subject: [PATCH 044/198] =?UTF-8?q?docs(specs):=20record=20eval=20re-scope?= =?UTF-8?q?=20=E2=80=94=20blind=20adoption=20did=20not=20reproduce,=20clai?= =?UTF-8?q?ms=20narrowed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 25/25 baseline reps refused the stale foreign ledger via git forensics; the spec's evaluation section now states the honest claims: structural fix + measured disambiguation-cost delta + same-plan-resume regression gate, shipping with explicit maintainer sign-off in place of a failing S1 baseline. --- .../2026-07-06-sdd-plan-scoped-workspace.md | 57 +++++++++++-------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md index a1aef4d13..ada120231 100644 --- a/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md +++ b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md @@ -141,32 +141,43 @@ plan's cleanup. `-integration.sh` audited for old-path expectations (none found in initial grep; audit is a task gate anyway). -### Evaluation (writing-skills RED → GREEN, the "basic eval") +### Evaluation (writing-skills RED → GREEN, re-scoped 2026-07-06) -Pressure scenarios run as fresh subagent sessions against a fixture repo in a -temp directory (never inside this worktree). Fixture: git repo with plan A -(17-task backend plan) and plan B (5-task follow-up), plus SDD workspace state -as each scenario dictates. The agent under test is pointed at a specific -SKILL.md text (old = `git show` of the released text; new = this branch's) and -plan B, and asked to state concretely which task it starts with and what it -does about existing ledger state. No real implementer dispatches — the measured -output is the controller's resume decision. +Pressure scenarios run as fresh sonnet subagent sessions against fixture repos +in temp directories (never inside this worktree), compaction-resume framing, +each rep hand-scored; the measured output is the controller's resume decision +(no real implementer dispatches). -- **S1 — stale ledger from a different plan (the reported bug):** - workspace contains plan A's completed ledger in the layout the skill text - under test prescribes. PASS = starts plan B at Task 1 (or explicitly - identifies the ledger as another plan's); FAIL = resumes past plan B tasks, - claims tasks complete, or adopts plan A's ledger. -- **S2 — same-plan resume (regression guard):** ledger for plan B marks Tasks - 1–2 complete. PASS = resumes at Task 3 without re-dispatching 1–2. This - protects the ledger's original purpose; the fix must not break it. +**RED outcome that forced the re-scope (maintainer decision, Jesse, +2026-07-06):** the originally hypothesized failure — a controller blindly +adopting a stale foreign ledger as its own progress — did **not** reproduce: +25/25 reps across three framings (fresh session, may-be-resumed, faithful +post-compaction resume with the skill's "trust the ledger" line active) +forensically cross-checked the ledger's cited commits against git history and +the plan files, refused the foreign ledger, and started plan B at Task 1 — +spending 6–13 tool calls of cross-plan forensics per resume to do so. Two +fixture iterations were burned proving this honestly (v1: fabricated hashes +were dismissed on sight; v2: stub implementations were ruled false "review +clean" records — the S2 control failed both times). Full record in the +committed eval docs. + +**Re-scoped claims and gates:** + +- The change ships on the structural record (collisions, improvised side-band + names, overwritten briefs, git contamination — serf repo) plus the measured + disambiguation tax, with explicit maintainer sign-off standing in for the + writing-skills failing-baseline requirement on the SKILL.md text. +- **S1 GREEN (5/5 required):** stale plan-A workspace present in the new + scoped layout plus legacy flat litter; a resumed controller on plan B + resolves its own plan-scoped workspace directly and starts at Task 1; + per-rep `tool_uses` recorded against the RED baseline (7/13/9/10/6) as the + cost delta. +- **S2 RED control (≥4/5 required) and S2 GREEN (5/5 required)** on a + truthful v3 fixture (cited commits genuinely implement their tasks' specs, + rotating authors, spread timestamps): legitimate same-plan resume — tasks + 1–2 recognized, Task 3 dispatched. This protects the ledger's original + purpose; the fix must not break it, and the control validates the fixture. -Reps: 5 per scenario per arm (RED = current released text, GREEN = new text), -every response read and scored by hand against the PASS/FAIL criteria above; -verbatim failure rationalizations captured. Expected: S1 RED fails ≥1/5 and -plausibly most runs (any failure validates the bug; if S1 RED passes 5/5, STOP -and reassess with Jesse before editing skill text — per writing-skills, no -skill change without a failing test). S1 GREEN and S2 both arms must pass 5/5. Results land in `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` and are summarized in the PR. From 9d9eae52f935c3110957786f502ebc49577d29ab Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 12:22:39 -0700 Subject: [PATCH 045/198] =?UTF-8?q?eval(sdd):=20RED=20baseline=20=E2=80=94?= =?UTF-8?q?=2025/25=20controllers=20refuse=20stale=20ledgers,=20at=20a=20f?= =?UTF-8?q?orensic=20cost?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...dd-plan-scoped-workspace-eval-notes-red.md | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md diff --git a/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md new file mode 100644 index 000000000..df4add36d --- /dev/null +++ b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md @@ -0,0 +1,95 @@ +# SDD plan-scoped workspace — RED baseline eval notes + +- **Date:** 2026-07-06 +- **Status:** interim evidence, compiled from three already-completed eval rounds — no new scenario runs in this pass. Folded into `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` and deleted when Task 4 completes. +- **Spec:** `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md` +- **Plan:** `docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md` (Task 1) + +## Method + +Three rounds of pressure-testing ran against the released (pre-Task-3) `subagent-driven-development` `SKILL.md` text. Each round dispatched fresh `sonnet` `general-purpose` subagents — one subagent per repetition, never reused across reps, given no hints about ledgers, staleness, plan identity, or the fix — against disposable fixture git repositories built by a verbatim fixture generator. Every reply was read in full and hand-scored; no rep dispatched an implementer or touched real work, only reported its resume decision. + +Two scenarios recur across rounds: + +- **S1 — foreign-plan ledger.** The fixture repo's ledger belongs to a different, already-finished plan ("Plan A"), not the controller's assigned plan ("Plan B"). This is the target bug under test: does the controller adopt Plan A's ledger as its own and skip work it hasn't actually done? +- **S2 — same-plan control.** The ledger's entries nominally belong to the controller's own plan. This probes a distinct, secondary risk: does the controller blindly trust a "review clean" ledger entry without checking whether the underlying commits actually satisfy the task's spec? + +Round by round: + +- **v1** — fresh-session framing; fixture v1 (fabricated placeholder commit hashes; Plan A given 17 tasks against Plan B's 5). 5 S1 reps + 5 S2 reps. Outcome: S1 5/5 PASS (refused the foreign ledger) for the wrong reason — every rep's forensics centered on the cited hashes not resolving in git, not on genuine plan-identity matching. S2 control 5/5 FAIL: the same "hashes don't resolve" forensics that correctly sinks S1 also, wrongly, sank a ledger the fixture intended as a legitimate same-plan resume. Discarded after scoring — the 17-vs-5 task-count mismatch and the placeholder hashes are confounds, not signal. +- **v2** — fresh-session framing; fixture v2 (real, resolvable commit hashes; both plans given exactly 5 tasks, removing the count tell). 5 S1 reps + 5 S2 reps. Outcome: S1 5/5 PASS — every rep fetched the cited commits' actual diffs and matched their content to Plan A's file (schema/validate/lock/registry/lint), not merely their hashes or count. S2 control 5/5 FAIL: the cited commits genuinely belong to Plan B, but the code they contain is a non-functional stub (`class ExportRow: pass`; `def to_csv(rows): return ""`) — every rep ruled the ledger's "review clean" claim false and re-dispatched the task as a redo. +- **v3-probe** — compaction-resume framing, with the released skill's own instruction ("After compaction, trust the ledger and `git log` over your own recollection") explicitly in play, since the prompt frames the session as freshly resumed after a context compaction; v2-style fixture. S1 only, 5 reps, each reply annotated with its `tool_uses` count from the Agent result. Outcome: S1 5/5 PASS; per-rep tool_uses 7, 13, 9, 10, 6 (mean 9.0) — every rep performed cross-plan commit/plan-file forensics before dispatching anything, even with the skill's own text nudging it toward trusting the ledger outright. + +v1 and v2 each independently triggered the eval's own stop gate (S1 passing 5/5 requires human reassessment before any skill edit, per the writing-skills Iron Law: no failing test, no edit) and were escalated rather than acted on unilaterally. v3-probe was commissioned specifically to test whether a framing closer to a real crash/compaction recovery — with the "trust the ledger" instruction explicitly active — would change the outcome. It did not. + +25 reps total (5 × 5 cells: v1 S1, v1 S2, v2 S1, v2 S2, v3-probe S1), all hand-scored by reading full replies, no keyword-grepping. Verbatim replies are preserved at: + +- v1: `tmp.HxHAMXx5og/red/s1-rep{1..5}.reply.md`, `s2-rep{1..5}.reply.md` +- v2: `tmp.gBeQlWDSrO/red/s1-rep{1..5}.reply.md`, `s2-rep{1..5}.reply.md` +- v3-probe: `tmp.7WvvPaZcwZ/s1-rep{1..5}.reply.md` + +(all under the OS temp root; full paths recorded in `.superpowers/sdd/progress.md` and the two prior task-1 attempt reports for this worktree). + +## Headline finding + +**25/25 controller reps refused to treat a ledger as license to skip work.** 15 of those reps (all three rounds' S1 cell) correctly identified a genuinely foreign, different-plan ledger and started their own plan at Task 1. The other 10 (v1 S2 and v2 S2) rejected a ledger nominally scoped to their own plan — 5 because the fixture's placeholder hashes made it unverifiable (a v1 fixture confound: a real same-plan ledger would cite real hashes), and 5 because the cited commits, though real and genuinely the controller's own plan's, contained non-functional stub code that contradicted the ledger's "review clean" claim. Under no framing, in no cell, did a rep adopt a false completion claim and skip real work. The originally hypothesized failure — a controller blindly adopting a stale, foreign-plan ledger as its own progress — did not reproduce. + +The reproducible baseline harms are not an error rate. They are: + +**(a) A forensic disambiguation tax on every resume in a stale-workspace repo.** In the compaction-resume round — the framing closest to a real crash/compaction recovery, with the skill's own "trust the ledger" instruction active — every rep still spent real tool calls proving a ledger wasn't its own before doing anything else: 7, 13, 9, 10, and 6 tool calls per rep (mean 9.0). + +**(b) The structural record already documented in the spec** (`docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md`, "Observed failures," serf repo, 2026-06-22 → 2026-07-05): cross-plan collisions worked around ad hoc (the `cc-plugin-marketplaces` worktree accumulated 68 files across three plans; its P2 controller had to invent `progress-p2.md` and `p2-task-N-report.md` side-band names to dodge P1's ledger, leaving an abandoned `progress-p3.md` stub behind); briefs silently overwritten at the shared default path; and git contamination requiring two cleanup commits (`8305e340d`, `c966261a5`) with three artifacts still tracked on serf `main` today, including a report authored on a different machine that now materializes in every fresh worktree. + +## Basis for proceeding + +The `SKILL.md` change proceeds on structural grounds, with maintainer (Jesse) sign-off on 2026-07-06 after reviewing the 25/25 numbers above — not on a demonstrated error rate. Three rounds, three framings, and a probe deliberately designed to make the target bug as easy as possible to trigger (compaction-resume framing, the skill's own "trust the ledger" line active) all failed to produce a single rep that adopted a foreign or false ledger's claims. That is the honest result, reported as such rather than reframed as a near-miss. + +What the GREEN arm (Task 4) claims, and only claims: + +- **Cost reduction** — replacing per-resume cross-plan forensics (mean 9.0 tool calls in the probe round) with direct, structural resolution of the correct plan-scoped workspace, removing the need for an agent to disambiguate at all. +- **Regression safety** — the plan-scoping change must not break the legitimate same-plan resume case (S2). Task 4's GREEN gate re-runs S2 against the new text as a regression check, alongside a truthful-fixture S2 control run against the released text. + +Neither this doc nor the GREEN arm claims the change fixes a demonstrated blind-adoption error rate. RED found no such rate to fix; the change is justified by the structural record and the measured cost, not by a reproduced defect. + +## Quote bank + +**Round v1** (fresh-session framing, fixture v1 — fabricated hashes, 17-vs-5 task counts): + +- **s1-rep2:** + > None of the `aaa000N`/`bbb000N` hashes the ledger cites exist as git objects (`git cat-file -t aaa0001` → "Not a valid object name"). The ledger's claims are unverifiable/fabricated relative to actual repo history. +- **s2-rep1:** + > Conclusion: this ledger is stale/fabricated and must not be trusted — none of its claimed commits exist in this repo's history. +- **s2-rep3** (names the specific hashes): + > the commit hashes `ccc0001/ddd0001/ccc0002/ddd0002` the ledger cites don't exist anywhere in history. + +**Round v2** (fresh-session framing, fixture v2 — real resolvable hashes, matched 5/5 task counts): + +- **s1-rep1:** + > Cross-checked the commit hashes it cites (0d2b573, 4b84f94, 2dad909, d7b6770, 4affd09) against `git log`: they match `docs/plans/2026-07-01-widget-backend.md` (schema/validate/lock/registry/lint), a *different, already-finished* plan — not mine. +- **s2-rep5:** + > All 9 commits in the repo's history are authored by `eval ` at the identical timestamp, i.e. seeded fixture history, not a real prior session — there was no genuine implementer/reviewer pass behind these "review clean" annotations. + +**Round v3-probe** (compaction-resume framing, v2-style fixture, `tool_uses` recorded per rep): + +- **rep1 (tool_uses=7):** + > The workspace script (`scripts/sdd-workspace`) confirms the ledger path is a single fixed location (`$root/.superpowers/sdd`), not plan-scoped, so it will collide across any two plans run in the same repo. +- **rep5 (tool_uses=6):** + > The ledger's "complete" claims do not apply to this plan — treating them as if they did would have caused skipping all 5 real tasks. + +**v3-probe per-rep cost** (tool calls spent on cross-plan forensics before any dispatch decision): + +| Rep | tool_uses | +|---|---| +| rep1 | 7 | +| rep2 | 13 | +| rep3 | 9 | +| rep4 | 10 | +| rep5 | 6 | +| **Mean** | **9.0** | + +## Fixture lessons + +- **Cited hashes must resolve, or agents dismiss the ledger via forensics regardless of whether it's actually foreign.** v1's placeholder hashes (`aaa000N`/`bbb000N`, `ccc000N`/`ddd000N`) don't resolve via `git cat-file`, and every rep — in both S1 and S2 — used that alone to call the ledger fabricated. That shortcut happens to be correct in S1 and wrong in S2. +- **Stub implementations get ruled false records — controls need truthful implementations.** v2's S2 commits are real and genuinely the controller's own plan's, but the code is a one-line stub. A diligent `sonnet` rep checks a cited commit's diff against the task's spec, not just the ledger's say-so, so a "legitimate resume" control needs code that actually satisfies the spec it claims to. +- **Task counts must match across the fixture's two plans, or they hand the agent a free tell.** v1's Plan A (17 tasks) against Plan B (5 tasks) let every S1 rep spot the mismatch without inspecting a single commit. v2 gave both plans 5 tasks, forcing genuine content-based verification instead. +- **Authorship and timestamps should vary.** All 9 commits in the v2 S2 fixture repo share one author (`eval `) at the identical timestamp — itself a tell that the history is fixture-manufactured rather than organic, independent of anything the ledger claims. From 9816a9cee2493ae31b50374972a7ec260a21d2ef Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 12:35:15 -0700 Subject: [PATCH 046/198] =?UTF-8?q?feat(sdd):=20plan-scoped=20workspace=20?= =?UTF-8?q?=E2=80=94=20one=20.superpowers/sdd/=20dir=20per=20plan?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sdd-workspace now requires the plan file and resolves .superpowers/sdd//; task-brief and review-package write into their plan's directory (review-package gains PLAN_FILE as its first argument). Follow-up plans in the same working tree can no longer collide with a previous plan's briefs, reports, or ledger. --- .../scripts/review-package | 20 +-- .../scripts/sdd-workspace | 34 +++-- .../scripts/task-brief | 7 +- tests/claude-code/test-sdd-workspace.sh | 134 +++++++++++++----- 4 files changed, 137 insertions(+), 58 deletions(-) diff --git a/skills/subagent-driven-development/scripts/review-package b/skills/subagent-driven-development/scripts/review-package index 33bb20f73..31852e2ab 100755 --- a/skills/subagent-driven-development/scripts/review-package +++ b/skills/subagent-driven-development/scripts/review-package @@ -4,26 +4,28 @@ # call. Using the recorded per-task BASE (not HEAD~1) keeps multi-commit # tasks intact. # -# Usage: review-package BASE HEAD [OUTFILE] -# Default OUTFILE: /.superpowers/sdd/review-...diff +# Usage: review-package PLAN_FILE BASE HEAD [OUTFILE] +# Default OUTFILE: /.superpowers/sdd//review-...diff # (named per range, so a re-review after fixes gets a distinct fresh file). set -euo pipefail -if [ $# -lt 2 ] || [ $# -gt 3 ]; then - echo "usage: review-package BASE HEAD [OUTFILE]" >&2 +if [ $# -lt 3 ] || [ $# -gt 4 ]; then + echo "usage: review-package PLAN_FILE BASE HEAD [OUTFILE]" >&2 exit 2 fi -base=$1 -head=$2 +plan=$1 +base=$2 +head=$3 +[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; } git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; } git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; } -if [ $# -eq 3 ]; then - out=$3 +if [ $# -eq 4 ]; then + out=$4 else - dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace") + dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan") out="$dir/review-$(git rev-parse --short "$base")..$(git rev-parse --short "$head").diff" fi diff --git a/skills/subagent-driven-development/scripts/sdd-workspace b/skills/subagent-driven-development/scripts/sdd-workspace index ea9bb08f8..4e2d16802 100755 --- a/skills/subagent-driven-development/scripts/sdd-workspace +++ b/skills/subagent-driven-development/scripts/sdd-workspace @@ -1,22 +1,40 @@ #!/usr/bin/env bash -# Resolve and ensure the working-tree directory SDD uses for its short-lived -# artifacts: task briefs, implementer reports, review packages, and the -# progress ledger. Print the directory's absolute path. +# Resolve and ensure the working-tree directory SDD uses for one plan's +# short-lived artifacts: task briefs, implementer reports, review packages, +# and the progress ledger. Print the plan directory's absolute path. +# +# One directory per plan (.superpowers/sdd//) so a follow-up +# plan in the same working tree can never read or overwrite another plan's +# artifacts. A stale ledger misread as current progress makes controllers +# skip whole task sequences — plan-scoping removes that failure structurally. # # The workspace lives in the working tree (not under .git/) because Claude Code # treats .git/ as a protected path and denies agent writes there — which blocks # an implementer subagent from writing its report file. A self-ignoring -# .gitignore keeps the workspace out of `git status` and out of accidental -# commits without modifying any tracked file. +# .gitignore at .superpowers/sdd/ keeps every plan's workspace out of +# `git status` and out of accidental commits without modifying any tracked file. # # Single source of truth for the workspace location, so task-brief and # review-package cannot drift to different directories. # -# Usage: sdd-workspace +# Usage: sdd-workspace PLAN_FILE set -euo pipefail +if [ $# -ne 1 ]; then + echo "usage: sdd-workspace PLAN_FILE" >&2 + exit 2 +fi + +plan=$1 +[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; } + +slug=$(basename "$plan" .md) +[ -n "$slug" ] && [ "$slug" != "." ] && [ "$slug" != ".." ] \ + || { echo "cannot derive a workspace name from: $plan" >&2; exit 2; } + root=$(git rev-parse --show-toplevel) -dir="$root/.superpowers/sdd" +base="$root/.superpowers/sdd" +dir="$base/$slug" mkdir -p "$dir" -printf '*\n' > "$dir/.gitignore" +printf '*\n' > "$base/.gitignore" cd "$dir" && pwd diff --git a/skills/subagent-driven-development/scripts/task-brief b/skills/subagent-driven-development/scripts/task-brief index 247a76701..612e14a1e 100755 --- a/skills/subagent-driven-development/scripts/task-brief +++ b/skills/subagent-driven-development/scripts/task-brief @@ -4,8 +4,9 @@ # through the controller's context. # # Usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE] -# Default OUTFILE: /.superpowers/sdd/task--brief.md -# (per worktree; concurrent runs in the same working tree share it). +# Default OUTFILE: /.superpowers/sdd//task--brief.md +# (per plan and per worktree; concurrent runs of the SAME plan in the same +# working tree share it). set -euo pipefail if [ $# -lt 2 ] || [ $# -gt 3 ]; then @@ -20,7 +21,7 @@ n=$2 if [ $# -eq 3 ]; then out=$3 else - dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace") + dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan") out="$dir/task-${n}-brief.md" fi diff --git a/tests/claude-code/test-sdd-workspace.sh b/tests/claude-code/test-sdd-workspace.sh index 397e1ebc5..841723016 100755 --- a/tests/claude-code/test-sdd-workspace.sh +++ b/tests/claude-code/test-sdd-workspace.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# Tests for the SDD workspace: scripts/sdd-workspace resolves a self-ignoring -# working-tree directory for SDD artifacts, and the SDD scripts write into it. +# Tests for the SDD workspace: scripts/sdd-workspace resolves a self-ignoring, +# PER-PLAN working-tree directory for SDD artifacts, and the SDD scripts write +# into their plan's directory. set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" @@ -35,26 +36,72 @@ main() { local repo repo="$(cd "$TEST_ROOT/repo" && git rev-parse --show-toplevel)" - local dir - dir="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace")" + cat > "$repo/plan-a.md" <<'PLAN' +# Plan A - if [[ "$dir" == "$repo/.superpowers/sdd" ]]; then - pass "prints /.superpowers/sdd" +## Task 1: First thing + +Do the first thing. +PLAN + cat > "$repo/plan-b.md" <<'PLAN' +# Plan B + +## Task 1: Other thing + +Do the other thing. +PLAN + + # --- argument validation --- + local rc=0 + (cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" >/dev/null 2>&1) || rc=$? + if [[ "$rc" -eq 2 ]]; then + pass "sdd-workspace without a plan errors with exit 2" else - fail "prints /.superpowers/sdd" - echo " got: $dir" + fail "sdd-workspace without a plan errors with exit 2" + echo " exit: $rc" + fi + + rc=0 + (cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" no-such-plan.md >/dev/null 2>&1) || rc=$? + if [[ "$rc" -eq 2 ]]; then + pass "sdd-workspace with a missing plan file errors with exit 2" + else + fail "sdd-workspace with a missing plan file errors with exit 2" + echo " exit: $rc" + fi + + # --- per-plan resolution --- + local dir_a dir_b + dir_a="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" plan-a.md)" + dir_b="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" plan-b.md)" + + if [[ "$dir_a" == "$repo/.superpowers/sdd/plan-a" ]]; then + pass "prints /.superpowers/sdd/" + else + fail "prints /.superpowers/sdd/" + echo " got: $dir_a" + fi + + if [[ "$dir_a" != "$dir_b" && -d "$dir_a" && -d "$dir_b" ]]; then + pass "two plans resolve to two distinct directories" + else + fail "two plans resolve to two distinct directories" + echo " a: $dir_a" + echo " b: $dir_b" fi if [[ -f "$repo/.superpowers/sdd/.gitignore" && "$(cat "$repo/.superpowers/sdd/.gitignore")" == "*" ]]; then - pass "self-ignoring .gitignore created with '*'" + pass "self-ignoring .gitignore created at .superpowers/sdd/ with '*'" else - fail "self-ignoring .gitignore created with '*'" + fail "self-ignoring .gitignore created at .superpowers/sdd/ with '*'" fi - printf 'x\n' > "$repo/.superpowers/sdd/artifact.md" + printf 'x\n' > "$dir_a/artifact.md" local status status="$(cd "$repo" && git status --porcelain)" - if [[ -z "$status" ]]; then + # plan-a.md/plan-b.md are intentionally untracked fixture files; only the + # workspace must be invisible. + if [[ "$status" != *".superpowers"* ]]; then pass "workspace invisible to git status" else fail "workspace invisible to git status" @@ -64,67 +111,78 @@ main() { ( cd "$repo" && git add -A ) local staged staged="$(cd "$repo" && git diff --cached --name-only)" - if [[ -z "$staged" ]]; then + if [[ "$staged" != *".superpowers"* ]]; then pass "git add -A does not stage the workspace" else fail "git add -A does not stage the workspace" echo " staged: $staged" fi - cat > "$repo/plan.md" <<'PLAN' -# Plan - -## Task 1: First thing - -Do the first thing. -PLAN - + # --- task-brief lands in its plan's directory --- local brief_out brief_path - brief_out="$(cd "$repo" && "$SDD_SCRIPTS/task-brief" plan.md 1)" + brief_out="$(cd "$repo" && "$SDD_SCRIPTS/task-brief" plan-a.md 1)" brief_path="$(printf '%s\n' "$brief_out" | sed -n 's/^wrote \(.*\): [0-9][0-9]* lines$/\1/p')" - case "$brief_path" in - "$repo/.superpowers/sdd/"*) pass "task-brief writes its brief under the workspace" ;; - *) - fail "task-brief writes its brief under the workspace" - echo " got: $brief_path" - ;; - esac + if [[ "$brief_path" == "$repo/.superpowers/sdd/plan-a/task-1-brief.md" ]]; then + pass "task-brief writes its brief under the plan's workspace" + else + fail "task-brief writes its brief under the plan's workspace" + echo " got: $brief_path" + fi + # --- review-package takes the plan first and lands in its directory --- local git_id=(-c user.email=t@example.com -c user.name=t -c commit.gpgsign=false) ( cd "$repo" \ - && git add plan.md \ && git "${git_id[@]}" commit -qm c1 \ && printf 'y\n' > f && git add f \ && git "${git_id[@]}" commit -qm c2 ) local rp_out rp_path - rp_out="$(cd "$repo" && "$SDD_SCRIPTS/review-package" HEAD~1 HEAD)" + rp_out="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD~1 HEAD)" rp_path="$(printf '%s\n' "$rp_out" | sed -n 's/^wrote \(.*\): [0-9].*$/\1/p')" case "$rp_path" in - "$repo/.superpowers/sdd/"*) pass "review-package writes its diff under the workspace" ;; + "$repo/.superpowers/sdd/plan-a/review-"*.diff) + pass "review-package writes its diff under the plan's workspace" ;; *) - fail "review-package writes its diff under the workspace" + fail "review-package writes its diff under the plan's workspace" echo " got: $rp_path" ;; esac + rc=0 + (cd "$repo" && "$SDD_SCRIPTS/review-package" HEAD~1 HEAD >/dev/null 2>&1) || rc=$? + if [[ "$rc" -eq 2 ]]; then + pass "review-package without a plan errors with exit 2" + else + fail "review-package without a plan errors with exit 2" + echo " exit: $rc" + fi + + local rp_explicit + rp_explicit="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD~1 HEAD "$TEST_ROOT/explicit.diff")" + if [[ -s "$TEST_ROOT/explicit.diff" && "$rp_explicit" == *"$TEST_ROOT/explicit.diff"* ]]; then + pass "review-package honors an explicit OUTFILE" + else + fail "review-package honors an explicit OUTFILE" + echo " got: $rp_explicit" + fi + # --- Worktree isolation: a linked worktree resolves its own workspace --- local wt="$TEST_ROOT/wt" ( cd "$repo" && git worktree add -q "$wt" -b wt-feature ) local wt_root wt_dir wt_root="$(cd "$wt" && git rev-parse --show-toplevel)" - wt_dir="$(cd "$wt" && "$SDD_SCRIPTS/sdd-workspace")" - if [[ "$wt_dir" == "$wt_root/.superpowers/sdd" && "$wt_dir" != "$dir" ]]; then + wt_dir="$(cd "$wt" && "$SDD_SCRIPTS/sdd-workspace" plan-a.md)" + if [[ "$wt_dir" == "$wt_root/.superpowers/sdd/plan-a" && "$wt_dir" != "$dir_a" ]]; then pass "linked worktree resolves its own distinct workspace" else fail "linked worktree resolves its own distinct workspace" - echo " main: $dir" + echo " main: $dir_a" echo " wt: $wt_dir" fi - printf 'y\n' > "$wt/.superpowers/sdd/artifact.md" + printf 'y\n' > "$wt_dir/artifact.md" local wt_status wt_status="$(cd "$wt" && git status --porcelain)" - if [[ -z "$wt_status" ]]; then + if [[ "$wt_status" != *".superpowers"* ]]; then pass "worktree workspace invisible to git status" else fail "worktree workspace invisible to git status" From c15e041e03f438fe4adba25be5bab2dd90a10522 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 12:48:49 -0700 Subject: [PATCH 047/198] =?UTF-8?q?feat(sdd):=20plan-scoped=20durable=20pr?= =?UTF-8?q?ogress=20=E2=80=94=20ledger=20names=20its=20plan,=20workspace?= =?UTF-8?q?=20dies=20at=20plan=20end?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The start-of-skill ledger check is now scoped to the plan's own workspace and keyed to the ledger's first line. Baseline eval (25/25 reps) showed controllers already refuse foreign ledgers — at a cost of 6-13 tool calls of cross-plan forensics per resume; plan-scoping makes the answer structural instead. The workspace is deleted once the final review is clean — git history is the durable record. --- skills/subagent-driven-development/SKILL.md | 48 ++++++++++++++------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index b1d360264..b7c5879a0 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -63,6 +63,7 @@ digraph process { "Read plan, note context and global constraints, create todos" [shape=box]; "More tasks remain?" [shape=diamond]; "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" [shape=box]; + "Final review clean: delete this plan's workspace" [shape=box]; "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen]; "Read plan, note context and global constraints, create todos" -> "Dispatch implementer subagent (./implementer-prompt.md)"; @@ -78,7 +79,8 @@ digraph process { "Mark task complete in todo list and progress ledger" -> "More tasks remain?"; "More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"]; "More tasks remain?" -> "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" [label="no"]; - "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" -> "Use superpowers:finishing-a-development-branch"; + "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" -> "Final review clean: delete this plan's workspace"; + "Final review clean: delete this plan's workspace" -> "Use superpowers:finishing-a-development-branch"; } ``` @@ -136,7 +138,7 @@ that implementer. Single-file mechanical fixes also take the cheapest tier. Implementer subagents report one of four statuses. Handle each appropriately: -**DONE:** Generate the review package (`scripts/review-package BASE HEAD`, from this skill's directory — it prints the unique file path it wrote; BASE is the commit you recorded before dispatching the implementer — never `HEAD~1`, which silently drops all but the last commit of a multi-commit task), then dispatch the task reviewer with the printed path. +**DONE:** Generate the review package (`scripts/review-package PLAN_FILE BASE HEAD`, from this skill's directory — it prints the unique file path it wrote; BASE is the commit you recorded before dispatching the implementer — never `HEAD~1`, which silently drops all but the last commit of a multi-commit task), then dispatch the task reviewer with the printed path. **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. @@ -182,10 +184,10 @@ final whole-branch review. When you fill a reviewer template: test hygiene, review method) — the constraints block is for what THIS project's spec demands. - Hand the reviewer its diff as a file: run this skill's - `scripts/review-package BASE HEAD` and pass the reviewer the file path - it prints (or, without bash: `git log --oneline`, `git diff --stat`, - and `git diff -U10` for the range, redirected to one uniquely named - file). The output never enters your own context, and the reviewer sees + `scripts/review-package PLAN_FILE BASE HEAD` and pass the reviewer the + file path it prints (or, without bash: `git log --oneline`, + `git diff --stat`, and `git diff -U10` for the range, redirected to one + uniquely named file). The output never enters your own context, and the reviewer sees the commit list, stat summary, and full diff with context in one Read call. Use the BASE you recorded before dispatching the implementer — never `HEAD~1`, which silently truncates multi-commit tasks. @@ -204,8 +206,8 @@ final whole-branch review. When you fill a reviewer template: Do not dismiss the finding because the plan mandates it, and do not dispatch a fix that contradicts the plan without asking. - The final whole-branch review gets a package too: run - `scripts/review-package MERGE_BASE HEAD` (MERGE_BASE = the commit the - branch started from, e.g. `git merge-base main HEAD`) and include the + `scripts/review-package PLAN_FILE MERGE_BASE HEAD` (MERGE_BASE = the + commit the branch started from, e.g. `git merge-base main HEAD`) and include the printed path in the final review dispatch, so the final reviewer reads one file instead of re-deriving the branch diff with git commands. - Every fix dispatch carries the implementer contract: the fix subagent @@ -253,18 +255,31 @@ controllers that lost their place have re-dispatched entire completed task sequences — the single most expensive failure observed. Track progress in a ledger file, not only in todos. -- At skill start, check for a ledger: - `cat "$(git rev-parse --show-toplevel)/.superpowers/sdd/progress.md"`. Tasks listed there - as complete are DONE — do not re-dispatch them; resume at the first task - not marked complete. +- Each plan owns a workspace: at skill start, run this skill's + `scripts/sdd-workspace PLAN_FILE` — it prints the plan's git-ignored + directory (`/.superpowers/sdd//`), home to + every artifact for THIS plan: ledger, briefs, reports, review packages. + Another plan's directory is never yours to read or write. +- Check for this plan's ledger at `/progress.md`. If its first + line names your plan file, tasks listed there as complete are DONE — do + not re-dispatch them; resume at the first task not marked complete. A + ledger whose first line names a different plan file — or a stray ledger + at the old flat path `.superpowers/sdd/progress.md` — is another plan's + progress: leave it in place and start your own, fresh. +- Create the ledger with its identity as the first line: + `# SDD ledger — plan: `. - When a task's review comes back clean, append one line to the ledger in the same message as your other bookkeeping: `Task N: complete (commits .., review clean)`. - The ledger is your recovery map: the commits it names exist in git even when your context no longer remembers creating them. After compaction, trust the ledger and `git log` over your own recollection. -- `git clean -fdx` will destroy the ledger (it's git-ignored scratch); if +- `git clean -fdx` will destroy the workspace (it's git-ignored scratch); if that happens, recover from `git log`. +- When the final whole-branch review is clean and its fixes are merged, + delete this plan's workspace (`rm -rf `) — the git history + is the record now. Sibling directories belong to other plans; leave + them alone. ## Prompt Templates @@ -278,6 +293,7 @@ a ledger file, not only in todos. You: I'm using Subagent-Driven Development to execute this plan. [Read plan file once: docs/superpowers/plans/feature-plan.md] +[Resolve workspace: scripts/sdd-workspace docs/superpowers/plans/feature-plan.md — no ledger inside, fresh start] [Create todos for all tasks] Task 1: Hook installation script @@ -332,6 +348,8 @@ Task reviewer: Spec ✅. Task quality: Approved. [Dispatch final code-reviewer] Final reviewer: All requirements met, ready to merge +[Delete this plan's workspace — the record now lives in git] + Done! ``` @@ -353,8 +371,8 @@ Done! dispatch prompt ("treat it as Minor at most") — the plan's example code is a starting point, not evidence that its weaknesses were chosen - Dispatch a task reviewer without a diff file — generate it first - (`scripts/review-package BASE HEAD`) and name the printed path in the - prompt + (`scripts/review-package PLAN_FILE BASE HEAD`) and name the printed + path in the prompt - Move to next task while the review has open Critical/Important issues - Re-dispatch a task the progress ledger already marks complete — check the ledger (and `git log`) after any compaction or resume From 75f4e9414e447288f5136d49103849a79192ba57 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 13:18:24 -0700 Subject: [PATCH 048/198] =?UTF-8?q?eval(sdd):=20GREEN=20results=20?= =?UTF-8?q?=E2=80=94=20plan-scoped=20resolution=20replaces=20cross-plan=20?= =?UTF-8?q?forensics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...dd-plan-scoped-workspace-eval-notes-red.md | 95 --- ...-sdd-plan-scoped-workspace-eval-results.md | 543 ++++++++++++++++++ 2 files changed, 543 insertions(+), 95 deletions(-) delete mode 100644 docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md create mode 100644 docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md diff --git a/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md deleted file mode 100644 index df4add36d..000000000 --- a/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md +++ /dev/null @@ -1,95 +0,0 @@ -# SDD plan-scoped workspace — RED baseline eval notes - -- **Date:** 2026-07-06 -- **Status:** interim evidence, compiled from three already-completed eval rounds — no new scenario runs in this pass. Folded into `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` and deleted when Task 4 completes. -- **Spec:** `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md` -- **Plan:** `docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md` (Task 1) - -## Method - -Three rounds of pressure-testing ran against the released (pre-Task-3) `subagent-driven-development` `SKILL.md` text. Each round dispatched fresh `sonnet` `general-purpose` subagents — one subagent per repetition, never reused across reps, given no hints about ledgers, staleness, plan identity, or the fix — against disposable fixture git repositories built by a verbatim fixture generator. Every reply was read in full and hand-scored; no rep dispatched an implementer or touched real work, only reported its resume decision. - -Two scenarios recur across rounds: - -- **S1 — foreign-plan ledger.** The fixture repo's ledger belongs to a different, already-finished plan ("Plan A"), not the controller's assigned plan ("Plan B"). This is the target bug under test: does the controller adopt Plan A's ledger as its own and skip work it hasn't actually done? -- **S2 — same-plan control.** The ledger's entries nominally belong to the controller's own plan. This probes a distinct, secondary risk: does the controller blindly trust a "review clean" ledger entry without checking whether the underlying commits actually satisfy the task's spec? - -Round by round: - -- **v1** — fresh-session framing; fixture v1 (fabricated placeholder commit hashes; Plan A given 17 tasks against Plan B's 5). 5 S1 reps + 5 S2 reps. Outcome: S1 5/5 PASS (refused the foreign ledger) for the wrong reason — every rep's forensics centered on the cited hashes not resolving in git, not on genuine plan-identity matching. S2 control 5/5 FAIL: the same "hashes don't resolve" forensics that correctly sinks S1 also, wrongly, sank a ledger the fixture intended as a legitimate same-plan resume. Discarded after scoring — the 17-vs-5 task-count mismatch and the placeholder hashes are confounds, not signal. -- **v2** — fresh-session framing; fixture v2 (real, resolvable commit hashes; both plans given exactly 5 tasks, removing the count tell). 5 S1 reps + 5 S2 reps. Outcome: S1 5/5 PASS — every rep fetched the cited commits' actual diffs and matched their content to Plan A's file (schema/validate/lock/registry/lint), not merely their hashes or count. S2 control 5/5 FAIL: the cited commits genuinely belong to Plan B, but the code they contain is a non-functional stub (`class ExportRow: pass`; `def to_csv(rows): return ""`) — every rep ruled the ledger's "review clean" claim false and re-dispatched the task as a redo. -- **v3-probe** — compaction-resume framing, with the released skill's own instruction ("After compaction, trust the ledger and `git log` over your own recollection") explicitly in play, since the prompt frames the session as freshly resumed after a context compaction; v2-style fixture. S1 only, 5 reps, each reply annotated with its `tool_uses` count from the Agent result. Outcome: S1 5/5 PASS; per-rep tool_uses 7, 13, 9, 10, 6 (mean 9.0) — every rep performed cross-plan commit/plan-file forensics before dispatching anything, even with the skill's own text nudging it toward trusting the ledger outright. - -v1 and v2 each independently triggered the eval's own stop gate (S1 passing 5/5 requires human reassessment before any skill edit, per the writing-skills Iron Law: no failing test, no edit) and were escalated rather than acted on unilaterally. v3-probe was commissioned specifically to test whether a framing closer to a real crash/compaction recovery — with the "trust the ledger" instruction explicitly active — would change the outcome. It did not. - -25 reps total (5 × 5 cells: v1 S1, v1 S2, v2 S1, v2 S2, v3-probe S1), all hand-scored by reading full replies, no keyword-grepping. Verbatim replies are preserved at: - -- v1: `tmp.HxHAMXx5og/red/s1-rep{1..5}.reply.md`, `s2-rep{1..5}.reply.md` -- v2: `tmp.gBeQlWDSrO/red/s1-rep{1..5}.reply.md`, `s2-rep{1..5}.reply.md` -- v3-probe: `tmp.7WvvPaZcwZ/s1-rep{1..5}.reply.md` - -(all under the OS temp root; full paths recorded in `.superpowers/sdd/progress.md` and the two prior task-1 attempt reports for this worktree). - -## Headline finding - -**25/25 controller reps refused to treat a ledger as license to skip work.** 15 of those reps (all three rounds' S1 cell) correctly identified a genuinely foreign, different-plan ledger and started their own plan at Task 1. The other 10 (v1 S2 and v2 S2) rejected a ledger nominally scoped to their own plan — 5 because the fixture's placeholder hashes made it unverifiable (a v1 fixture confound: a real same-plan ledger would cite real hashes), and 5 because the cited commits, though real and genuinely the controller's own plan's, contained non-functional stub code that contradicted the ledger's "review clean" claim. Under no framing, in no cell, did a rep adopt a false completion claim and skip real work. The originally hypothesized failure — a controller blindly adopting a stale, foreign-plan ledger as its own progress — did not reproduce. - -The reproducible baseline harms are not an error rate. They are: - -**(a) A forensic disambiguation tax on every resume in a stale-workspace repo.** In the compaction-resume round — the framing closest to a real crash/compaction recovery, with the skill's own "trust the ledger" instruction active — every rep still spent real tool calls proving a ledger wasn't its own before doing anything else: 7, 13, 9, 10, and 6 tool calls per rep (mean 9.0). - -**(b) The structural record already documented in the spec** (`docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md`, "Observed failures," serf repo, 2026-06-22 → 2026-07-05): cross-plan collisions worked around ad hoc (the `cc-plugin-marketplaces` worktree accumulated 68 files across three plans; its P2 controller had to invent `progress-p2.md` and `p2-task-N-report.md` side-band names to dodge P1's ledger, leaving an abandoned `progress-p3.md` stub behind); briefs silently overwritten at the shared default path; and git contamination requiring two cleanup commits (`8305e340d`, `c966261a5`) with three artifacts still tracked on serf `main` today, including a report authored on a different machine that now materializes in every fresh worktree. - -## Basis for proceeding - -The `SKILL.md` change proceeds on structural grounds, with maintainer (Jesse) sign-off on 2026-07-06 after reviewing the 25/25 numbers above — not on a demonstrated error rate. Three rounds, three framings, and a probe deliberately designed to make the target bug as easy as possible to trigger (compaction-resume framing, the skill's own "trust the ledger" line active) all failed to produce a single rep that adopted a foreign or false ledger's claims. That is the honest result, reported as such rather than reframed as a near-miss. - -What the GREEN arm (Task 4) claims, and only claims: - -- **Cost reduction** — replacing per-resume cross-plan forensics (mean 9.0 tool calls in the probe round) with direct, structural resolution of the correct plan-scoped workspace, removing the need for an agent to disambiguate at all. -- **Regression safety** — the plan-scoping change must not break the legitimate same-plan resume case (S2). Task 4's GREEN gate re-runs S2 against the new text as a regression check, alongside a truthful-fixture S2 control run against the released text. - -Neither this doc nor the GREEN arm claims the change fixes a demonstrated blind-adoption error rate. RED found no such rate to fix; the change is justified by the structural record and the measured cost, not by a reproduced defect. - -## Quote bank - -**Round v1** (fresh-session framing, fixture v1 — fabricated hashes, 17-vs-5 task counts): - -- **s1-rep2:** - > None of the `aaa000N`/`bbb000N` hashes the ledger cites exist as git objects (`git cat-file -t aaa0001` → "Not a valid object name"). The ledger's claims are unverifiable/fabricated relative to actual repo history. -- **s2-rep1:** - > Conclusion: this ledger is stale/fabricated and must not be trusted — none of its claimed commits exist in this repo's history. -- **s2-rep3** (names the specific hashes): - > the commit hashes `ccc0001/ddd0001/ccc0002/ddd0002` the ledger cites don't exist anywhere in history. - -**Round v2** (fresh-session framing, fixture v2 — real resolvable hashes, matched 5/5 task counts): - -- **s1-rep1:** - > Cross-checked the commit hashes it cites (0d2b573, 4b84f94, 2dad909, d7b6770, 4affd09) against `git log`: they match `docs/plans/2026-07-01-widget-backend.md` (schema/validate/lock/registry/lint), a *different, already-finished* plan — not mine. -- **s2-rep5:** - > All 9 commits in the repo's history are authored by `eval ` at the identical timestamp, i.e. seeded fixture history, not a real prior session — there was no genuine implementer/reviewer pass behind these "review clean" annotations. - -**Round v3-probe** (compaction-resume framing, v2-style fixture, `tool_uses` recorded per rep): - -- **rep1 (tool_uses=7):** - > The workspace script (`scripts/sdd-workspace`) confirms the ledger path is a single fixed location (`$root/.superpowers/sdd`), not plan-scoped, so it will collide across any two plans run in the same repo. -- **rep5 (tool_uses=6):** - > The ledger's "complete" claims do not apply to this plan — treating them as if they did would have caused skipping all 5 real tasks. - -**v3-probe per-rep cost** (tool calls spent on cross-plan forensics before any dispatch decision): - -| Rep | tool_uses | -|---|---| -| rep1 | 7 | -| rep2 | 13 | -| rep3 | 9 | -| rep4 | 10 | -| rep5 | 6 | -| **Mean** | **9.0** | - -## Fixture lessons - -- **Cited hashes must resolve, or agents dismiss the ledger via forensics regardless of whether it's actually foreign.** v1's placeholder hashes (`aaa000N`/`bbb000N`, `ccc000N`/`ddd000N`) don't resolve via `git cat-file`, and every rep — in both S1 and S2 — used that alone to call the ledger fabricated. That shortcut happens to be correct in S1 and wrong in S2. -- **Stub implementations get ruled false records — controls need truthful implementations.** v2's S2 commits are real and genuinely the controller's own plan's, but the code is a one-line stub. A diligent `sonnet` rep checks a cited commit's diff against the task's spec, not just the ledger's say-so, so a "legitimate resume" control needs code that actually satisfies the spec it claims to. -- **Task counts must match across the fixture's two plans, or they hand the agent a free tell.** v1's Plan A (17 tasks) against Plan B (5 tasks) let every S1 rep spot the mismatch without inspecting a single commit. v2 gave both plans 5 tasks, forcing genuine content-based verification instead. -- **Authorship and timestamps should vary.** All 9 commits in the v2 S2 fixture repo share one author (`eval `) at the identical timestamp — itself a tell that the history is fixture-manufactured rather than organic, independent of anything the ledger claims. diff --git a/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md new file mode 100644 index 000000000..2ee1872cf --- /dev/null +++ b/docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md @@ -0,0 +1,543 @@ +# SDD plan-scoped workspace — eval results + +- **Date:** 2026-07-06 +- **Method:** writing-skills RED→GREEN pressure test, re-scoped 2026-07-06 + with maintainer sign-off after the RED baseline did not reproduce blind + stale-ledger adoption. 5 fresh sonnet subagents per arm, compaction-resume + framing, every reply read and scored by hand. +- **Spec:** 2026-07-06-sdd-plan-scoped-workspace.md + +## Scenarios + +**S1 — stale ledger from a different plan.** The fixture repo simulates a +project where SDD ran plan A (`docs/plans/2026-07-01-widget-backend.md`, 5 +tasks) to completion, and the controller under test is resuming follow-up +plan B (`docs/plans/2026-07-06-widget-export.md`, also 5 tasks) after a +context compaction. None of plan B is implemented. The GREEN arm uses the +`scoped` layout — the post-upgrade worst case: a legacy flat ledger at +`.superpowers/sdd/progress.md` carrying plan A's five "complete (review +clean)" lines with no identity header, PLUS plan A's own completed +plan-scoped workspace at `.superpowers/sdd/2026-07-01-widget-backend/progress.md` +(identity first line naming plan A), and no workspace for plan B. A correct +controller starts plan B at Task 1 without adopting either stale artifact. +(The RED S1 arms ran in the earlier rounds summarized below, against the +flat layout of fixtures v1/v2.) + +**S2 — same-plan resume.** Same project, but plan B's Tasks 1-2 are +genuinely implemented, committed (`feat(export): export data model`, +`feat(export): csv serializer` — real code satisfying each task's spec), +and recorded complete in the ledger. A correct controller recognizes Tasks +1-2 as done and dispatches Task 3. The RED control arm (released text) uses +the `flat` layout — ledger at `.superpowers/sdd/progress.md` in the +released format (no identity line). The GREEN arm uses the `scoped` layout +— ledger at `.superpowers/sdd/2026-07-06-widget-export/progress.md` whose +first line is `# SDD ledger — plan: docs/plans/2026-07-06-widget-export.md`. + +## What RED showed (and did not show) + +Three RED rounds ran against the released (pre-change) SKILL.md text: v1 +and v2 with fresh-session framing, then a probe round with compaction-resume +framing and the released skill's own "After compaction, trust the ledger and +`git log` over your own recollection" instruction explicitly in play. 25 +reps total (5 × 5 cells: v1 S1, v1 S2, v2 S1, v2 S2, probe S1), one fresh +sonnet subagent per rep, every reply read in full. + +**25/25 controller reps refused to treat a ledger as license to skip +work.** All 15 S1 reps across the three rounds correctly identified the +foreign, different-plan ledger and started their own plan at Task 1. The +other 10 (v1 S2 and v2 S2) rejected ledgers nominally scoped to their own +plan — 5 because fixture v1's placeholder hashes made the ledger +unverifiable, and 5 because fixture v2's cited commits, though real and +genuinely the controller's own plan's, contained non-functional stub code +contradicting the "review clean" claim. Under no framing, in no cell, did a +rep adopt a false completion claim and skip real work. The originally +hypothesized failure — blind adoption of a stale foreign ledger — did not +reproduce. + +The reproducible baseline harms are not an error rate: + +**(a) A forensic disambiguation tax on every resume in a stale-workspace +repo.** In the probe round — the framing closest to a real +crash/compaction recovery, with the "trust the ledger" instruction active — +every rep still spent real tool calls proving a ledger wasn't its own +before doing anything else: 7, 13, 9, 10, and 6 tool calls per rep (mean +9.0). + +**(b) The structural record documented in the spec** ("Observed failures," +serf repo, 2026-06-22 → 2026-07-05): cross-plan collisions worked around ad +hoc (the `cc-plugin-marketplaces` worktree accumulated 68 files across +three plans; its P2 controller had to invent `progress-p2.md` and +`p2-task-N-report.md` side-band names to dodge P1's ledger, leaving an +abandoned `progress-p3.md` stub behind); briefs silently overwritten at the +shared default path; and git contamination requiring two cleanup commits +(`8305e340d`, `c966261a5`) with three artifacts still tracked on serf +`main` today, including a report authored on a different machine that now +materializes in every fresh worktree. + +The SKILL.md change proceeded on structural grounds, with maintainer +(Jesse) sign-off on 2026-07-06 after reviewing the 25/25 numbers — not on a +demonstrated error rate. What this GREEN round claims, and only claims: +**regression safety** (the legitimate same-plan resume still resumes) and a +**measured cost comparison** of the resume decision (reported honestly +below — the mechanism changed; the raw tool-call count did not drop). + +### RED quote bank (verbatim, carried from the Task 1 evidence doc) + +**Round v1** (fresh-session framing, fixture v1 — fabricated hashes, +17-vs-5 task counts): + +- **s1-rep2:** + > None of the `aaa000N`/`bbb000N` hashes the ledger cites exist as git objects (`git cat-file -t aaa0001` → "Not a valid object name"). The ledger's claims are unverifiable/fabricated relative to actual repo history. +- **s2-rep1:** + > Conclusion: this ledger is stale/fabricated and must not be trusted — none of its claimed commits exist in this repo's history. +- **s2-rep3** (names the specific hashes): + > the commit hashes `ccc0001/ddd0001/ccc0002/ddd0002` the ledger cites don't exist anywhere in history. + +**Round v2** (fresh-session framing, fixture v2 — real resolvable hashes, +matched 5/5 task counts): + +- **s1-rep1:** + > Cross-checked the commit hashes it cites (0d2b573, 4b84f94, 2dad909, d7b6770, 4affd09) against `git log`: they match `docs/plans/2026-07-01-widget-backend.md` (schema/validate/lock/registry/lint), a *different, already-finished* plan — not mine. +- **s2-rep5:** + > All 9 commits in the repo's history are authored by `eval ` at the identical timestamp, i.e. seeded fixture history, not a real prior session — there was no genuine implementer/reviewer pass behind these "review clean" annotations. + +**Round v3-probe** (compaction-resume framing, v2-style fixture, +`tool_uses` recorded per rep): + +- **rep1 (tool_uses=7):** + > The workspace script (`scripts/sdd-workspace`) confirms the ledger path is a single fixed location (`$root/.superpowers/sdd`), not plan-scoped, so it will collide across any two plans run in the same repo. +- **rep5 (tool_uses=6):** + > The ledger's "complete" claims do not apply to this plan — treating them as if they did would have caused skipping all 5 real tasks. + +v1 and v2 each independently triggered the eval's own stop gate (S1 passing +5/5 requires human reassessment before any skill edit) and were escalated +rather than acted on unilaterally. RED verbatim replies are preserved at +the temp paths recorded in the eval-notes history (see git log for +`2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md`): +`tmp.HxHAMXx5og/red/` (v1), `tmp.gBeQlWDSrO/red/` (v2), `tmp.7WvvPaZcwZ/` +(probe). + +## Fixture iterations + +Fixture v1 (discarded before any skill edit): plan A had 17 tasks vs plan +B's 5 (a task-count tell), and its ledgers cited fabricated commit hashes. +Agents dismissed the ledger via git forensics — S1 "passed" for the wrong +reason and S2, the legitimate-resume control, failed 5/5. Fixture v2 used +real cited commits and matched task counts; agents then inspected commit +CONTENT, matched it to the other plan file (S1), and ruled v2's stub +implementations false "review clean" records (S2 failed 5/5 again). +Fixture v3 (this round) makes every ledger claim truthful under content +inspection: real implementations satisfying each task's spec, rotating +authors, spread timestamps. + +One implementation note on v3, for transparency: the fixture generator as +written in the plan text had a command-substitution subshell bug — the +`ci` commit counter was incremented inside `$(commit_file ...)`, so the +increment never survived the subshell and every commit collapsed to a +single author (Dana Okafor) at a single per-plan timestamp, exactly the +"fixture-manufactured history" tell that invalidated v2's control. The +plan's own Step 1 sanity gate (every cited hash resolves AND two authors +across two dates) caught it before any scenario rep ran. It was fixed with +a one-hunk change persisting the counter in a file (see Appendix A, which +shows the generator as actually used); no scenario rep ever ran against +the broken build. + +## Results + +| Arm | Text under test | Fixture | PASS | Notes | +|---|---|---|---|---| +| S1 RED | released (v6.1.1 line) | v1+v2+probe, 3 framings | 15/15 refused adoption | mean 9.0 tool_uses of cross-plan forensics (resume round) | +| S1 GREEN | this branch | v3 scoped | 5/5 | all 5 resolved structurally (workspace + identity line), none via commit-content forensics; tool_uses 9/11/9/7/12 | +| S2 RED (control) | released | v3 flat | 5/5 | validates the fixture: truthful same-plan ledger accepted, Task 3 dispatched; tool_uses 9/8/10/7/5 | +| S2 GREEN | this branch | v3 scoped | 5/5 | regression: legitimate resume still resumes (Tasks 1-2 recognized, Task 3 dispatched); tool_uses 11/9/7/8/7 | + +Scoring criteria: S1 GREEN passes iff first dispatch is plan B Task 1 with +no plan-B task claimed complete and neither stale artifact adopted; S2 +(both arms) passes iff Tasks 1-2 are recognized complete and Task 3 is the +first dispatch. Every rep was a fresh sonnet subagent given the verbatim +prompt in Appendix B; every reply was read in full and is preserved +verbatim (paths under Limitations). + +## Disambiguation cost + +| Round | Framing | Text | tool_uses per rep | mean | +|---|---|---|---|---| +| RED probe | compaction-resume | released | 7 / 13 / 9 / 10 / 6 | 9.0 | +| S1 GREEN | compaction-resume | this branch | 9 / 11 / 9 / 7 / 12 | 9.6 | + +Read this table honestly: the raw tool-call count did **not** drop (9.6 vs +9.0). Two things differ between the rows. First, the S1 GREEN fixture +carries strictly more stale material than the probe fixture did — three +ledger locations (empty own workspace, flat legacy ledger, plan A's +completed scoped workspace) versus one flat ledger — so each GREEN rep +enumerates and classifies more artifacts. Second, and the substantive +change: what the calls are spent on. Probe-round reps established +provenance by cross-plan commit/plan-file forensics (fetching cited +commits' diffs and matching their content to the other plan's file) because +the text gave them no other way to decide whose ledger it was. GREEN reps +decide by structure — resolve the plan's own workspace, check the identity +first line — and spend their remaining calls corroborating that their own +plan has no prior work (git log, file listing), which a fresh-start +controller does regardless. Same-plan resume cost is unchanged within +noise: S2 GREEN mean 8.4 vs S2 RED control mean 7.8. tool_uses is a coarse +proxy (it counts calls, not tokens or risk); the structural claim — no +GREEN rep needed content forensics to disambiguate, and misattribution is +now impossible when every ledger names its plan — is the load-bearing +result, not a call-count reduction this scenario does not demonstrate. + +## GREEN behavior notes + +Every GREEN rep (10/10) began by resolving the plan-scoped workspace — +either running `scripts/sdd-workspace docs/plans/2026-07-06-widget-export.md` +or checking `.superpowers/sdd/2026-07-06-widget-export/` directly — and +treated the identity first line as the authority on ledger ownership. + +**S1 GREEN resolution shape, per rep** (expected shape: plan-scoped +workspace resolution without commit-content forensics): + +- **rep1 (9):** structural decision plus git-log correlation of the stray + ledger's cited hashes to commit subjects (never fetched diffs): "an + unidentified stray ledger at the old flat path belongs to another plan — + disregarded as evidence for this plan"; the plan-A scoped ledger's + identity line "proves ledger #2 is that plan's leftover duplicate, not + mine." +- **rep2 (11):** purely structural: the flat ledger "has no `# SDD ledger — + plan: …` identity line. Per skill rule, a flat-path ledger is another + plan's stray progress — not mine, left untouched." +- **rep3 (9):** purely structural; noted the flat ledger is "byte-identical + to the widget-backend ledger" and left both foreign artifacts untouched. +- **rep4 (7):** structural with a light hash-to-`git log` cross-reference; + own workspace resolved via the script and found empty; both stale + artifacts "left in place untouched — not mine." +- **rep5 (12):** purely structural; the workspace "did not exist until the + script created it just now," flat ledger rejected on the missing header + alone. + +None of the five fetched a cited commit's diff to match its content +against the other plan's file — the v2/probe rounds' signature forensic +move. All five dispatched plan B Task 1; none claimed any plan-B task +complete; both stale artifacts were left in place (per the skill's "leave +it in place and start your own, fresh"). + +**S2 GREEN (regression):** 5/5 recognized Tasks 1-2 as complete from the +identity-lined ledger, cross-checked the two cited commits against `git +log` (commit-level, consistent with the ledger's own recovery-map role), +and dispatched Task 3. No rep re-dispatched completed work; no rep +rejected the legitimate ledger — the failure mode that sank the v1/v2 S2 +controls did not recur on the truthful fixture, in either the control or +the GREEN arm. + +**Refinement iterations:** none. All three gates passed on the first run; +no SKILL.md wording changes were made during this eval round. + +## Appendix A: fixture generator (v3) + +The generator **as actually used** for every fixture in this round. Delta +from the plan text: the single fix described under Fixture iterations — +`ci` is persisted in a per-invocation counter file (`SELF_DIR`/`CI_FILE` +lines and the two-line read/write inside `commit_file`) instead of a plain +shell variable that command substitution discards; everything else is +verbatim from the plan. + +```bash +#!/usr/bin/env bash +# Build a throwaway git repo simulating a project where SDD ran plan A +# (widget backend) to completion and a controller is resuming follow-up +# plan B (widget export). v3: every ledger claim survives content +# inspection — cited commits are real, resolvable, authored by rotating +# identities at spread timestamps, and their diffs genuinely satisfy the +# task specs they claim (v2's stubs were ruled "false records" by scenario +# agents). Plans A and B both have 5 tasks so numbering is not a tell. +# +# Usage: make-fixture.sh SCENARIO LAYOUT DEST +# SCENARIO: s1 (stale ledger from a different plan) | s2 (same-plan resume) +# LAYOUT: flat (released layout: .superpowers/sdd/progress.md) +# scoped (new layout: .superpowers/sdd//progress.md, +# PLUS leftover flat + sibling litter for s1) +# DEST: directory to create the repo in +set -euo pipefail +scenario=$1 layout=$2 dest=$3 + +# Fix vs. the plan text (2026-07-06, controller-authorized): commit_file is +# called via command substitution, which forks a subshell, so `ci=$((ci+1))` +# on a plain shell variable never propagated back — every commit took the +# odd/Dana branch at the same T11 timestamp, failing the plan's own sanity +# gate (two authors across two dates). Persist ci in a fresh per-invocation +# counter file under the script's own directory (= EVAL_ROOT), initialized +# here so consecutive builds cannot bleed state into each other. +SELF_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +CI_FILE=$(mktemp "$SELF_DIR/.ci-counter.XXXXXX") +echo 0 > "$CI_FILE" + +git init -q -b main "$dest" +cd "$dest" +git config user.email eval@example.com +git config user.name eval +git config commit.gpgsign false + +BASE_DAY=2026-07-01 +commit_file() { # commit_file FILE MESSAGE -> prints short hash; FILE already written + git add "$1" + ci=$(( $(cat "$CI_FILE") + 1 )) + echo "$ci" > "$CI_FILE" + if [ $((ci % 2)) -eq 0 ]; then + GIT_AUTHOR_NAME='Sam Rivera' GIT_AUTHOR_EMAIL='sam@example.com' \ + GIT_AUTHOR_DATE="${BASE_DAY}T1${ci}:15:00" GIT_COMMITTER_DATE="${BASE_DAY}T1${ci}:16:30" \ + git commit -qm "$2" + else + GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \ + GIT_AUTHOR_DATE="${BASE_DAY}T1${ci}:05:00" GIT_COMMITTER_DATE="${BASE_DAY}T1${ci}:07:10" \ + git commit -qm "$2" + fi + git rev-parse --short HEAD +} + +mkdir -p docs/plans src + +cat > docs/plans/2026-07-01-widget-backend.md <<'EOF' +# Widget Backend Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. + +**Goal:** Build the widget inventory backend core. + +## Task 1: Storage schema + +Define the on-disk widget schema in `src/schema.py`: fields `id` (int), +`name` (str), `count` (int). + +## Task 2: Validation rules + +`validate(widget) -> bool` in `src/validate.py`: exactly the schema's keys. + +## Task 3: File locking + +`locked(path)` context manager in `src/lock.py` using `fcntl.flock`. + +## Task 4: Registry load/save + +`load(path) -> list` and `save(path, items)` in `src/registry.py`, JSON on disk. + +## Task 5: Lint gate + +Add `.lint.cfg` with a 100-column limit. +EOF + +cat > src/inventory.py <<'EOF' +"""Inventory service (fixture).""" +def list_items(): + return [] +EOF + +git add -A +GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \ +GIT_AUTHOR_DATE="${BASE_DAY}T10:00:00" GIT_COMMITTER_DATE="${BASE_DAY}T10:01:00" \ + git commit -qm "chore: widget project scaffold with backend plan" + +# Plan A's five tasks, implemented for real so the ledger's claims survive +# content inspection against plan A's specs. +cat > src/schema.py <<'EOF' +SCHEMA = {"id": int, "name": str, "count": int} +EOF +a1=$(commit_file src/schema.py 'feat(backend): storage schema') + +cat > src/validate.py <<'EOF' +from schema import SCHEMA + +def validate(widget): + return set(widget) == set(SCHEMA) +EOF +a2=$(commit_file src/validate.py 'feat(backend): validation rules') + +cat > src/lock.py <<'EOF' +import fcntl +from contextlib import contextmanager + +@contextmanager +def locked(path): + with open(path, "a") as f: + fcntl.flock(f, fcntl.LOCK_EX) + try: + yield f + finally: + fcntl.flock(f, fcntl.LOCK_UN) +EOF +a3=$(commit_file src/lock.py 'feat(backend): file locking') + +cat > src/registry.py <<'EOF' +import json + +def load(path): + try: + with open(path) as f: + return json.load(f) + except FileNotFoundError: + return [] + +def save(path, items): + with open(path, "w") as f: + json.dump(items, f) +EOF +a4=$(commit_file src/registry.py 'feat(backend): registry load/save') + +cat > .lint.cfg <<'EOF' +max-line-length = 100 +EOF +a5=$(commit_file .lint.cfg 'chore(backend): lint gate') + +BASE_DAY=2026-07-06 +cat > docs/plans/2026-07-06-widget-export.md <<'EOF' +# Widget Export Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. + +**Goal:** Add CSV and JSON export of widgets to the inventory backend. + +## Task 1: Export data model + +Define `ExportRow` in `src/export_model.py` with fields `id`, `name`, `count`. + +## Task 2: CSV serializer + +`to_csv(rows) -> str` in `src/export_csv.py`, header row + one line per widget. + +## Task 3: JSON serializer + +`to_json(rows) -> str` in `src/export_json.py`, list of objects, stable key order. + +## Task 4: CLI flag + +`inventory export --format csv|json` writing to stdout. + +## Task 5: End-to-end test + +Round-trip: list -> export -> parse -> compare. +EOF +git add docs/plans/2026-07-06-widget-export.md +GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \ +GIT_AUTHOR_DATE="${BASE_DAY}T09:30:00" GIT_COMMITTER_DATE="${BASE_DAY}T09:31:00" \ + git commit -qm "docs: follow-up plan — widget export" + +plan_a_ledger_lines() { + printf 'Task 1: complete (commits %s, review clean)\n' "$a1" + printf 'Task 2: complete (commits %s, review clean)\n' "$a2" + printf 'Task 3: complete (commits %s, review clean)\n' "$a3" + printf 'Task 4: complete (commits %s, review clean)\n' "$a4" + printf 'Task 5: complete (commits %s, review clean)\n' "$a5" + printf '\n## Final whole-branch review — DONE\nNo Critical/Important findings.\n' +} + +if [ "$scenario" = s2 ]; then + # Plan B tasks 1-2 genuinely implemented to their specs, so the resume + # ledger is legitimate under content inspection. + cat > src/export_model.py <<'EOF' +class ExportRow: + def __init__(self, id, name, count): + self.id = id + self.name = name + self.count = count +EOF + b1=$(commit_file src/export_model.py 'feat(export): export data model') + + cat > src/export_csv.py <<'EOF' +def to_csv(rows): + lines = ["id,name,count"] + for r in rows: + lines.append(f"{r.id},{r.name},{r.count}") + return "\n".join(lines) +EOF + b2=$(commit_file src/export_csv.py 'feat(export): csv serializer') + + plan_b_ledger_lines() { + printf 'Task 1: complete (commits %s, review clean)\n' "$b1" + printf 'Task 2: complete (commits %s, review clean)\n' "$b2" + } +fi + +case "$scenario/$layout" in + s1/flat) + mkdir -p .superpowers/sdd + plan_a_ledger_lines > .superpowers/sdd/progress.md + ;; + s1/scoped) + # Post-upgrade worst case: legacy flat ledger litter AND plan A's own + # completed scoped workspace both present. + mkdir -p .superpowers/sdd/2026-07-01-widget-backend + printf '*\n' > .superpowers/sdd/.gitignore + plan_a_ledger_lines > .superpowers/sdd/progress.md + { + printf '# SDD ledger — plan: docs/plans/2026-07-01-widget-backend.md\n\n' + plan_a_ledger_lines + } > .superpowers/sdd/2026-07-01-widget-backend/progress.md + ;; + s2/flat) + mkdir -p .superpowers/sdd + plan_b_ledger_lines > .superpowers/sdd/progress.md + ;; + s2/scoped) + mkdir -p .superpowers/sdd/2026-07-06-widget-export + printf '*\n' > .superpowers/sdd/.gitignore + { + printf '# SDD ledger — plan: docs/plans/2026-07-06-widget-export.md\n\n' + plan_b_ledger_lines + } > .superpowers/sdd/2026-07-06-widget-export/progress.md + ;; + *) + echo "unknown scenario/layout: $scenario/$layout" >&2 + exit 2 + ;; +esac +``` + +## Appendix B: scenario prompt + +One fresh subagent per rep (model `sonnet`, subagent_type +`general-purpose`), given this prompt verbatim with only `` and +`` filled. `` was this branch's +`skills/subagent-driven-development` for the GREEN arms and the released +tree extracted from git (`git archive 4118245`) for the S2 RED control. + +``` + +This session is being continued from a previous conversation that ran out of +context and was compacted. Summary of the earlier portion: + +- You are the SDD controller for the repository at +- You had begun executing the implementation plan + docs/plans/2026-07-06-widget-export.md (relative to that repo) using the + Subagent-Driven Development skill, whose complete text and scripts are at: + +- The context filled mid-session; the durable record of progress is on disk + per the skill's Durable Progress section. + + +Continue executing the plan. Re-read the skill's SKILL.md to re-anchor on the +process, recover your place, and continue. + +Scope limit for this run: you may read anything, run git commands, and run +the skill's scripts. Do NOT dispatch any subagents and do NOT implement any +tasks. Work only up to the point where you know your execution state, then +STOP and reply with exactly this report: + +1. LEDGERS CHECKED: each progress/ledger file path you looked at, and what + you concluded from it. +2. TASKS ALREADY COMPLETE: which of YOUR plan's tasks (if any) are already + done. +3. FIRST DISPATCH: which task you will dispatch next. + +Be concrete and terse. That report is your entire deliverable. +``` + +## Limitations + +Five reps per cell is a smoke-strength signal, not a statistical one; the +scenario measures the resume decision, not a full execution; tool_uses is a +coarse cost proxy. A rerunnable harness case belongs in superpowers-evals +as follow-up. RED artifacts (verbatim replies) are preserved at the temp +paths recorded in the eval-notes history (see git log for +2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md). This round's +artifacts — the 15 fixture repos, all 15 verbatim replies +(`-repN.reply.md`, first line = tool_uses), and the as-used generator +— are preserved under the OS temp root at +`/var/folders/g6/_sjng8h14gs3xt6c7t72w0180000gn/T/tmp.eSJKC2JemT` (path +also recorded in `/tmp/sdd-eval-root-v3.path`). From 30ff376cb65a2e5cad41e5a177044fbe967ba33d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 6 Jul 2026 13:52:38 -0700 Subject: [PATCH 049/198] chore(sdd): consistency sweep for plan-scoped workspace signatures --- skills/subagent-driven-development/task-reviewer-prompt.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/subagent-driven-development/task-reviewer-prompt.md b/skills/subagent-driven-development/task-reviewer-prompt.md index 588a40227..9fb24c408 100644 --- a/skills/subagent-driven-development/task-reviewer-prompt.md +++ b/skills/subagent-driven-development/task-reviewer-prompt.md @@ -178,8 +178,8 @@ Subagent (general-purpose): - `[BASE_SHA]` — commit before this task - `[HEAD_SHA]` — current commit - `[DIFF_FILE]` — REQUIRED: the path the controller wrote the review - package to (`scripts/review-package BASE HEAD` prints the unique path it - wrote; the package never enters the controller's context) + package to (`scripts/review-package PLAN_FILE BASE HEAD` prints the unique + path it wrote; the package never enters the controller's context) **Reviewer returns:** Spec Compliance verdict (✅/❌/⚠️), Strengths, Issues (Critical/Important/Minor), Task quality verdict From df78c6bfafb55db2d17c1c61bab2b532a9aa3e09 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 16 Jul 2026 00:13:35 +0000 Subject: [PATCH 050/198] fix(hooks): dispatch the SessionStart hook via Git Bash on Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SessionStart command string starts with a quoted path, which breaks both Windows shells Claude Code may hand it to: PowerShell parses the leading quoted string as an expression and dies on the next bareword ('Unexpected token session-start', #1751), and cmd.exe's /c quote rule drops the outer quotes when the path contains a metacharacter, so a profile dir like C:\Users\Name(External) truncates the command at the '(' (#1918). Either way the bootstrap silently never loads. Declare shell: "bash" on the hook. Claude Code >= 2.1.81 then resolves Git for Windows and runs the polyglot's bash path directly — the same route it already picks when it detects Git Bash — and when Git Bash is missing it surfaces an actionable install prompt instead of a parser error. Older versions ignore the unknown key and behave exactly as before (verified live on 2.0.77 and 2.1.80). Verified end-to-end with real claude sessions: Linux (hook fires, bootstrap injected), Windows 11 + Git Bash under a path containing '(' and a space (fires, 3276-char context), and Windows 11 without Git Bash (actionable error replaces the #1751 ParserError, reproduced verbatim as control). Fixes #1751 Fixes #1918 --- hooks/hooks.json | 1 + tests/hooks/test-session-start.sh | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/hooks/hooks.json b/hooks/hooks.json index 79d8cee37..67975137a 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -7,6 +7,7 @@ { "type": "command", "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start", + "shell": "bash", "async": false } ] diff --git a/tests/hooks/test-session-start.sh b/tests/hooks/test-session-start.sh index b027f3c65..c1508290e 100755 --- a/tests/hooks/test-session-start.sh +++ b/tests/hooks/test-session-start.sh @@ -143,6 +143,27 @@ for (const forbiddenText of forbiddenTexts) { echo "SessionStart hook output tests" +# Registration shape: the hook must declare shell:"bash" so Claude Code on +# Windows dispatches via Git Bash (or fails with an actionable error) instead +# of PowerShell/cmd.exe, whose parsers break on the quoted command string +# (PowerShell ParserError; cmd.exe quote-stripping on paths with metacharacters). +if node -e ' +const hooks = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); +const entry = hooks.hooks.SessionStart[0].hooks[0]; +if (entry.shell !== "bash") { + console.error(`SessionStart hook shell is ${JSON.stringify(entry.shell)}, expected "bash"`); + process.exit(1); +} +if (!/run-hook\.cmd" session-start$/.test(entry.command)) { + console.error(`unexpected SessionStart command shape: ${entry.command}`); + process.exit(1); +} +' "$REPO_ROOT/hooks/hooks.json"; then + pass "hooks.json registers SessionStart with shell:bash dispatch" +else + fail "hooks.json registers SessionStart with shell:bash dispatch" +fi + claude_home="$(make_home claude-code)" assert_command_output \ "Claude Code emits nested SessionStart additionalContext" \ From fe0b24390e80a9bbdf0298074fab4a8d79c2553a Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 16 Jul 2026 00:14:13 +0000 Subject: [PATCH 051/198] docs(windows): document shell:bash hook dispatch and the PowerShell/CMD fallback hazards --- docs/windows/polyglot-hooks.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/windows/polyglot-hooks.md b/docs/windows/polyglot-hooks.md index 8b84f2717..d1bcb84ec 100644 --- a/docs/windows/polyglot-hooks.md +++ b/docs/windows/polyglot-hooks.md @@ -6,9 +6,18 @@ Claude Code plugins need hooks that work on Windows, macOS, and Linux. This docu ## The Problem -Claude Code runs hook commands through the system's default shell: -- **Windows**: CMD.exe +Claude Code runs hook commands through a shell: - **macOS/Linux**: bash or sh +- **Windows with Git Bash installed**: Git Bash +- **Windows without Git Bash**: PowerShell (older versions used CMD.exe) + +Neither Windows fallback shell can parse our command string: PowerShell treats +a leading quoted path as a string expression and errors on the next bareword, +and CMD.exe's `/c` quoting rules strip the outer quotes when the path contains +a metacharacter such as `(`. Our hooks therefore declare `"shell": "bash"` +(supported since Claude Code 2.1.81; older versions ignore the key), which +forces the Git Bash route and, when Git Bash is absent, produces an actionable +"install Git for Windows" error instead of a shell parser failure. This creates several challenges: @@ -42,6 +51,7 @@ hooks/ { "type": "command", "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start", + "shell": "bash", "async": false } ] From 3fe3cb0530794f0b0b613a4f015e094efd61431d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 16 Jul 2026 03:32:25 +0000 Subject: [PATCH 052/198] fix(codex): make package script and its test portable beyond macOS/bsdtar The packaging pipeline only worked on a Mac with default umask, for three stacked reasons: - The deterministic-metadata tar flags (--uid/--gid/--uname/--gname) are bsdtar spellings; GNU tar rejects them, so the tar.gz archive step died on Linux. Detect the tar flavor and use --owner=:0 --group=:0 --numeric-owner on GNU tar, which writes byte-identical ustar headers (uid/gid 0, empty uname/gname). - Staged file modes depended on two umasks canceling out: git archive masks entry modes with tar.umask (git default 0002 -> 775), and the unflagged tar extraction re-masked with the process umask (022 on macOS -> 755, but 002 elsewhere -> 775). Pin tar.umask=0022 on the archive call and extract with -p so staged modes are canonical 755/644 on every machine. - The test's timestamp assertion parsed bsdtar's -tv column layout and expected epoch 0 rendered in a US timezone ("Dec 31 1969"); GNU tar uses different columns and UTC hosts render "1970-01-01". Assert mtime == 0 via python3 tarfile instead, matching how the test already checks zip timestamps. tests/codex/test-package-codex-plugin.sh now passes on Linux/GNU tar; the bsdtar branch preserves the exact flags that passed on macOS. --- scripts/package-codex-plugin.sh | 17 +++++++++++++---- tests/codex/test-package-codex-plugin.sh | 9 +++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/scripts/package-codex-plugin.sh b/scripts/package-codex-plugin.sh index 00399f061..5308e28d9 100755 --- a/scripts/package-codex-plugin.sh +++ b/scripts/package-codex-plugin.sh @@ -230,14 +230,16 @@ prepare_metadata_root() { METADATA_ROOT="$(prepare_metadata_root "$METADATA_SOURCE")" -git -C "$REPO_ROOT" archive --format=tar "$REF" -- \ +# Pin tar.umask and extract with -p so staged modes are canonical 755/644 +# regardless of the builder's git config or process umask. +git -C "$REPO_ROOT" -c tar.umask=0022 archive --format=tar "$REF" -- \ .codex-plugin \ CODE_OF_CONDUCT.md \ LICENSE \ README.md \ assets \ skills \ - | tar -xf - -C "$STAGE" + | tar -xpf - -C "$STAGE" VERSION="$(jq -r '.version // empty' "$STAGE/.codex-plugin/plugin.json")" [[ -n "$VERSION" ]] || die "could not read version from .codex-plugin/plugin.json" @@ -298,12 +300,19 @@ case "$FORMAT" in ) ;; tar.gz) - # Match the prior official archive's deterministic tar entry metadata. + # Match the prior official archive's deterministic tar entry metadata: + # ustar entries with uid/gid 0 and empty uname/gname. GNU tar and bsdtar + # (macOS) spell those flags differently. + if tar --version 2>/dev/null | grep -q 'GNU tar'; then + TAR_METADATA_FLAGS=(--owner=:0 --group=:0 --numeric-owner) + else + TAR_METADATA_FLAGS=(--uid 0 --gid 0 --uname '' --gname '') + fi TZ=UTC find "$STAGE" -exec touch -t 197001010000 {} + ( cd "$STAGE" rm -f "$OUTPUT" - COPYFILE_DISABLE=1 tar -cf - --no-recursion --format ustar --uid 0 --gid 0 --uname '' --gname '' -T "$ARCHIVE_LIST" | + COPYFILE_DISABLE=1 tar -cf - --no-recursion --format ustar "${TAR_METADATA_FLAGS[@]}" -T "$ARCHIVE_LIST" | gzip -9n >"$OUTPUT" ) ;; diff --git a/tests/codex/test-package-codex-plugin.sh b/tests/codex/test-package-codex-plugin.sh index 62c73f1cc..947cb6db1 100755 --- a/tests/codex/test-package-codex-plugin.sh +++ b/tests/codex/test-package-codex-plugin.sh @@ -210,8 +210,13 @@ assert_equals "$tar_archive_paths" "$archive_paths" "zip and tar.gz archives con tar_task_brief_mode="$(tar -tzvf "$tar_archive" skills/subagent-driven-development/scripts/task-brief | awk '{print $1}')" assert_equals "$tar_task_brief_mode" "-rwxr-xr-x" "tar.gz archive preserves executable script mode" -tar_metadata_times="$(tar -tzvf "$tar_archive" | awk '{print $6, $7, $8}' | sort -u)" -assert_equals "$tar_metadata_times" "Dec 31 1969" "tar.gz archive normalizes entry timestamps" +tar_metadata_times="$(python3 - "$tar_archive" <<'PY' +import sys, tarfile +with tarfile.open(sys.argv[1]) as archive: + print(sorted({member.mtime for member in archive.getmembers()})) +PY +)" +assert_equals "$tar_metadata_times" "[0]" "tar.gz archive normalizes entry timestamps" metadata_archive="$TEST_ROOT/metadata-source.tar.gz" metadata_zip="$TEST_ROOT/metadata-source.zip" From 0634449ca6b8198556a60f0f59ae70493b13fe1b Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 16 Jul 2026 04:00:15 +0000 Subject: [PATCH 053/198] fix(tests): stop the SDD skill test flaking on timing and prose case MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tests/claude-code/test-subagent-driven-development.sh failed intermittently for two independent reasons: - Budget mismatch: the file runs 9 prompts with a 90s timeout each (810s worst case) inside the runner's 600s per-file ceiling, so slow backend days produced spurious timeouts. Raise the runner default to 900s and fix the help text, which claimed the default was 300. - Case-sensitive prose matching: the assert helpers grepped free-form model output case-sensitively, but models capitalize the skill's own headings — observed failures include "Do Not Trust the Report" missing pattern "not trust" and a structured answer missing "First:.*spec.*compliance". Match case-insensitively in assert_contains/assert_not_contains/assert_count/assert_order, widen two Test 5 keyword patterns to phrasings observed in real runs, and make assert_order dump the output on failure the way assert_contains already does, so the next flake is diagnosable. Observed 3 failures across 4 runs before the change (timeout, two distinct pattern misses); 3/3 consecutive full runs pass after it. --- tests/claude-code/run-skill-tests.sh | 5 +++-- tests/claude-code/test-helpers.sh | 16 +++++++++++----- .../test-subagent-driven-development.sh | 4 ++-- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/tests/claude-code/run-skill-tests.sh b/tests/claude-code/run-skill-tests.sh index c94cfec9e..83217cdad 100755 --- a/tests/claude-code/run-skill-tests.sh +++ b/tests/claude-code/run-skill-tests.sh @@ -25,7 +25,8 @@ fi # Parse command line arguments VERBOSE=false SPECIFIC_TEST="" -TIMEOUT=600 # Default 10 minute timeout per test +TIMEOUT=900 # Per-test-file budget; must exceed the file's worst case + # (test-subagent-driven-development.sh: 9 prompts x 90s each) RUN_INTEGRATION=false while [[ $# -gt 0 ]]; do @@ -52,7 +53,7 @@ while [[ $# -gt 0 ]]; do echo "Options:" echo " --verbose, -v Show verbose output" echo " --test, -t NAME Run only the specified test" - echo " --timeout SECONDS Set timeout per test (default: 300)" + echo " --timeout SECONDS Set timeout per test (default: 900)" echo " --integration, -i Run integration tests (slow, 10-30 min)" echo " --help, -h Show this help" echo "" diff --git a/tests/claude-code/test-helpers.sh b/tests/claude-code/test-helpers.sh index 1b5ead3b4..9e187610d 100755 --- a/tests/claude-code/test-helpers.sh +++ b/tests/claude-code/test-helpers.sh @@ -30,12 +30,14 @@ run_claude() { # Check if output contains a pattern # Usage: assert_contains "output" "pattern" "test name" +# Matching is case-insensitive: patterns are prose keywords, and models +# freely capitalize skill terms ("Do Not Trust", "Spec Compliance"). assert_contains() { local output="$1" local pattern="$2" local test_name="${3:-test}" - if echo "$output" | grep -q "$pattern"; then + if echo "$output" | grep -qi "$pattern"; then echo " [PASS] $test_name" return 0 else @@ -54,7 +56,7 @@ assert_not_contains() { local pattern="$2" local test_name="${3:-test}" - if echo "$output" | grep -q "$pattern"; then + if echo "$output" | grep -qi "$pattern"; then echo " [FAIL] $test_name" echo " Did not expect to find: $pattern" echo " In output:" @@ -74,7 +76,7 @@ assert_count() { local expected="$3" local test_name="${4:-test}" - local actual=$(echo "$output" | grep -c "$pattern" || echo "0") + local actual=$(echo "$output" | grep -ci "$pattern" || echo "0") if [ "$actual" -eq "$expected" ]; then echo " [PASS] $test_name (found $actual instances)" @@ -98,16 +100,20 @@ assert_order() { local test_name="${4:-test}" # Get line numbers where patterns appear - local line_a=$(echo "$output" | grep -n "$pattern_a" | head -1 | cut -d: -f1) - local line_b=$(echo "$output" | grep -n "$pattern_b" | head -1 | cut -d: -f1) + local line_a=$(echo "$output" | grep -ni "$pattern_a" | head -1 | cut -d: -f1) + local line_b=$(echo "$output" | grep -ni "$pattern_b" | head -1 | cut -d: -f1) if [ -z "$line_a" ]; then echo " [FAIL] $test_name: pattern A not found: $pattern_a" + echo " In output:" + echo "$output" | sed 's/^/ /' return 1 fi if [ -z "$line_b" ]; then echo " [FAIL] $test_name: pattern B not found: $pattern_b" + echo " In output:" + echo "$output" | sed 's/^/ /' return 1 fi diff --git a/tests/claude-code/test-subagent-driven-development.sh b/tests/claude-code/test-subagent-driven-development.sh index d8f3e10ce..151fc64d0 100755 --- a/tests/claude-code/test-subagent-driven-development.sh +++ b/tests/claude-code/test-subagent-driven-development.sh @@ -96,13 +96,13 @@ echo "Test 5: Spec compliance reviewer mindset..." output=$(run_claude "What is the spec compliance reviewer's attitude toward the implementer's report in subagent-driven-development?" "$CLAUDE_PROMPT_TIMEOUT") -if assert_contains "$output" "not trust\|don't trust\|skeptical\|verify.*independently\|suspiciously" "Reviewer is skeptical"; then +if assert_contains "$output" "not.*trust\|don't trust\|skeptical\|verify.*independently\|suspiciously" "Reviewer is skeptical"; then : # pass else exit 1 fi -if assert_contains "$output" "read.*code\|inspect.*code\|verify.*code" "Reviewer reads code"; then +if assert_contains "$output" "read.*code\|inspect.*code\|verify.*code\|read.*diff\|trust.*diff" "Reviewer reads code"; then : # pass else exit 1 From bea92dce1a6ccd2f3fc7470b4a2a28a93e461b32 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 15 Jul 2026 11:11:02 -0700 Subject: [PATCH 054/198] docs(specs): SDD fix-loop redesign design spec Review-fix loop gets resume-the-implementer semantics, scoped re-reviews, a five-round circuit breaker, and controller adjudication at trip. SKILL.md reorganizes by lifecycle; Red Flags converts to a rationalization table. Brainstormed with Jesse 2026-07-15. --- ...2026-07-15-sdd-fix-loop-redesign-design.md | 196 ++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-15-sdd-fix-loop-redesign-design.md diff --git a/docs/superpowers/specs/2026-07-15-sdd-fix-loop-redesign-design.md b/docs/superpowers/specs/2026-07-15-sdd-fix-loop-redesign-design.md new file mode 100644 index 000000000..89e3e24bf --- /dev/null +++ b/docs/superpowers/specs/2026-07-15-sdd-fix-loop-redesign-design.md @@ -0,0 +1,196 @@ +# SDD Fix-Loop Redesign — Design Spec + +**Status:** Approved design (brainstormed with Jesse 2026-07-15); implementation +plan to follow. +**Objective:** make the subagent-driven-development skill's review-fix loop +convergent and autonomous, and make the document readable, without rewriting +its eval-tuned language. +**Hard invariant:** existing eval-tuned sentences move; they do not get +reworded. New machinery ships with drill evidence. + +## Problems + +Four, all observed in real sessions: + +1. **Pathological review loops.** The loop is literally "Repeat until + approved" — no round cap. Each re-review is a fresh full review of the + whole diff, so a nondeterministic frontier reviewer surfaces new findings + every round instead of verifying fixes. Result: implement, review, fix, + review, review, fix, review, fix — with no circuit breaker. The + strict-cost spec (2026-06-10) independently measured review-loop count as + the biggest run-to-run cost variance. +2. **Contradictory fix policy.** The process diagram and "Constructing + Reviewer Prompts" dispatch dedicated fix subagents; Red Flags says + "Implementer (same subagent) fixes them"; implementer-prompt.md's "After + Review Findings" section assumes the implementer will be re-engaged. Three + answers to "who fixes?" in one skill. +3. **Accreted structure.** Thirteen top-level sections; guidance for one + activity is scattered across four of them. "Constructing Reviewer Prompts" + is a grab-bag holding reviewer guidance, fix policy, final-review policy, + and plan-conflict adjudication. +4. **Red Flags format.** Seven sibling skills use the `| Excuse | Reality |` + rationalization table; SDD carries a 17-bullet "Never" list plus three + "If X" mini-blocks. + +## Design Decisions + +| # | Decision | Rationale | +|---|----------|-----------| +| 1 | The original implementer fixes its own review findings — resume it in place. | It already holds the task context; ownership beats a drive-by patcher. Fresh "fix subagents" rebuild context per finding and lack the task frame. | +| 2 | Re-reviews are scoped to the findings. | Fresh full reviews each round are the churn engine. Scoped re-reviews make the loop structurally convergent; the final whole-branch review remains the broad safety net. | +| 3 | Circuit breaker at five fix rounds: three resumes, then two fresh dispatches on a more capable model. | Jesse's call. A loop that survives three resumes usually means the implementer cannot see its own problem — the fresh capable dispatch de-anchors and capability-bumps in one move. | +| 4 | At trip, the controller adjudicates and routes. No new human checkpoint — structural failures reach the existing BLOCKED stop. | SDD's point is autonomous execution. The controller holds the plan and cross-task context the reviewer lacks; the existing text already sanctions it ("adjudicate it in the review loop") without ever specifying the mechanism. | +| 5 | Reorganize SKILL.md by lifecycle, preserving tuned sentences. | Fixes "hard to follow" at the root. Content moves to its point of use, matching the house direction (recent commits fold recap sections into points of use). | +| 6 | Convert Red Flags to a `| Excuse | Reality |` rationalization table; relocate hard rules to their points of use. | Matches the other seven skills. Excuses get rebuttals; rules get enforced where the reader acts. | + +## The Fix Loop + +Trigger: a task review returns spec ❌ or any Critical/Important finding. + +**Rounds 1–3 — resume the original implementer.** Send the findings verbatim +(Critical/Important plus spec gaps). The implementer fixes, re-runs the +covering tests, appends the fix report to its existing report file, and +returns the short contract. On a harness without agent resume, a "resume" is +a fresh dispatch carrying the brief, the report file, and the findings — the +report file is the persistent memory either way. + +**Rounds 4–5 — fresh implementer, more capable model.** Full task context: +brief, report file, open findings, and the framing "a prior implementer +attempted this N times; you own the task now." + +**Every round's re-review is scoped.** The re-reviewer receives the brief, +the updated report, the original findings list, and a fix-scoped diff package +(`review-package FIX_BASE HEAD`, where FIX_BASE is the head the reviewer +last reviewed; the script already takes arbitrary ranges). +It verdicts each finding addressed / not addressed and flags new breakage in +the fix diff only. Novel findings on code the fix did not touch are reported +as non-blocking; the controller ledgers them for the final review. + +**Fix-report completeness gate (existing rule, kept):** before dispatching a +re-review, confirm the fix report names the covering tests, the command run, +and the output. + +**No early exit.** The controller never adjudicates before the cap — an early +exit reopens the "pre-judge findings to spare yourself a review loop" hole +the current content deliberately closed. One exception, unchanged from +today: a finding that conflicts with what the plan's text mandates goes to +the human immediately (plan authority, not loop churn). + +**Minor findings** never enter the loop: ledger them as they arrive (existing +rule, kept). + +### Adjudication at Trip + +After round five fails, the controller stops dispatching and judges each open +finding against the brief, the plan, and cross-task context: + +- **Contested or wrong** → ledger with a one-line adjudication ("controller: + reviewer wrong because X"), continue. The final review sees both sides. +- **Real, not load-bearing** → ledger as known-open, continue. Later + dispatches touching that area carry a pointer to the entry. +- **Real and load-bearing** (later tasks build on it, or it reveals a plan + defect) → the existing BLOCKED stop. Park-and-continue defers a structural + failure to the most expensive point and lets dependents build on it, so + structural failures stop the run — through the stop condition that already + exists, not a new checkpoint. + +Every adjudication is a ledger entry. Silent discards stay forbidden. + +## Document Restructure + +New skeleton, in execution order: + +1. Intro — why subagents, core principle, narration, continuous execution +2. When to Use — unchanged, including the decision graph +3. The Process — diagram updated for the new loop +4. Setup — worktree, ledger check/resume, pre-flight plan review, todos +5. Model Selection — stays one cross-cutting section; every dispatch + consults it, so folding it into points of use would repeat it five times +6. The Task Loop — five numbered steps: + 1. Dispatch the implementer (task-brief script, five-part dispatch + composition, model line required) + 2. Handle the report (DONE / DONE_WITH_CONCERNS / NEEDS_CONTEXT / BLOCKED) + 3. Review the task (review-package script, reviewer dispatch composition, + constraints lens, no pre-judging, ⚠️ handling) + 4. Fix loop (the machinery above) + 5. Complete the task (ledger append, todo update) +7. Final Review — package, model pin, one fix wave, one scoped re-review, + adjudication +8. Finish — finishing-a-development-branch +9. Common Rationalizations — the table +10. Example Workflow — updated to show a resume-based fix round and the + breaker not tripping + +"Constructing Reviewer Prompts," "File Handoffs," and "Durable Progress" +dissolve into the steps where each rule applies. Every eval-tuned sentence +lands in exactly one new location; a move map in the implementation plan +tracks source → destination so review can verify nothing was dropped or +reworded. + +## Rationalization Table + +Excuse-shaped Never items convert to rows; new rows cover the loop +pathology. Draft rows (final wording at implementation): + +| Excuse | Reality | +|--------|---------| +| "Close enough on spec compliance" | Reviewer found gaps = not done. | +| "I'll fix it myself, dispatching is overhead" | Controller fixes pollute your context and skip review. Resume the implementer. | +| "One more round will converge" | Past the cap, rounds don't converge. Adjudicate. | +| "The reviewer will just find something new anyway" | Scoped re-reviews check fixes, not taste. New findings on untouched code go to the ledger, not the loop. | +| "This finding is obviously wrong, I'll drop it" | You adjudicate only at the cap, and every adjudication is a ledger entry. Silent discards are forbidden. | +| "The fix was small, skip the re-review" | Unreviewed fixes are how regressions land. | + +Hard rules that are not excuses (never parallel implementers, never dispatch +a reviewer without a diff file, model line required, never re-dispatch +ledger-complete tasks) move to their points of use. + +## Prompt Templates + +- **implementer-prompt.md** — "After Review Findings" rewritten for resume + semantics: you will be resumed with findings; fix, re-run covering tests, + append to your report file, return the short contract. +- **task-reviewer-prompt.md** — initial review only; the trailing re-review + sentence moves out. +- **re-review-prompt.md (new)** — the scoped re-review contract: inputs are + brief, updated report, original findings, fix-scoped diff package; output + is a per-finding verdict (addressed / not addressed), new breakage in the + fix diff, and non-blocking observations outside it. A separate template + because it is a different contract — overloading the full-review template + produced the current ambiguity. +- **Takeover dispatch (rounds 4–5)** — composed from implementer-prompt.md + plus SKILL.md guidance (brief, report path, open findings, takeover + framing); no new template file. + +## Final Review Loop + +Unchanged: merge-base package, most capable model, ONE fixer with the +complete findings list. New: exactly one scoped re-review of the fix wave, +then controller adjudication. Residual load-bearing findings surface at +finishing-a-development-branch, where the human already is. The end of the +branch gets a bounded loop too. + +## Evals + +Three new drill scenarios in `evals/`: + +1. **Resume, don't re-dispatch:** a task review returns findings; the + controller must resume the same implementer rather than dispatch a fix + subagent. +2. **Breaker trips:** a seeded never-satisfied reviewer; the controller must + stop dispatching after the fifth round fails, adjudicate, ledger, and + continue — not loop. +3. **Structural finding stops:** a load-bearing finding (later tasks depend + on it); the controller must stop via BLOCKED rather than park. + +Plus before/after runs of the existing SDD scenarios to catch regressions +from the reorganization. + +## Non-Goals + +- Ledger session-scoping — PR #1943 owns it. This work touches the same + sections, so the implementation plan notes the collision risk. +- Script changes — task-brief and review-package already do what the new + loop needs. +- Changes to executing-plans or requesting-code-review beyond the final- + review pointer continuing to resolve. From eb1ff1f11f083ddd1a03e34d7e8f2d60f9d07f3c Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 15 Jul 2026 11:28:08 -0700 Subject: [PATCH 055/198] docs(plans): SDD fix-loop redesign implementation plan Eight tasks across two repos: new re-review template, template/reference alignment, full SKILL.md lifecycle restructure with move map, two seeded-ledger fixture helpers, three quorum scenarios, and the RED/GREEN/ regression live-run campaign. --- .../plans/2026-07-15-sdd-fix-loop-redesign.md | 1649 +++++++++++++++++ 1 file changed, 1649 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-15-sdd-fix-loop-redesign.md diff --git a/docs/superpowers/plans/2026-07-15-sdd-fix-loop-redesign.md b/docs/superpowers/plans/2026-07-15-sdd-fix-loop-redesign.md new file mode 100644 index 000000000..93fdc82ea --- /dev/null +++ b/docs/superpowers/plans/2026-07-15-sdd-fix-loop-redesign.md @@ -0,0 +1,1649 @@ +# SDD Fix-Loop Redesign 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:** Make subagent-driven-development's review-fix loop convergent and autonomous (resume-the-implementer fix rounds, scoped re-reviews, five-round breaker, controller adjudication) and reorganize its SKILL.md by lifecycle — with quorum eval evidence. + +**Architecture:** Two repos. The `superpowers` repo (branch `sdd-fix-loop-redesign`, already created; spec committed) gets the skill restructure: one new prompt template, two template edits, one reference edit, and the SKILL.md rewrite whose full text is in Task 3. The `superpowers-evals` repo (`evals/` checkout; create branch `sdd-fix-loop-scenarios` off `main`) gets two seeded-ledger fixture helpers and three scenarios, then a live before/after campaign. + +**Tech Stack:** Markdown skill content; Bash scenario DSL (`story.md`/`setup.sh`/`checks.sh`); TypeScript setup-helpers on Bun (`bun test`); quorum live runs. + +**Design spec:** `docs/superpowers/specs/2026-07-15-sdd-fix-loop-redesign-design.md`. Read it before starting any task. + +## Global Constraints + +- **Verbatim-move rule:** eval-tuned sentences from the current SKILL.md move unchanged. Only fix-policy language may be reworded, and every rewording appears in Task 3's move map. Do not "improve" moved prose. +- **Round cap:** 5 fix rounds per task. Rounds 1–3 resume the original implementer; rounds 4–5 dispatch a fresh implementer on a more capable model. Adjudication happens only at the cap; the one earlier exit is a finding that conflicts with plan text (human decides, existing behavior). +- **Ledger line formats** (exact — scenarios grep for these; `` = 7-char short SHA): + - `Task : complete (commits .., review clean)` + - `Task : complete (commits .., parked)` + - `Task : fix round /5 ( addressed, open — [; …]; commits ..)` + - `Task : minor (deferred): ` + - `Task : parked — — ruling: ` + - `Task : BLOCKED — ` + - Resume rule: a task is DONE iff it has a `Task : complete` line. +- **Template placeholders** keep the existing bracket convention: `[MODEL]`, `[BRIEF_FILE]`, `[REPORT_FILE]`, `[BASE_SHA]`, `[HEAD_SHA]`, `[DIFF_FILE]`, `[GLOBAL_CONSTRAINTS]`; the new re-review template adds `[FINDINGS]`, `[FIX_BASE_SHA]`. +- **Commit discipline:** superpowers commits on `sdd-fix-loop-redesign`; evals commits on `sdd-fix-loop-scenarios` (separate repo — `cd evals` first). Never commit one repo's work from the other. +- **Static gates before any live run:** `bun run check` and `bun run quorum check` pass in `evals/`. +- **Live runs are trusted-maintainer operations** — they need `SUPERPOWERS_ROOT`, an `ANTHROPIC_API_KEY`, and cost real money (~$3–15 per SDD run). Task 8 marks them explicitly. +- **Collision note:** PR #1943 (ledger session-scoping) touches the same Durable Progress content this plan relocates into Setup. Do not absorb #1943; if it lands mid-execution, rebase and re-place its lines using the move map. + +## File Structure + +**superpowers repo:** +- Create: `skills/subagent-driven-development/re-review-prompt.md` — scoped re-review contract (Task 1) +- Modify: `skills/subagent-driven-development/implementer-prompt.md` — resume semantics (Task 2) +- Modify: `skills/subagent-driven-development/task-reviewer-prompt.md` — initial review only (Task 2) +- Modify: `skills/using-superpowers/references/codex-tools.md` — implementer close timing (Task 2) +- Modify: `skills/subagent-driven-development/SKILL.md` — full restructure (Task 3) + +**superpowers-evals repo (`evals/`):** +- Modify: `src/setup-helpers/sdd-fixtures.ts` — add `scaffoldSddMidloopParked`, `scaffoldSddMidloopStructural` (Task 4) +- Modify: `src/setup-helpers/registry.ts` — register both helpers (Task 4) +- Modify: `test/setup-helpers-sdd.test.ts` — unit tests for both helpers (Task 4) +- Create: `scenarios/sdd-fix-loop-resumes-implementer/{story.md,setup.sh,checks.sh}` (Task 5) +- Create: `scenarios/sdd-breaker-adjudicates-at-cap/{story.md,setup.sh,checks.sh}` (Task 6) +- Create: `scenarios/sdd-breaker-structural-blocks/{story.md,setup.sh,checks.sh}` (Task 7) +- Create: `docs/experiments/2026-07-sdd-fix-loop-redesign.md` — campaign log (Task 8) + +--- + +### Task 1: Create the scoped re-review template + +**Files:** +- Create: `skills/subagent-driven-development/re-review-prompt.md` + +**Interfaces:** +- Produces: template placeholders `[MODEL]`, `[BRIEF_FILE]`, `[REPORT_FILE]`, `[FINDINGS]`, `[FIX_BASE_SHA]`, `[HEAD_SHA]`, `[DIFF_FILE]` — Task 3's SKILL.md step 4 links this file and instructs the controller to fill exactly these. + +- [ ] **Step 1: Write the file with exactly this content** + +````markdown +# Scoped Re-Review Prompt Template + +Use this template when dispatching a re-review after a fix round. The +re-reviewer verifies the findings were addressed and checks the fix diff for +new breakage. It is not a fresh review — the full review already happened. + +**Purpose:** Verify each finding from the previous review was addressed, and +that the fix itself broke nothing. + +``` +Subagent (general-purpose): + description: "Re-review Task N fix round R" + model: [MODEL — REQUIRED: choose per SKILL.md Model Selection; an omitted + model silently inherits the session's most expensive one] + prompt: | + You are re-reviewing one task's fix round. A previous review produced + findings; an implementer has attempted to fix them. Your job is to + verdict each finding and inspect the fix diff — nothing else. + + ## The Task + + Read the task brief: [BRIEF_FILE] + + ## The Findings Under Verification + + [FINDINGS] + + ## The Fix + + Read the implementer's report (fix reports are appended at the end): + [REPORT_FILE] + + **Fix base:** [FIX_BASE_SHA] (the head the previous review saw) + **Head:** [HEAD_SHA] + **Diff file:** [DIFF_FILE] + + Read the diff file once — it contains the fix commits, a stat summary, + and the fix diff with surrounding context. Do not re-run git commands. + If the diff file is missing, fetch the diff yourself: + `git diff --stat [FIX_BASE_SHA]..[HEAD_SHA]` and + `git diff [FIX_BASE_SHA]..[HEAD_SHA]`. + + Your review is read-only on this checkout. Do not mutate the working + tree, the index, HEAD, or branch state in any way. + + ## Scope + + Your scope is the findings list and the fix diff. Verdict every finding. + Inspect the fix diff for new problems the fix itself introduced. Do NOT + re-review code the fix did not touch: if you notice an issue entirely + outside the fix diff, report it under Out-of-Scope Observations — it + does not block this task and does not extend the loop. A broad + whole-branch review happens after all tasks are complete. + + ## Tests + + The implementer re-ran the tests covering the amended code and appended + the results to the report file. Treat the report as unverified claims: + confirm the fix report names the covering tests and shows their output, + and verify the claims against the diff. Do not re-run the suite to + confirm their report. Run a test only when reading the code raises a + specific doubt that no existing run answers — and then a focused test, + never a package-wide suite. + + ## Output Format + + Your final message is the report itself: begin directly with the first + finding's verdict. Every line is a verdict, a finding with file:line, + or a check you ran — no preamble, no process narration. + + ### Finding Verdicts + + For each finding in The Findings Under Verification, in order: + - **[finding one-liner]** — ADDRESSED | NOT ADDRESSED, with file:line + evidence. "Attempted" is not addressed: the specific defect must no + longer exist. + + ### New Breakage in the Fix Diff + + Anything the fix itself broke or introduced, with severity + (Critical/Important/Minor) and file:line. "None" if clean. + + ### Out-of-Scope Observations + + Issues you noticed entirely outside the fix diff. Non-blocking; the + controller ledgers these for the final review. "None" if none. + + ### Verdict + + **Fix round:** [All findings addressed, no new Critical/Important + breakage | Findings remain open] — list the open ones. +``` + +**Placeholders:** +- `[MODEL]` — REQUIRED: reviewer model per SKILL.md Model Selection; scoped + re-reviews of small fix diffs take a cheap-to-mid tier +- `[BRIEF_FILE]` — the task brief file (same file the implementer worked from) +- `[FINDINGS]` — the Critical/Important findings and spec gaps from the + previous review, copied verbatim, one per bullet +- `[REPORT_FILE]` — the implementer's report file (fix reports appended) +- `[FIX_BASE_SHA]` — the head the previous review saw +- `[HEAD_SHA]` — current commit +- `[DIFF_FILE]` — the path `scripts/review-package FIX_BASE HEAD` printed + +**Re-reviewer returns:** per-finding verdicts (ADDRESSED / NOT ADDRESSED), +new breakage in the fix diff, out-of-scope observations, and a round verdict. +```` + +- [ ] **Step 2: Verify the file parses as the other templates do** + +Run: `grep -c '^\[MODEL' skills/subagent-driven-development/re-review-prompt.md` +Expected: `0` (placeholder docs use `- \`[MODEL]\`` list form, matching task-reviewer-prompt.md) + +Run: `grep -n 'FIX_BASE_SHA' skills/subagent-driven-development/re-review-prompt.md | head -3` +Expected: hits in the prompt body and the placeholder list. + +- [ ] **Step 3: Commit** + +```bash +git add skills/subagent-driven-development/re-review-prompt.md +git commit -m "feat(sdd): add scoped re-review prompt template" +``` + +--- + +### Task 2: Align the implementer and task-reviewer templates and the Codex reference with resume semantics + +**Files:** +- Modify: `skills/subagent-driven-development/implementer-prompt.md` (the "After Review Findings" section) +- Modify: `skills/subagent-driven-development/task-reviewer-prompt.md` (trailing paragraph) +- Modify: `skills/using-superpowers/references/codex-tools.md` (subagent close timing) + +**Interfaces:** +- Consumes: `re-review-prompt.md` exists (Task 1). +- Produces: the implementer contract Task 3's fix loop cites ("fix, re-run covering tests, append to your report file, return the short contract"). + +- [ ] **Step 1: Replace the "After Review Findings" section in implementer-prompt.md** + +Old text (exact): + +```markdown + ## After Review Findings + + If a reviewer finds issues and you fix them, re-run the tests that cover + the amended code and append the results to your report file. Reviewers + will not re-run tests for you — your report is the test evidence. +``` + +New text (exact): + +```markdown + ## After Review Findings + + If the task review finds issues, you will be resumed with the findings. + Fix them, re-run the tests that cover the amended code, and append a fix + report to your report file: what you changed, the covering tests you + ran, the command, and the output. Reviewers will not re-run tests for + you — your report is the test evidence. Then reply with the same short + status contract as your first report. +``` + +- [ ] **Step 2: Delete the trailing re-review paragraph in task-reviewer-prompt.md** + +Delete this text (exact, at end of file): + +```markdown +A fix dispatch can address spec gaps and quality findings together; +re-review after fixes covers both verdicts. +``` + +Nothing replaces it — the scoped re-review contract now lives in +`re-review-prompt.md`, and SKILL.md step 4 (Task 3) owns the loop rules. + +- [ ] **Step 3: Update the Codex subagent close-timing sentence in codex-tools.md** + +Old text (exact, line 10): + +```markdown +When using subagent-driven-development, you should always close implementer and reviewer subagents when they have finished all their work. +``` + +New text (exact): + +```markdown +When using subagent-driven-development, close reviewer subagents when their review returns. Keep each implementer subagent open until its task's review passes — the fix loop resumes the implementer — then close it. If your harness cannot send another message to a spawned agent, dispatch each fix round as a fresh implementer carrying the brief, the report file, and the findings. +``` + +- [ ] **Step 4: Verify no template still references dedicated fix subagents** + +Run: `grep -rn "fix subagent" skills/subagent-driven-development/*.md` +Expected: no output (SKILL.md still has hits until Task 3 — this command scopes to templates only after Task 3; at this point expect hits ONLY in SKILL.md). + +Run: `grep -rn "fix subagent" skills/subagent-driven-development/implementer-prompt.md skills/subagent-driven-development/task-reviewer-prompt.md skills/subagent-driven-development/re-review-prompt.md` +Expected: no output. + +- [ ] **Step 5: Commit** + +```bash +git add skills/subagent-driven-development/implementer-prompt.md skills/subagent-driven-development/task-reviewer-prompt.md skills/using-superpowers/references/codex-tools.md +git commit -m "feat(sdd): align templates and codex reference with resume-based fix rounds" +``` + +--- + +### Task 3: Restructure SKILL.md by lifecycle with the fix loop and rationalization table + +**Files:** +- Modify: `skills/subagent-driven-development/SKILL.md` (full-file replacement; new text below) + +**Interfaces:** +- Consumes: all three templates (Tasks 1–2); `scripts/task-brief`, `scripts/review-package`, `scripts/sdd-workspace` (unchanged). +- Produces: the ledger line formats in Global Constraints (scenarios grep them); section names `Setup`, `The Task Loop`, `Final Review`, `Common Rationalizations`. + +- [ ] **Step 1: Replace the entire SKILL.md body with exactly this content** + +`````markdown +--- +name: subagent-driven-development +description: Use when executing implementation plans with independent tasks in the current session +--- + +# Subagent-Driven Development + +Execute plan by dispatching a fresh implementer subagent per task, a task review (spec compliance + code quality) after each, and a broad whole-branch review at the end. + +**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 + task review (spec + quality) + broad final review = high quality, fast iteration + +**Narration:** between tool calls, narrate at most one short line — the +ledger and the tool results carry the record. + +**Continuous execution:** Do not pause to check in with your human partner 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) +- Review after each task (spec compliance + code quality), broad review at the end +- 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 asks questions?" [shape=diamond]; + "Answer questions, provide context" [shape=box]; + "Implementer implements, tests, commits, self-reviews" [shape=box]; + "Generate review package, dispatch task reviewer (./task-reviewer-prompt.md)" [shape=box]; + "Spec ✅ and quality approved?" [shape=diamond]; + "Finding conflicts with plan text?" [shape=diamond]; + "Ask human partner which governs" [shape=box]; + "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [shape=box]; + "Dispatch scoped re-review (./re-review-prompt.md)" [shape=box]; + "All findings addressed?" [shape=diamond]; + "R = 5?" [shape=diamond]; + "Adjudicate each open finding" [shape=box]; + "Any load-bearing finding?" [shape=diamond]; + "STOP: report BLOCKED to human partner" [shape=box]; + "Park findings in ledger with rulings" [shape=box]; + "Append completion to ledger, mark todo complete" [shape=box]; + } + + "Setup: worktree, ledger check, read plan, pre-flight review" [shape=box]; + "More tasks remain?" [shape=diamond]; + "Dispatch final code reviewer (../requesting-code-review/code-reviewer.md)" [shape=box]; + "Final findings? ONE fix dispatch, one scoped re-review, adjudicate residuals" [shape=box]; + "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen]; + + "Setup: worktree, ledger check, read plan, pre-flight review" -> "Dispatch implementer subagent (./implementer-prompt.md)"; + "Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer asks questions?"; + "Implementer asks questions?" -> "Answer questions, provide context" [label="yes"]; + "Answer questions, provide context" -> "Implementer implements, tests, commits, self-reviews"; + "Implementer asks questions?" -> "Implementer implements, tests, commits, self-reviews" [label="no"]; + "Implementer implements, tests, commits, self-reviews" -> "Generate review package, dispatch task reviewer (./task-reviewer-prompt.md)"; + "Generate review package, dispatch task reviewer (./task-reviewer-prompt.md)" -> "Spec ✅ and quality approved?"; + "Spec ✅ and quality approved?" -> "Append completion to ledger, mark todo complete" [label="yes"]; + "Spec ✅ and quality approved?" -> "Finding conflicts with plan text?" [label="no"]; + "Finding conflicts with plan text?" -> "Ask human partner which governs" [label="yes"]; + "Ask human partner which governs" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model"; + "Finding conflicts with plan text?" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [label="no"]; + "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" -> "Dispatch scoped re-review (./re-review-prompt.md)"; + "Dispatch scoped re-review (./re-review-prompt.md)" -> "All findings addressed?"; + "All findings addressed?" -> "Append completion to ledger, mark todo complete" [label="yes"]; + "All findings addressed?" -> "R = 5?" [label="no"]; + "R = 5?" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [label="no - next round"]; + "R = 5?" -> "Adjudicate each open finding" [label="yes - breaker trips"]; + "Adjudicate each open finding" -> "Any load-bearing finding?"; + "Any load-bearing finding?" -> "STOP: report BLOCKED to human partner" [label="yes"]; + "Any load-bearing finding?" -> "Park findings in ledger with rulings" [label="no"]; + "Park findings in ledger with rulings" -> "Append completion to ledger, mark todo complete"; + "Append completion to ledger, mark todo complete" -> "More tasks remain?"; + "More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"]; + "More tasks remain?" -> "Dispatch final code reviewer (../requesting-code-review/code-reviewer.md)" [label="no"]; + "Dispatch final code reviewer (../requesting-code-review/code-reviewer.md)" -> "Final findings? ONE fix dispatch, one scoped re-review, adjudicate residuals"; + "Final findings? ONE fix dispatch, one scoped re-review, adjudicate residuals" -> "Use superpowers:finishing-a-development-branch"; +} +``` + +## Setup + +Ensure the work happens in an isolated workspace: use +superpowers:using-git-worktrees to create one or verify the existing one. +Never start implementation on a main/master branch without your human +partner's explicit consent. + +Conversation memory does not survive compaction. In real sessions, +controllers that lost their place have re-dispatched entire completed task +sequences — the single most expensive failure observed. Track progress in +a ledger file, not only in todos. + +- At skill start, check for a ledger: + `cat "$(git rev-parse --show-toplevel)/.superpowers/sdd/progress.md"`. Tasks with + a `Task : complete` line are DONE — do not re-dispatch them; resume at + the first task without one. A task whose last line is a fix round is + mid-loop: resume the loop at the next round. +- The ledger is your recovery map: the commits it names exist in git even + when your context no longer remembers creating them. After compaction, + trust the ledger and `git log` over your own recollection. +- `git clean -fdx` will destroy the ledger (it's git-ignored scratch); if + that happens, recover from `git log`. + +Read the plan once, note its context and Global Constraints, and create a +todo per task. + +Before dispatching Task 1, scan the plan once for conflicts: + +- tasks that contradict each other or the plan's Global Constraints +- anything the plan explicitly mandates that the review rubric treats as a + defect (a test that asserts nothing, verbatim duplication of a logic block) + +Present everything you find to your human partner as one batched question — +each finding beside the plan text that mandates it, asking which governs — +before execution begins, not one interrupt per discovery mid-plan. If the +scan is clean, proceed without comment. The review loop remains the net for +conflicts that only emerge from implementation. + +## 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 and design tasks**: use the most capable available model. +The final whole-branch review is one of these — dispatch it on the most +capable available model, not the session default. + +**Review tasks**: choose the model with the same judgment, scaled to the +diff's size, complexity, and risk. A small mechanical diff does not need the +most capable model; a subtle concurrency change does. Scoped re-reviews of +small fix diffs take a cheap-to-mid tier. + +**Fix-loop escalation (rounds 4-5)**: use a model at least one tier above +the implementer that got stuck. + +**Always specify the model explicitly when dispatching a subagent.** An +omitted model inherits your session's model — often the most capable and +most expensive — which silently defeats this section. + +**Turn count beats token price.** Wall-clock and context cost scale with how +many turns a subagent takes, and the cheapest models routinely take 2-3× the +turns on multi-step work — costing more overall. Use a mid-tier model as the +floor for reviewers and for implementers working from prose descriptions. +When the task's plan text contains the complete code to write, the +implementation is transcription plus testing: use the cheapest tier for +that implementer. Single-file mechanical fixes also take the cheapest tier. + +**Task complexity signals (implementation tasks):** +- 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 + +## The Task Loop + +Everything you paste into a dispatch prompt — and everything a subagent +prints back — stays resident in your context for the rest of the session +and is re-read on every later turn. Hand artifacts over as files. + +### 1. Dispatch the implementer + +Record BASE (`git rev-parse HEAD`) before dispatching — the review package +and fix-round diffs need it. + +- **Task brief:** run this skill's `scripts/task-brief PLAN_FILE N` — it + extracts the task's full text to a uniquely named file and prints the + path. Compose the dispatch so the brief stays the single source of + requirements. Your dispatch should contain: (1) one line on where this + task fits in the project; (2) the brief path, introduced as "read this + first — it is your requirements, with the exact values to use verbatim"; + (3) interfaces and decisions from earlier tasks that the brief cannot + know; (4) your resolution of any ambiguity you noticed in the brief; + (5) the report-file path and report contract. Exact values (numbers, + magic strings, signatures, test cases) appear only in the brief. Never + make a subagent read the whole plan file. +- **Report file:** name the implementer's report file after the brief + (brief `…/task-N-brief.md` → report `…/task-N-report.md`) and put it in + the dispatch prompt. The implementer writes the full report there and + returns only status, commits, a one-line test summary, and concerns. +- A dispatch prompt describes one task, not the session's history. Do not + paste accumulated prior-task summaries ("state after Tasks 1-3") into + later dispatches — a real session's dispatch hit 42k chars of which 99% + was pasted history. A fresh subagent needs its task, the interfaces it + touches, and the global constraints. Nothing else. +- If an earlier task parked a finding in the area this task touches, carry + a pointer to that ledger entry in the dispatch. +- Record the implementer's agent identity from the dispatch result — + fix-loop rounds 1-3 resume this agent. +- Never dispatch multiple implementation subagents in parallel (conflicts). + +Template: [implementer-prompt.md](implementer-prompt.md) + +### 2. Handle the report + +Implementer subagents report one of four statuses. Handle each appropriately: + +**DONE:** Generate the review package (`scripts/review-package BASE HEAD`, from this skill's directory — it prints the unique file path it wrote; BASE is the commit you recorded before dispatching the implementer — never `HEAD~1`, which silently drops all but the last commit of a multi-commit task), then dispatch the task reviewer with the printed path. + +**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. + +If the implementer asks questions — before starting or mid-task — answer +clearly and completely, provide additional context if needed, and don't +rush it into implementation. + +### 3. Review the task + +Per-task reviews are task-scoped gates. The broad review happens once, at the +final whole-branch review. Never skip the task review, and never accept a +report missing either verdict — spec compliance AND task quality are both +required. Implementer self-review never replaces the task review; both are +needed. + +- Hand the reviewer its diff as a file: run this skill's + `scripts/review-package BASE HEAD` and pass the reviewer the file path + it prints (or, without bash: `git log --oneline`, `git diff --stat`, + and `git diff -U10` for the range, redirected to one uniquely named + file). The output never enters your own context, and the reviewer sees + the commit list, stat summary, and full diff with context in one Read + call. Use the BASE you recorded before dispatching the implementer — + never `HEAD~1`, which silently truncates multi-commit tasks. Never + dispatch a task reviewer without a diff file. +- The task reviewer gets three paths — the same brief file, the report + file, and the review package — plus the global constraints that bind + the task. +- The global-constraints block you hand the reviewer is its attention + lens. Copy the binding requirements verbatim from the plan's Global + Constraints section or the spec: exact values, exact formats, and the + stated relationships between components ("same layout as X", "matches + Y"). The reviewer's template already carries the process rules (YAGNI, + test hygiene, review method) — the constraints block is for what THIS + project's spec demands. +- Do not add open-ended directives like "check all uses" or "run race tests + if useful" without a concrete, task-specific reason +- Do not ask a reviewer to re-run tests the implementer already ran on the + same code — the implementer's report carries the test evidence +- Do not pre-judge findings for the reviewer — never instruct a reviewer to + ignore or not flag a specific issue. If you believe a finding would be a + false positive, let the reviewer raise it and adjudicate it in the review + loop. If the prompt you are writing contains "do not flag," "don't treat X + as a defect," "at most Minor," or "the plan chose" — stop: you are + pre-judging, usually to spare yourself a review loop. + +The task reviewer may report "⚠️ Cannot verify from diff" items — requirements +that live in unchanged code or span tasks. These do not block the rest of the +review, but you must resolve each one yourself before marking the task +complete: you hold the plan and cross-task context the reviewer +lacks. If you confirm an item is a real gap, treat it as a failed spec +review — it enters the fix loop with the other findings. + +Template: [task-reviewer-prompt.md](task-reviewer-prompt.md) + +### 4. The fix loop + +The loop triggers when the review reports spec ❌, any Critical or Important +finding, or a ⚠️ item you confirmed as a real gap. + +Before the loop starts, two routes leave it immediately: + +- Record Minor findings in the progress ledger as you go + (`Task : minor (deferred): `), and point the final + whole-branch review at that list so it can triage which must be fixed + before merge. A roll-up nobody reads is a silent discard. Minor findings + never enter the loop. +- A finding labeled plan-mandated — or any finding that conflicts with + what the plan's text requires — is the human's decision, like any plan + contradiction: present the finding and the plan text, ask which governs. + Do not dismiss the finding because the plan mandates it, and do not + dispatch a fix that contradicts the plan without asking. + +Everything else enters the loop. A fix round is one fix dispatch plus one +scoped re-review. Five rounds maximum per task: + +**Rounds 1-3 — resume the original implementer.** Send it the open findings +verbatim. Its context is intact: it knows the task, the code, and its own +choices. If your harness cannot send another message to a live subagent, +dispatch a fresh implementer carrying the brief path, the report-file path, +and the findings — the report file is the persistent memory either way. + +**Rounds 4-5 — dispatch a fresh implementer on a more capable model** (per +Model Selection), with the brief path, the report-file path, the open +findings, and this framing: "A prior implementer attempted this task +[N] times; you own it now. Read the report file for what was tried." A loop +that survives three resumes usually means the implementer cannot see its +own problem — fresh eyes and a capability bump in one move. + +**Every round, either way:** the implementer fixes, re-runs the tests +covering the amended code, appends its fix report to the same report file, +and returns the short contract. Before dispatching the re-review, confirm +the fix report contains the covering tests, the command run, and the +output; dispatch the re-review once all three are present. Name the +covering test files in the fix message — a one-line fix does not need the +whole suite. + +**The re-review is scoped.** Run `scripts/review-package FIX_BASE HEAD` +where FIX_BASE is the head the previous review saw, and dispatch +[re-review-prompt.md](re-review-prompt.md) with the findings list, the +brief, the report file, and the printed diff path. The re-reviewer verdicts +each finding ADDRESSED or NOT ADDRESSED and flags new breakage in the fix +diff only. New Critical/Important breakage in the fix diff joins the open +findings list. Out-of-scope observations go to the ledger as deferred +minors — they never extend the loop. + +**After each round,** append to the ledger: +`Task : fix round /5 ( addressed, open — ; commits ..)` + +Never fix findings yourself in the controller session — your context stays +clean for coordination, and controller fixes skip review. + +**The breaker.** When round 5's re-review still leaves findings open, stop +dispatching. Adjudicate each open finding yourself — you hold the plan and +the cross-task context the reviewer lacks: + +- **The reviewer is wrong, or the point is contestable:** park it — + `Task : parked — — ruling: `. The final + review sees both sides. +- **Real, but nothing downstream builds on it:** park it the same way, with + a ruling that says it's real and deferred. +- **Real and load-bearing** — a later task builds on it, or it reveals a + plan defect: STOP. Append `Task : BLOCKED — ` and report to + your human partner with the finding, the plan text it collides with, and + the fix history. Parking a structural failure lets every dependent task + build on it and hands the final review a problem it cannot fix either. + +Adjudicate only at the cap. Adjudicating earlier to end a loop is +pre-judging with a different name. Every adjudication is a ledger entry — +a silent discard is forbidden. + +### 5. Complete the task + +When the review comes back clean — or every open finding is parked with a +ruling at the cap — append the completion line to the ledger in the same +message as your other bookkeeping: + +- `Task : complete (commits .., review clean)` +- `Task : complete (commits .., parked)` after a + tripped breaker + +Then mark the todo complete and move on. Never move to the next task while +the review has open Critical/Important issues that are neither fixed nor +parked-with-ruling at the cap. + +## Final Review + +After all tasks complete, run +`scripts/review-package MERGE_BASE HEAD` (MERGE_BASE = the commit the +branch started from, e.g. `git merge-base main HEAD`) and include the +printed path in the final review dispatch, so the final reviewer reads +one file instead of re-deriving the branch diff with git commands. Dispatch +on the most capable available model (see Model Selection), using +superpowers:requesting-code-review's +[code-reviewer.md](../requesting-code-review/code-reviewer.md). Point it at +the ledger's deferred-minor and parked lines so it can triage which must be +fixed before merge. + +If the final whole-branch review returns findings, dispatch ONE fix +subagent with the complete findings list — not one fixer per finding. +Per-finding fixers each rebuild context and re-run suites; a real +session's final-review fix wave cost more than all its tasks combined. +Then run exactly one scoped re-review of the fix wave +(`scripts/review-package` over the fix range, [re-review-prompt.md](re-review-prompt.md)). +Adjudicate any residual findings as in the task loop's breaker: park with +rulings, or stop on load-bearing ones. There is no second fix wave — +residual load-bearing findings surface to your human partner when +finishing-a-development-branch presents the options. + +## Finish + +Use superpowers:finishing-a-development-branch. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Close enough on spec compliance" | Reviewer found spec gaps = not done. Fix or hit the cap and adjudicate — those are the only exits. | +| "I'll fix it myself, dispatching is overhead" | Controller fixes pollute your context and skip review. Resume the implementer. | +| "One more round will converge" | Past the cap, rounds don't converge — the failure is structural. Adjudicate and route. | +| "The reviewer will just find something new anyway" | Scoped re-reviews verify fixes; they cannot wander. New findings on untouched code go to the ledger, not the loop. | +| "This finding is obviously wrong, I'll drop it" | You adjudicate only at the cap, and every ruling is a ledger entry. Silent discards are forbidden. | +| "The fix was small, skip the re-review" | Unreviewed fixes are how regressions land. Every round ends with a scoped re-review. | +| "Reviews slow the loop down" | The loop without reviews is just unverified churn. Reviews are the loop's brakes and steering. | +| "Ledger bookkeeping is overhead" | The ledger is what survives compaction. Controllers without one have re-dispatched entire completed task sequences. | + +## Example Workflow + +``` +You: I'm using Subagent-Driven Development to execute this plan. + +[Setup: worktree verified, no ledger found, read plan, created todos] + +Task 1: Hook installation script + +[Run task-brief for Task 1; dispatch implementer with brief + report paths + context] + +Implementer: "Before I begin - should the hook be installed at user or system level?" + +You: "User level (~/.config/superpowers/hooks/)" + +Implementer: [Later] + - Implemented install-hook command + - Added tests, 5/5 passing + - Self-review: Found I missed --force flag, added it + - Committed + +[Run review-package, dispatch task reviewer with the printed path] +Task reviewer: Spec ✅ - all requirements met, nothing extra. + Strengths: Good test coverage, clean. Issues: None. Task quality: Approved. + +[Ledger: Task 1: complete (commits a1b2c3d..d4e5f6a, review clean)] + +Task 2: Recovery modes + +[Run task-brief for Task 2; dispatch implementer with brief + report paths + context] + +Implementer: [No questions] + - Added verify/repair modes + - 8/8 tests passing + - Committed + +[Run review-package, dispatch task reviewer with the printed path] +Task reviewer: Spec ❌: + - Missing: Progress reporting (spec says "report every 100 items") + Issues (Important): Magic number (100) + +[Fix round 1: resume the implementer with both findings] +Implementer: Added progress reporting, extracted PROGRESS_INTERVAL constant. + Re-ran test/recovery.test.js — 10/10 passing. Fix report appended. + +[Run review-package FIX_BASE HEAD; dispatch scoped re-review] +Re-reviewer: Missing progress reporting — ADDRESSED (src/recovery.js:41). + Magic number — ADDRESSED (src/recovery.js:7). New breakage: none. + Verdict: all findings addressed. + +[Ledger: Task 2: fix round 1/5 (2 addressed, 0 open; commits d4e5f6a..b7c8d9e)] +[Ledger: Task 2: complete (commits d4e5f6a..b7c8d9e, review clean)] + +... + +[After all tasks] +[Run review-package MERGE_BASE HEAD; dispatch final code-reviewer, most capable model] +Final reviewer: All requirements met. Deferred minors triaged: none block merge. + +Done! Using superpowers:finishing-a-development-branch. +``` +````` + +- [ ] **Step 2: Verify the move map — every row below must hold** + +The move map. "Verbatim" rows: the sentence(s) must appear unchanged in the +new location (allowing only the list-marker/indentation changes noted). +"Reworded" rows show the only permitted rewordings. Check each row against +the new file; fix any drift toward paraphrase. + +| Current SKILL.md (dev) | Content | New location | Disposition | +|---|---|---|---| +| lines 8-17 | intro, why-subagents, core principle, narration, continuous execution | Intro | Verbatim | +| lines 19-43 | When to Use + vs. block | When to Use | Verbatim | +| lines 47-83 | process diagram | The Process | Redrawn (new loop; old "Dispatch fix subagent…" node deleted) | +| lines 87-89 | worktree | Setup ¶1 | Verbatim + appended main/master sentence (from Never item 1) | +| lines 90-100 | pre-flight scan | Setup (last ¶s) | Verbatim | +| lines 104-133 | model selection | Model Selection | Verbatim + two additions: re-review tier sentence; "Fix-loop escalation (rounds 4-5)" block | +| lines 137-151 | implementer statuses | Task Loop §2 | Verbatim | +| lines 153-160 | ⚠️ handling | Task Loop §3 (last ¶) | Reworded ending: "send it back to the implementer and re-review" → "it enters the fix loop with the other findings" | +| lines 166-177 | no open-ended directives; no test re-runs; no pre-judging | Task Loop §3 bullets | Verbatim | +| lines 178-183 | constraints lens | Task Loop §3 bullet | Verbatim | +| lines 184-191 | diff as a file | Task Loop §3 first bullet | Verbatim + appended "Never dispatch a task reviewer without a diff file." (from Never item) | +| lines 192-196 | one-task dispatch, 42k anecdote | Task Loop §1 bullet | Verbatim | +| lines 197-201 | fix subagents for Crit/Imp; Minor→ledger | Task Loop §4 first route | Reworded first sentence: "Dispatch fix subagents for Critical and Important findings." deleted (superseded by the loop); "Record Minor findings… silent discard." kept verbatim + appended "Minor findings never enter the loop." + ledger line format | +| lines 202-205 | plan-mandated findings | Task Loop §4 second route | Verbatim | +| lines 206-210 | final review package | Final Review ¶1 | Verbatim | +| lines 211-216 | fix dispatch contract + completeness gate | Task Loop §4 "Every round" ¶ | Reworded opener: "Every fix dispatch carries the implementer contract: the fix subagent re-runs…" → "the implementer fixes, re-runs the tests covering the amended code, appends its fix report to the same report file, and returns the short contract."; the confirm-three-things sentence kept verbatim; "Name the covering test files in the dispatch" → "…in the fix message" | +| lines 217-220 | ONE final fixer | Final Review ¶2 | Verbatim + appended one-scoped-re-review + adjudication sentences (new) | +| lines 224-226 | file-handoff rationale | Task Loop preamble | Verbatim ("Hand artifacts over as files:" → "…as files.") | +| lines 227-238 | task brief 5-part dispatch | Task Loop §1 first bullet | Verbatim + appended "Never make a subagent read the whole plan file." (from Never item) | +| lines 239-242 | report file | Task Loop §1 second bullet | Verbatim | +| lines 243-245 | reviewer inputs | Task Loop §3 second bullet | Verbatim | +| lines 246-247 | fix appends to report file | Task Loop §4 "Every round" ¶ | Superseded by the reworded contract (row for 211-216); no separate sentence | +| lines 251-254 | compaction rationale | Setup ¶2 | Verbatim | +| lines 255-259 | ledger check | Setup bullet 1 | Reworded: "Tasks listed there as complete are DONE" → "Tasks with a `Task : complete` line are DONE"; appended mid-loop resume sentence (new) | +| lines 260-262 | append on clean | Task Loop §5 | Reworded to include the parked-completion variant; "in the same message as your other bookkeeping" kept verbatim | +| lines 263-265 | recovery map | Setup bullet 2 | Verbatim | +| lines 266-267 | git clean warning | Setup bullet 3 | Verbatim | +| lines 271-273 | template list | dissolved: links at §1, §3, §4, Final Review | Restated as links | +| lines 277-336 | example workflow | Example Workflow | Rewritten (shows resume round + ledger lines) | +| lines 340-360 | Never list | distributed: items 1→Setup; 2,8,11,12→§3; 4,5,6→§1; 13→§5; 14→Setup bullet 1; 3,7(answer-questions)→§2; 9,10→rationalization rows | Verbatim where moved as rules; excuse-shaped items converted to table rows | +| lines 362-366 | "If subagent asks questions" | Task Loop §2 last ¶ | Verbatim (reflowed into one sentence) | +| lines 367-371 | "If reviewer finds issues: Implementer (same subagent) fixes them…" | Task Loop §4 | Superseded — this is the contradiction the redesign resolves; the loop's rounds 1-3 ARE this policy, now specified | +| lines 372-375 | "If subagent fails task: Dispatch fix subagent…" | Task Loop §4 last sentence before breaker | Reworded: "Don't try to fix manually (context pollution)" → "Never fix findings yourself in the controller session — your context stays clean for coordination, and controller fixes skip review." | + +Run: `grep -n "fix subagent" skills/subagent-driven-development/SKILL.md` +Expected: exactly one hit — the Final Review's "dispatch ONE fix subagent" (the deliberately kept, tuned final-wave rule). + +Run: `grep -c "Task " skills/subagent-driven-development/SKILL.md` +Expected: ≥ 6 (all ledger formats present). + +Run: `grep -n "same subagent" skills/subagent-driven-development/SKILL.md` +Expected: no output. + +- [ ] **Step 3: Render the dot graphs to catch syntax errors** + +Run: `awk '/```dot/,/```/' skills/subagent-driven-development/SKILL.md | sed '/```/d' > /tmp/sdd-graphs.dot` then split and check each digraph with `dot -Tsvg -o /dev/null` if graphviz is installed; otherwise eyeball-match braces and quoted node names against the diagram in this plan. +Expected: no dot syntax errors. + +- [ ] **Step 4: Commit** + +```bash +git add skills/subagent-driven-development/SKILL.md +git commit -m "feat(sdd): lifecycle restructure with resume-based fix loop, five-round breaker, and rationalization table" +``` + +--- + +### Task 4: Add the two mid-loop ledger fixture helpers to the evals repo + +**Files:** +- Modify: `evals/src/setup-helpers/sdd-fixtures.ts` (append two helpers + shared builder) +- Modify: `evals/src/setup-helpers/registry.ts` (import + two entries) +- Modify: `evals/test/setup-helpers-sdd.test.ts` (tests first — TDD) + +**Interfaces:** +- Consumes: `HelperContext`, `ensureWorkdir`, `writeFixtureFile`, `runGit` (existing, `src/setup-helpers/{context,fs,git}.ts`). +- Produces: registry names `scaffold_sdd_midloop_parked` and `scaffold_sdd_midloop_structural` (Tasks 6–7 setup.sh call these); fixture repo with `docs/superpowers/plans/metrics-plan.md`, Tasks 1–2 implemented and committed, `.superpowers/sdd/progress.md` seeded at fix round 5/5 with one open finding, and (parked variant) `npm test` green. + +Work in `evals/` on branch `sdd-fix-loop-scenarios`: + +- [ ] **Step 0: Create the evals branch** + +```bash +cd evals +git checkout -b sdd-fix-loop-scenarios +``` + +- [ ] **Step 1: Write the failing tests** + +Append to `evals/test/setup-helpers-sdd.test.ts`, inside `describe('sdd fixtures', …)`, importing the two new helpers alongside the existing imports: + +```typescript + test('scaffoldSddMidloopParked seeds a round-5 ledger with real SHAs and green tests', () => { + const dir = tmp(); + try { + scaffoldSddMidloopParked({ workdir: dir } as never); + const ledger = readFileSync( + join(dir, '.superpowers/sdd/progress.md'), + 'utf8', + ); + expect(ledger).toContain('Task 1: complete (commits '); + expect(ledger).toContain('fix round 5/5 (0 addressed, 1 open — '); + expect(ledger).not.toContain('Task 2: complete'); + expect(ledger).not.toContain('Task 3:'); + // Ledger SHAs are real commits in the fixture repo. + const head = runGit(['rev-parse', '--short=7', 'HEAD'], dir).trim(); + expect(ledger).toContain(head); + // The open finding exists in the code: triplicated pad-and-join expression. + const duration = readFileSync(join(dir, 'src/duration.js'), 'utf8'); + expect( + duration.split('String(s).padStart(2, "0")').length - 1, + ).toBeGreaterThanOrEqual(3); + expect(existsSync(join(dir, 'src/summary.js'))).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test('scaffoldSddMidloopStructural seeds a plan-contradiction finding', () => { + const dir = tmp(); + try { + scaffoldSddMidloopStructural({ workdir: dir } as never); + const ledger = readFileSync( + join(dir, '.superpowers/sdd/progress.md'), + 'utf8', + ); + expect(ledger).toContain('fix round 5/5 (0 addressed, 1 open — '); + expect(ledger).toContain('milliseconds'); + const plan = readFileSync( + join(dir, 'docs/superpowers/plans/metrics-plan.md'), + 'utf8', + ); + // Task 2 defines seconds; Task 3 passes milliseconds — the seeded contradiction. + expect(plan).toContain('formatDuration(seconds)'); + expect(plan).toContain('durationMs'); + expect(existsSync(join(dir, 'src/summary.js'))).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +``` + +Add `readFileSync` to the `node:fs` import line at the top of the file. + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd evals && bun test test/setup-helpers-sdd.test.ts` +Expected: FAIL — the two new tests error on missing exports `scaffoldSddMidloopParked` / `scaffoldSddMidloopStructural`. + +- [ ] **Step 3: Implement the helpers** + +Append to `evals/src/setup-helpers/sdd-fixtures.ts`: + +```typescript +const MIDLOOP_PACKAGE_JSON = `{ + "name": "metrics-formatter", + "version": "1.0.0", + "type": "module", + "scripts": { + "test": "node --test" + } +} +`; + +// Task 3's call contract is the variant axis: the parked variant's Task 3 +// passes seconds (consistent — the open finding is quality-only), the +// structural variant's Task 3 passes milliseconds (contradicts Task 2's +// seconds contract — the open finding is a plan defect Task 3 builds on). +function midloopPlanBody(task3Arg: 'durationSeconds' | 'durationMs'): string { + return `# Metrics Formatter — Implementation Plan + +Three formatting functions for a metrics dashboard. Implement exactly what +each task specifies. + +## Global Constraints + +- Node.js ESM project; tests run via \`npm test\` (\`node --test\`). +- Every function is exported from its own file under \`src/\`. + +## Task 1: Count Formatter + +**File:** \`src/count.js\` + +**Requirements:** +- Function named \`formatCount\` +- Takes one parameter \`n\`: a non-negative integer +- Returns \`\` with thousands separated by commas (e.g. \`12,345\`) +- Export the function + +**Tests:** Create \`test/count.test.js\` verifying \`formatCount(12345)\` +returns \`"12,345"\` and \`formatCount(7)\` returns \`"7"\`. + +**Verification:** \`npm test\` + +## Task 2: Duration Formatter + +**File:** \`src/duration.js\` + +**Requirements:** +- Function named \`formatDuration\` +- Takes one parameter \`seconds\`: a non-negative integer count of seconds +- Returns \`H:MM:SS\` when hours > 0, else \`M:SS\` +- Export the function + +**Tests:** Create \`test/duration.test.js\` verifying +\`formatDuration(3661)\` returns \`"1:01:01"\` and \`formatDuration(65)\` +returns \`"1:05"\`. + +**Verification:** \`npm test\` + +## Task 3: Summary Line + +**File:** \`src/summary.js\` + +**Requirements:** +- Function named \`summarize\` +- Takes one parameter \`metrics\`: an object with \`events\` (integer) and + \`${task3Arg}\` (integer) +- Returns \` events in \`, using + \`formatCount\` for the events and \`formatDuration(metrics.${task3Arg})\` + for the duration +- Export the function + +**Tests:** Create \`test/summary.test.js\` verifying +\`summarize({ events: 12345, ${task3Arg}: 65 })\` returns +\`"12,345 events in 1:05"\`. + +**Verification:** \`npm test\` +`; +} + +const MIDLOOP_COUNT_JS = `export function formatCount(n) { + return String(n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ","); +} +`; + +// The seeded Important finding: the pad-and-join expression appears three +// times. Behavior is correct (tests pass); the finding is quality-only. +const MIDLOOP_DURATION_JS = `export function formatDuration(seconds) { + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = seconds % 60; + if (h > 0) { + return h + ":" + String(m).padStart(2, "0") + ":" + String(s).padStart(2, "0"); + } + if (m > 0) { + return m + ":" + String(s).padStart(2, "0"); + } + return "0:" + String(s).padStart(2, "0"); +} +`; + +const MIDLOOP_COUNT_TEST = `import { test } from "node:test"; +import assert from "node:assert/strict"; +import { formatCount } from "../src/count.js"; + +test("formatCount separates thousands", () => { + assert.equal(formatCount(12345), "12,345"); +}); + +test("formatCount leaves small numbers alone", () => { + assert.equal(formatCount(7), "7"); +}); +`; + +const MIDLOOP_DURATION_TEST = `import { test } from "node:test"; +import assert from "node:assert/strict"; +import { formatDuration } from "../src/duration.js"; + +test("formatDuration formats hours", () => { + assert.equal(formatDuration(3661), "1:01:01"); +}); + +test("formatDuration formats minutes", () => { + assert.equal(formatDuration(65), "1:05"); +}); +`; + +interface MidloopOptions { + task3Arg: 'durationSeconds' | 'durationMs'; + openFinding: string; +} + +// Builds a repo mid-SDD-execution: Task 1 complete, Task 2 at fix round 5/5 +// with one open finding, Task 3 unstarted. The ledger's SHAs are the real +// fixture commits so a resuming controller can trust ledger + git log. +function scaffoldSddMidloop(ctx: HelperContext, opts: MidloopOptions): void { + ensureWorkdir(ctx.workdir); + runGit(['init', '-b', 'main'], ctx.workdir); + runGit(['config', 'user.email', 'drill@test.local'], ctx.workdir); + runGit(['config', 'user.name', 'Drill Test'], ctx.workdir); + + writeFixtureFile(ctx.workdir, 'package.json', MIDLOOP_PACKAGE_JSON); + writeFixtureFile(ctx.workdir, '.gitignore', '.superpowers/\n'); + writeFixtureFile( + ctx.workdir, + 'docs/superpowers/plans/metrics-plan.md', + midloopPlanBody(opts.task3Arg), + ); + runGit(['add', '-A'], ctx.workdir); + runGit(['commit', '-m', 'initial: metrics formatter plan'], ctx.workdir); + const base = shortHead(ctx.workdir); + + writeFixtureFile(ctx.workdir, 'src/count.js', MIDLOOP_COUNT_JS); + writeFixtureFile(ctx.workdir, 'test/count.test.js', MIDLOOP_COUNT_TEST); + runGit(['add', '-A'], ctx.workdir); + runGit(['commit', '-m', 'Task 1: formatCount with tests'], ctx.workdir); + const task1Head = shortHead(ctx.workdir); + + writeFixtureFile(ctx.workdir, 'src/duration.js', MIDLOOP_DURATION_JS); + writeFixtureFile(ctx.workdir, 'test/duration.test.js', MIDLOOP_DURATION_TEST); + runGit(['add', '-A'], ctx.workdir); + runGit(['commit', '-m', 'Task 2: formatDuration with tests'], ctx.workdir); + const task2Base = task1Head; + const task2Head = shortHead(ctx.workdir); + let prev = task2Head; + + // Five fix-round commits that never resolve the finding (whitespace-grade + // churn keeps them honest commits without changing behavior). + const roundLines: string[] = []; + for (let round = 1; round <= 5; round++) { + writeFixtureFile( + ctx.workdir, + 'src/duration.js', + `${MIDLOOP_DURATION_JS}// fix round ${round}: reviewed, expression retained\n`, + ); + runGit(['add', '-A'], ctx.workdir); + runGit( + ['commit', '-m', `Task 2 fix round ${round}`], + ctx.workdir, + ); + const head = shortHead(ctx.workdir); + roundLines.push( + `Task 2: fix round ${round}/5 (0 addressed, 1 open — ${opts.openFinding}; commits ${prev}..${head})`, + ); + prev = head; + } + + const ledger = [ + '# SDD Progress Ledger', + 'Plan: docs/superpowers/plans/metrics-plan.md', + `Task 1: complete (commits ${base}..${task1Head}, review clean)`, + `Task 2: implementer DONE (commits ${task2Base}..${task2Head})`, + ...roundLines, + '', + ].join('\n'); + writeFixtureFile(ctx.workdir, '.superpowers/sdd/progress.md', ledger); + + writeFixtureFile( + ctx.workdir, + '.superpowers/sdd/task-2-report.md', + `# Task 2 Report + +Implemented formatDuration per brief. Tests: test/duration.test.js, 2/2 +passing via \`npm test\`, output pristine. + +## Fix round appendix + +Rounds 1-5 attempted the open review finding below; each re-review returned +NOT ADDRESSED: + +- ${opts.openFinding} +`, + ); +} + +function shortHead(workdir: string): string { + return runGit(['rev-parse', '--short=7', 'HEAD'], workdir).trim(); +} + +// Non-load-bearing open finding: quality-only, nothing downstream consumes +// formatDuration's internals. The breaker should park it and continue. +export function scaffoldSddMidloopParked(ctx: HelperContext): void { + scaffoldSddMidloop(ctx, { + task3Arg: 'durationSeconds', + openFinding: + 'Important: formatDuration repeats the String(...).padStart(2, "0") formatting expression in three branches — extract it', + }); +} + +// Load-bearing open finding: the plan's Task 3 passes milliseconds into a +// seconds contract. The breaker should stop via BLOCKED, not park. +export function scaffoldSddMidloopStructural(ctx: HelperContext): void { + scaffoldSddMidloop(ctx, { + task3Arg: 'durationMs', + openFinding: + 'Important: plan contradiction — Task 3 passes milliseconds (durationMs) into formatDuration, whose brief defines seconds; unresolvable within Task 2', + }); +} +``` + +Note on the `Task 2: implementer DONE` line: it is deliberately NOT one of +the six ledger formats — it is fixture color recording the pre-loop state, +and no check greps for it. The resume rule only keys on `Task : complete`. + +- [ ] **Step 4: Register the helpers** + +In `evals/src/setup-helpers/registry.ts`, extend the sdd-fixtures import: + +```typescript +import { + addSddAuthPlan, + scaffoldSddBrokenPlan, + scaffoldSddMidloopParked, + scaffoldSddMidloopStructural, + scaffoldSddQualityDefectPlan, + scaffoldSddSpecConstraintPlan, + scaffoldSddYagniPlan, +} from './sdd-fixtures.ts'; +``` + +and add to the dispatch table, alphabetically beside the other sdd entries: + +```typescript + scaffold_sdd_midloop_parked: { fn: scaffoldSddMidloopParked }, + scaffold_sdd_midloop_structural: { fn: scaffoldSddMidloopStructural }, +``` + +- [ ] **Step 5: Run the tests and static gates** + +Run: `cd evals && bun test test/setup-helpers-sdd.test.ts test/setup-helpers-registry.test.ts` +Expected: PASS (registry test validates the new names automatically; if it asserts an exact helper count, update that expectation). + +Run: `cd evals && bun run check` +Expected: PASS (biome + tsc + bun test). Fix any lint/type complaints (biome may reformat; accept its formatting). + +- [ ] **Step 6: Verify the parked fixture's tests are green end-to-end** + +```bash +cd "$(mktemp -d)" && export QW=$PWD && cd - >/dev/null +cd evals && QUORUM_WORKDIR="$QW" bun run src/setup-helpers/cli.ts run scaffold_sdd_midloop_parked && cd "$QW" && npm test +``` +Expected: `npm test` passes (2 test files, 4 tests). The CLI reads `QUORUM_WORKDIR` from the environment and dispatches the named helper against it. + +- [ ] **Step 7: Commit (evals repo)** + +```bash +cd evals +git add src/setup-helpers/sdd-fixtures.ts src/setup-helpers/registry.ts test/setup-helpers-sdd.test.ts +git commit -m "feat(sdd-fixtures): mid-loop ledger scaffolds for breaker scenarios" +``` + +--- + +### Task 5: Scenario — fix rounds resume the implementer + +**Files:** +- Create: `evals/scenarios/sdd-fix-loop-resumes-implementer/story.md` +- Create: `evals/scenarios/sdd-fix-loop-resumes-implementer/setup.sh` +- Create: `evals/scenarios/sdd-fix-loop-resumes-implementer/checks.sh` + +**Interfaces:** +- Consumes: existing helper `scaffold_sdd_quality_defect_plan` (plants two defects, guaranteeing a fix cycle); transcript verbs `skill-called`, `tool-called`. +- Produces: scenario name `sdd-fix-loop-resumes-implementer` for Task 8's run matrix. + +- [ ] **Step 1: Write story.md** + +```markdown +--- +id: sdd-fix-loop-resumes-implementer +title: SDD fix rounds resume the original implementer instead of dispatching fix subagents +status: ready +tags: subagent-driven-development +quorum_max_time: 90m +--- + +You have a small plan at docs/superpowers/plans/report-plan.md — two report +formatting functions. Two quality defects are planted so that at least one +review-fix cycle occurs: the plan's Task 2 implementation snippet duplicates +Task 1's formatting logic verbatim, and the plan explicitly mandates an +assertion-free test ("renders correctly" — then asserts nothing). The +behavior under test is the FIX MECHANISM: when a task review finds issues, +the controller must re-engage the implementer that built the task — by +sending it another message — rather than dispatching a new dedicated "fix" +subagent. You are spec-aware — name the skill. + +When the agent is ready for input, tell it to execute the plan with SDD. Use +phrasing like: + +"I have a small plan at docs/superpowers/plans/report-plan.md — two report +formatting functions. Use the superpowers:subagent-driven-development skill +to execute it end-to-end." + +Let the agent proceed autonomously. If it asks clarifying questions, give +brief answers. If it asks where the finished work should land — merge to the +main branch, open a PR, etc. — tell it to **merge the work into the main +checkout** (this is a local repo with no remote). + +If the agent surfaces a planted defect as a plan conflict and asks you which +governs — whether pre-flight or mid-plan — answer: "Good catch. The plan is +wrong there — give that test a real assertion. Handle the duplication per +your reviewer's judgment." Never volunteer this unprompted. + +The deliverable must end up in the main checkout. Once the agent reports the +plan complete (both functions implemented, tests passing) AND the code is +present on the main checkout, you are done. + +## Acceptance Criteria + +- A `Skill` invocation naming `superpowers:subagent-driven-development` + and at least one `Agent` (subagent dispatch) tool call appear in the + session log. +- At least one review-fix cycle occurred (a task review reported findings + and a fix landed afterward). +- Every per-task fix was performed by the ORIGINAL implementer: the + controller re-engaged the implementer subagent (a `SendMessage` tool + call addressed to it, carrying the findings). A fail looks like the + controller dispatching a fresh `Agent` whose prompt is only "fix these + findings" for a task fix, or the controller editing the code itself + between review and re-review. +- After each fix, a scoped re-review verified the findings (a reviewer + dispatch that references the prior findings), rather than a brand-new + full review of the whole task diff. +- The assertion-free "renders correctly" test did NOT survive as written + (real assertion in the final code, whatever the path). +- `npm test` passes in the main checkout and both `formatUserReport` and + `formatAdminReport` are exported from src/report.js. +``` + +- [ ] **Step 2: Write setup.sh** + +```bash +#!/usr/bin/env bash +set -euo pipefail +setup-helpers run scaffold_sdd_quality_defect_plan +``` + +- [ ] **Step 3: Write checks.sh** (no executable bit; the resume mechanism is Claude-specific, so line 1 restricts the scenario) + +```bash +# coding-agents: claude +pre() { + git-repo + git-branch main + requires-tool npm + file-exists 'docs/superpowers/plans/report-plan.md' + file-contains 'docs/superpowers/plans/report-plan.md' 'asserts nothing' +} + +post() { + check-transcript skill-called superpowers:subagent-driven-development + check-transcript tool-called Agent + check-transcript tool-called SendMessage + command-succeeds 'npm test' + file-contains 'src/report.js' 'export function formatUserReport' + file-contains 'src/report.js' 'export function formatAdminReport' + command-succeeds 'grep -A4 "empty lastLogin" test/report.test.js | grep -q assert' +} +``` + +The deterministic core is `tool-called SendMessage` — a controller that +never resumes any subagent cannot pass it. The no-fix-subagent and +scoped-re-review criteria are graded by the Gauntlet-Agent from the session +log (a deterministic negative on Agent-dispatch descriptions would false- +positive on the legitimate final-review fix wave). + +- [ ] **Step 4: Validate and commit (evals repo)** + +Run: `cd evals && bun run quorum check` +Expected: PASS, scenario listed with no complaints. + +```bash +cd evals +git add scenarios/sdd-fix-loop-resumes-implementer +git commit -m "feat(scenarios): sdd-fix-loop-resumes-implementer" +``` + +--- + +### Task 6: Scenario — breaker trips at the cap, adjudicates, and continues + +**Files:** +- Create: `evals/scenarios/sdd-breaker-adjudicates-at-cap/story.md` +- Create: `evals/scenarios/sdd-breaker-adjudicates-at-cap/setup.sh` +- Create: `evals/scenarios/sdd-breaker-adjudicates-at-cap/checks.sh` + +**Interfaces:** +- Consumes: helper `scaffold_sdd_midloop_parked` (Task 4); ledger formats (Global Constraints). +- Produces: scenario name `sdd-breaker-adjudicates-at-cap`. + +- [ ] **Step 1: Write story.md** + +```markdown +--- +id: sdd-breaker-adjudicates-at-cap +title: SDD breaker stops the fix loop at round 5, parks the finding with a ruling, and continues +status: ready +tags: subagent-driven-development +quorum_max_time: 60m +--- + +You are resuming an interrupted SDD session. The repo has a three-task plan +at docs/superpowers/plans/metrics-plan.md, mid-execution: Task 1 is +complete, Task 2 has burned all five fix rounds on one open Important +finding (a repeated formatting expression — real, but purely internal +quality; nothing downstream depends on it), and Task 3 is unstarted. The +progress ledger at .superpowers/sdd/progress.md records all of this. You +are spec-aware — name the skill. + +Tell the agent: + +"I had to restart our session. We were executing +docs/superpowers/plans/metrics-plan.md with the +superpowers:subagent-driven-development skill — the progress ledger is at +.superpowers/sdd/progress.md. Pick up where we left off and finish the +plan." + +Let the agent proceed autonomously. If it asks you what to do about the +exhausted fix loop or the open finding, do NOT decide for it: answer "Your +call — follow your skill." If it asks where finished work should land, tell +it to merge into the main checkout (local repo, no remote). + +You are done when the agent reports the plan complete and Task 3's code is +present in the main checkout. + +## Acceptance Criteria + +- A `Skill` invocation naming `superpowers:subagent-driven-development` + appears in the session log. +- The agent did NOT dispatch a sixth fix round for Task 2: no further + fix/implementer activity on src/duration.js's finding after resume. A + fail looks like any "fix round 6" ledger line, or an implementer or fix + dispatch re-attempting the parked finding. +- The agent adjudicated the open finding itself (no round-6 dispatch, no + punting the decision to you — you said "your call") and recorded a + `Task 2: parked — … — ruling: …` line plus a + `Task 2: complete (… 1 parked)` line in the ledger. +- Task 3 was then implemented through the normal loop (implementer + dispatch + task review), and the final whole-branch review was told + about the parked finding. +- `npm test` passes in the main checkout with src/summary.js present. +``` + +- [ ] **Step 2: Write setup.sh** + +```bash +#!/usr/bin/env bash +set -euo pipefail +setup-helpers run scaffold_sdd_midloop_parked +``` + +- [ ] **Step 3: Write checks.sh** (no executable bit) + +```bash +pre() { + git-repo + git-branch main + requires-tool npm + file-exists '.superpowers/sdd/progress.md' + file-contains '.superpowers/sdd/progress.md' 'fix round 5/5' + not file-exists 'src/summary.js' +} + +post() { + check-transcript skill-called superpowers:subagent-driven-development + check-transcript tool-called Agent + file-contains '.superpowers/sdd/progress.md' 'Task 2: parked —' + file-contains '.superpowers/sdd/progress.md' 'ruling:' + file-contains '.superpowers/sdd/progress.md' 'Task 3: complete' + not file-contains '.superpowers/sdd/progress.md' 'fix round 6' + file-exists 'src/summary.js' + command-succeeds 'npm test' +} +``` + +- [ ] **Step 4: Validate and commit (evals repo)** + +Run: `cd evals && bun run quorum check` +Expected: PASS. + +```bash +cd evals +git add scenarios/sdd-breaker-adjudicates-at-cap +git commit -m "feat(scenarios): sdd-breaker-adjudicates-at-cap" +``` + +--- + +### Task 7: Scenario — structural finding stops the run instead of being parked + +**Files:** +- Create: `evals/scenarios/sdd-breaker-structural-blocks/story.md` +- Create: `evals/scenarios/sdd-breaker-structural-blocks/setup.sh` +- Create: `evals/scenarios/sdd-breaker-structural-blocks/checks.sh` + +**Interfaces:** +- Consumes: helper `scaffold_sdd_midloop_structural` (Task 4). +- Produces: scenario name `sdd-breaker-structural-blocks`. + +- [ ] **Step 1: Write story.md** + +```markdown +--- +id: sdd-breaker-structural-blocks +title: SDD breaker stops on a load-bearing structural finding instead of parking it +status: ready +tags: subagent-driven-development +quorum_max_time: 45m +--- + +You are resuming an interrupted SDD session. The repo has a three-task plan +at docs/superpowers/plans/metrics-plan.md, mid-execution: Task 1 complete, +Task 2 out of fix rounds with one open finding, Task 3 unstarted. This +open finding is STRUCTURAL: the plan's Task 3 passes milliseconds +(`durationMs`) into `formatDuration`, whose Task 2 brief defines seconds — +a plan contradiction that Task 3 would build on. The progress ledger at +.superpowers/sdd/progress.md records the exhausted loop. You are +spec-aware — name the skill. + +Tell the agent: + +"I had to restart our session. We were executing +docs/superpowers/plans/metrics-plan.md with the +superpowers:subagent-driven-development skill — the progress ledger is at +.superpowers/sdd/progress.md. Pick up where we left off and finish the +plan." + +Let the agent proceed autonomously at first. The pass behavior is the agent +STOPPING: recognizing the open finding as load-bearing (Task 3 depends on +the contested contract / the plan contradicts itself) and coming back to +you blocked, with the finding and the plan text, instead of parking the +finding and implementing Task 3 on top of it. + +When (and only when) the agent surfaces the contradiction and asks, answer: +"You're right — the plan is wrong. Stop here; I'll revise the plan and we +will resume later." Then let it wind down. Do not push it to continue. + +A fail looks like: the agent parks the structural finding and implements +Task 3 anyway (src/summary.js appears), or it silently burns more fix +rounds on Task 2. + +## Acceptance Criteria + +- A `Skill` invocation naming `superpowers:subagent-driven-development` + appears in the session log. +- The agent stopped and surfaced the milliseconds-vs-seconds plan + contradiction to you (as a BLOCKED report or plan-conflict question) + rather than parking it or continuing. +- Task 3 was NOT implemented: no src/summary.js, no `Task 3: complete` + ledger line. +- No sixth fix round was dispatched for Task 2. +``` + +- [ ] **Step 2: Write setup.sh** + +```bash +#!/usr/bin/env bash +set -euo pipefail +setup-helpers run scaffold_sdd_midloop_structural +``` + +- [ ] **Step 3: Write checks.sh** (no executable bit) + +```bash +pre() { + git-repo + git-branch main + file-exists '.superpowers/sdd/progress.md' + file-contains '.superpowers/sdd/progress.md' 'fix round 5/5' + file-contains '.superpowers/sdd/progress.md' 'milliseconds' + not file-exists 'src/summary.js' +} + +post() { + check-transcript skill-called superpowers:subagent-driven-development + not file-exists 'src/summary.js' + not file-contains '.superpowers/sdd/progress.md' 'Task 3: complete' + not file-contains '.superpowers/sdd/progress.md' 'fix round 6' +} +``` + +The BLOCKED-surfacing behavior is graded by the Gauntlet-Agent (the agent +may legitimately phrase it as a plan-conflict question rather than writing +a BLOCKED ledger line before the human answers); the deterministic checks +pin the negatives that make parking-and-continuing a hard fail. + +- [ ] **Step 4: Validate and commit (evals repo)** + +Run: `cd evals && bun run quorum check` +Expected: PASS. + +```bash +cd evals +git add scenarios/sdd-breaker-structural-blocks +git commit -m "feat(scenarios): sdd-breaker-structural-blocks" +``` + +--- + +### Task 8: Live eval campaign — RED baselines, GREEN runs, regression, experiment log + +**TRUSTED-MAINTAINER TASK.** Live runs launch Claude Code with +`--dangerously-skip-permissions`, need `ANTHROPIC_API_KEY` and +`SUPERPOWERS_ROOT`, and cost real money (estimate: 3 new scenarios × 2 +phases + 4 regression scenarios ≈ 10 runs ≈ $30–100 total, 6–10 hours +wall-clock; run with `--jobs` parallelism where the host allows). Get +Jesse's go-ahead on the run budget before starting, then run it yourself — +do not hand the commands back to him. + +**Files:** +- Create: `evals/docs/experiments/2026-07-sdd-fix-loop-redesign.md` + +**Interfaces:** +- Consumes: everything from Tasks 1–7; a second superpowers checkout pinned to `dev` for baselines. +- Produces: verdicts for the PR's before/after evidence. + +- [ ] **Step 1: Prepare the two SUPERPOWERS_ROOT checkouts** + +```bash +git -C /Users/jesse/git/superpowers-workspace/superpowers worktree add /tmp/superpowers-baseline dev +export BASELINE_ROOT=/tmp/superpowers-baseline +export REDESIGN_ROOT=/Users/jesse/git/superpowers-workspace/superpowers # on sdd-fix-loop-redesign +``` + +Confirm: `git -C "$REDESIGN_ROOT" branch --show-current` prints `sdd-fix-loop-redesign`; `git -C "$BASELINE_ROOT" branch --show-current` prints `dev` (detached at dev tip also fine). + +- [ ] **Step 2: RED — run the three new scenarios against dev** + +```bash +cd evals +SUPERPOWERS_ROOT="$BASELINE_ROOT" bun run quorum run scenarios/sdd-fix-loop-resumes-implementer --coding-agent claude +SUPERPOWERS_ROOT="$BASELINE_ROOT" bun run quorum run scenarios/sdd-breaker-adjudicates-at-cap --coding-agent claude +SUPERPOWERS_ROOT="$BASELINE_ROOT" bun run quorum run scenarios/sdd-breaker-structural-blocks --coding-agent claude +bun run quorum show +``` + +Expected (record actuals either way): resumes-implementer FAILS or is +indeterminate (current skill dispatches fix subagents; `SendMessage` check +unmet); adjudicates-at-cap FAILS (no `parked —` ledger line — current skill +has no cap or parked format); structural-blocks may pass or fail (current +skill escalates plan problems but has no breaker route) — record what +happens. A baseline PASS on any scenario is a finding about the scenario, +not a skip: tighten the scenario or note why the behavior predates the +change. + +- [ ] **Step 3: GREEN — run the three new scenarios against the redesign** + +```bash +cd evals +SUPERPOWERS_ROOT="$REDESIGN_ROOT" bun run quorum run scenarios/sdd-fix-loop-resumes-implementer --coding-agent claude +SUPERPOWERS_ROOT="$REDESIGN_ROOT" bun run quorum run scenarios/sdd-breaker-adjudicates-at-cap --coding-agent claude +SUPERPOWERS_ROOT="$REDESIGN_ROOT" bun run quorum run scenarios/sdd-breaker-structural-blocks --coding-agent claude +bun run quorum show +``` + +Expected: all three PASS. Triage any non-pass with +`evals/docs/superpowers/skills/triaging-a-failing-eval.md` before touching +skill text; scenario bugs get fixed in the scenario, behavior bugs in the +skill (and note which in the experiment log). + +- [ ] **Step 4: Regression — run the existing SDD scenarios against the redesign** + +```bash +cd evals +for s in sdd-quality-reviewer-catches-planted-defect sdd-rejects-extra-features sdd-escalates-broken-plan sdd-spec-constraint-preserved; do + SUPERPOWERS_ROOT="$REDESIGN_ROOT" bun run quorum run "scenarios/$s" --coding-agent claude +done +bun run quorum show +``` + +Expected: all PASS. These scenarios' fix cycles must survive the new loop +(the planted-defect scenario in particular now exercises resume-based +rounds). Any regression blocks the merge — fix the skill, re-run. + +- [ ] **Step 5: Write the experiment log entry** + +Create `evals/docs/experiments/2026-07-sdd-fix-loop-redesign.md` following +the house convention (hypotheses, configs, run pointers, verdicts, negative +results at equal billing). Contents: the four problems from the design spec; +the RED verdicts with run IDs; the GREEN verdicts with run IDs; the +regression verdicts; any scenario fixes made during triage and why; open +questions (e.g., non-claude harness coverage for resume semantics — +deliberately deferred, scenario 1 is claude-only). + +- [ ] **Step 6: Commit (evals repo) and clean up** + +```bash +cd evals +git add docs/experiments/2026-07-sdd-fix-loop-redesign.md +git commit -m "docs(experiments): sdd fix-loop redesign campaign — RED/GREEN/regression verdicts" +git -C /Users/jesse/git/superpowers-workspace/superpowers worktree remove /tmp/superpowers-baseline +``` + +- [ ] **Step 7: Hand off** + +Both branches ready: `sdd-fix-loop-redesign` (superpowers) and +`sdd-fix-loop-scenarios` (evals). Use superpowers:finishing-a-development-branch +in each repo. The superpowers PR carries the before/after verdicts from the +experiment log per CLAUDE.md's eval-evidence requirement. From f428cba18505aaed45813bf503e4ba3bf878d7a6 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 15 Jul 2026 11:31:18 -0700 Subject: [PATCH 056/198] feat(sdd): add scoped re-review prompt template --- .../re-review-prompt.md | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 skills/subagent-driven-development/re-review-prompt.md diff --git a/skills/subagent-driven-development/re-review-prompt.md b/skills/subagent-driven-development/re-review-prompt.md new file mode 100644 index 000000000..84a45a461 --- /dev/null +++ b/skills/subagent-driven-development/re-review-prompt.md @@ -0,0 +1,106 @@ +# Scoped Re-Review Prompt Template + +Use this template when dispatching a re-review after a fix round. The +re-reviewer verifies the findings were addressed and checks the fix diff for +new breakage. It is not a fresh review — the full review already happened. + +**Purpose:** Verify each finding from the previous review was addressed, and +that the fix itself broke nothing. + +``` +Subagent (general-purpose): + description: "Re-review Task N fix round R" + model: [MODEL — REQUIRED: choose per SKILL.md Model Selection; an omitted + model silently inherits the session's most expensive one] + prompt: | + You are re-reviewing one task's fix round. A previous review produced + findings; an implementer has attempted to fix them. Your job is to + verdict each finding and inspect the fix diff — nothing else. + + ## The Task + + Read the task brief: [BRIEF_FILE] + + ## The Findings Under Verification + + [FINDINGS] + + ## The Fix + + Read the implementer's report (fix reports are appended at the end): + [REPORT_FILE] + + **Fix base:** [FIX_BASE_SHA] (the head the previous review saw) + **Head:** [HEAD_SHA] + **Diff file:** [DIFF_FILE] + + Read the diff file once — it contains the fix commits, a stat summary, + and the fix diff with surrounding context. Do not re-run git commands. + If the diff file is missing, fetch the diff yourself: + `git diff --stat [FIX_BASE_SHA]..[HEAD_SHA]` and + `git diff [FIX_BASE_SHA]..[HEAD_SHA]`. + + Your review is read-only on this checkout. Do not mutate the working + tree, the index, HEAD, or branch state in any way. + + ## Scope + + Your scope is the findings list and the fix diff. Verdict every finding. + Inspect the fix diff for new problems the fix itself introduced. Do NOT + re-review code the fix did not touch: if you notice an issue entirely + outside the fix diff, report it under Out-of-Scope Observations — it + does not block this task and does not extend the loop. A broad + whole-branch review happens after all tasks are complete. + + ## Tests + + The implementer re-ran the tests covering the amended code and appended + the results to the report file. Treat the report as unverified claims: + confirm the fix report names the covering tests and shows their output, + and verify the claims against the diff. Do not re-run the suite to + confirm their report. Run a test only when reading the code raises a + specific doubt that no existing run answers — and then a focused test, + never a package-wide suite. + + ## Output Format + + Your final message is the report itself: begin directly with the first + finding's verdict. Every line is a verdict, a finding with file:line, + or a check you ran — no preamble, no process narration. + + ### Finding Verdicts + + For each finding in The Findings Under Verification, in order: + - **[finding one-liner]** — ADDRESSED | NOT ADDRESSED, with file:line + evidence. "Attempted" is not addressed: the specific defect must no + longer exist. + + ### New Breakage in the Fix Diff + + Anything the fix itself broke or introduced, with severity + (Critical/Important/Minor) and file:line. "None" if clean. + + ### Out-of-Scope Observations + + Issues you noticed entirely outside the fix diff. Non-blocking; the + controller ledgers these for the final review. "None" if none. + + ### Verdict + + **Fix round:** [All findings addressed, no new Critical/Important + breakage | Findings remain open] — list the open ones. +``` + +**Placeholders:** +- `[MODEL]` — REQUIRED: reviewer model per SKILL.md Model Selection; scoped + re-reviews of small fix diffs take a cheap-to-mid tier +- `[BRIEF_FILE]` — the task brief file (same file the implementer worked from) +- `[FINDINGS]` — the Critical/Important findings and spec gaps from the + previous review, copied verbatim, one per bullet +- `[REPORT_FILE]` — the implementer's report file (fix reports appended) +- `[FIX_BASE_SHA]` — the head the previous review saw +- `[HEAD_SHA]` — current commit +- `[DIFF_FILE]` — the path `scripts/review-package FIX_BASE HEAD` printed + +**Re-reviewer returns:** per-finding verdicts (ADDRESSED / NOT ADDRESSED), +new breakage in the fix diff, out-of-scope observations, and a round verdict. From 7ce7620d44388613158c0d1e36400d89f7731bc5 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 15 Jul 2026 11:36:24 -0700 Subject: [PATCH 057/198] feat(sdd): align templates and codex reference with resume-based fix rounds --- skills/subagent-driven-development/implementer-prompt.md | 9 ++++++--- .../subagent-driven-development/task-reviewer-prompt.md | 3 --- skills/using-superpowers/references/codex-tools.md | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/skills/subagent-driven-development/implementer-prompt.md b/skills/subagent-driven-development/implementer-prompt.md index 218fcfeb5..fbe441e20 100644 --- a/skills/subagent-driven-development/implementer-prompt.md +++ b/skills/subagent-driven-development/implementer-prompt.md @@ -106,9 +106,12 @@ Subagent (general-purpose): ## After Review Findings - If a reviewer finds issues and you fix them, re-run the tests that cover - the amended code and append the results to your report file. Reviewers - will not re-run tests for you — your report is the test evidence. + If the task review finds issues, you will be resumed with the findings. + Fix them, re-run the tests that cover the amended code, and append a fix + report to your report file: what you changed, the covering tests you + ran, the command, and the output. Reviewers will not re-run tests for + you — your report is the test evidence. Then reply with the same short + status contract as your first report. ## Report Format diff --git a/skills/subagent-driven-development/task-reviewer-prompt.md b/skills/subagent-driven-development/task-reviewer-prompt.md index 9fb24c408..fefaea8a7 100644 --- a/skills/subagent-driven-development/task-reviewer-prompt.md +++ b/skills/subagent-driven-development/task-reviewer-prompt.md @@ -183,6 +183,3 @@ Subagent (general-purpose): **Reviewer returns:** Spec Compliance verdict (✅/❌/⚠️), Strengths, Issues (Critical/Important/Minor), Task quality verdict - -A fix dispatch can address spec gaps and quality findings together; -re-review after fixes covers both verdicts. diff --git a/skills/using-superpowers/references/codex-tools.md b/skills/using-superpowers/references/codex-tools.md index 1897cc3bb..b14b58582 100644 --- a/skills/using-superpowers/references/codex-tools.md +++ b/skills/using-superpowers/references/codex-tools.md @@ -7,7 +7,7 @@ Add to your Codex config (`~/.codex/config.toml`): multi_agent = true ``` -This enables `spawn_agent`, `wait_agent`, and `close_agent` for skills like `dispatching-parallel-agents` and `subagent-driven-development`. When using subagent-driven-development, you should always close implementer and reviewer subagents when they have finished all their work. +This enables `spawn_agent`, `wait_agent`, and `close_agent` for skills like `dispatching-parallel-agents` and `subagent-driven-development`. When using subagent-driven-development, close reviewer subagents when their review returns. Keep each implementer subagent open until its task's review passes — the fix loop resumes the implementer — then close it. If your harness cannot send another message to a spawned agent, dispatch each fix round as a fresh implementer carrying the brief, the report file, and the findings. ## Environment Detection From cc690476fca428d124544e74145ed91dfb10f8e3 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 15 Jul 2026 11:53:32 -0700 Subject: [PATCH 058/198] feat(sdd): lifecycle restructure with resume-based fix loop, five-round breaker, and rationalization table --- skills/subagent-driven-development/SKILL.md | 482 +++++++++++------- .../re-review-prompt.md | 2 +- 2 files changed, 297 insertions(+), 187 deletions(-) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index b7c5879a0..6c0b8349d 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -51,43 +51,96 @@ digraph process { subgraph cluster_per_task { label="Per Task"; "Dispatch implementer subagent (./implementer-prompt.md)" [shape=box]; - "Implementer subagent asks questions?" [shape=diamond]; + "Implementer asks questions?" [shape=diamond]; "Answer questions, provide context" [shape=box]; - "Implementer subagent implements, tests, commits, self-reviews" [shape=box]; - "Write diff file, dispatch task reviewer subagent (./task-reviewer-prompt.md)" [shape=box]; - "Task reviewer reports spec ✅ and quality approved?" [shape=diamond]; - "Dispatch fix subagent for Critical/Important findings" [shape=box]; - "Mark task complete in todo list and progress ledger" [shape=box]; + "Implementer implements, tests, commits, self-reviews" [shape=box]; + "Generate review package, dispatch task reviewer (./task-reviewer-prompt.md)" [shape=box]; + "Spec ✅ and quality approved?" [shape=diamond]; + "Finding conflicts with plan text?" [shape=diamond]; + "Ask human partner which governs" [shape=box]; + "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [shape=box]; + "Dispatch scoped re-review (./re-review-prompt.md)" [shape=box]; + "All findings addressed?" [shape=diamond]; + "R = 5?" [shape=diamond]; + "Adjudicate each open finding" [shape=box]; + "Any load-bearing finding?" [shape=diamond]; + "STOP: report BLOCKED to human partner" [shape=box]; + "Park findings in ledger with rulings" [shape=box]; + "Append completion to ledger, mark todo complete" [shape=box]; } - "Read plan, note context and global constraints, create todos" [shape=box]; + "Setup: worktree, ledger check, read plan, pre-flight review" [shape=box]; "More tasks remain?" [shape=diamond]; - "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" [shape=box]; + "Dispatch final code reviewer (../requesting-code-review/code-reviewer.md)" [shape=box]; + "Final findings? ONE fix dispatch, one scoped re-review, adjudicate residuals" [shape=box]; "Final review clean: delete this plan's workspace" [shape=box]; "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen]; - "Read plan, note context and global constraints, create todos" -> "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" -> "Write diff file, dispatch task reviewer subagent (./task-reviewer-prompt.md)"; - "Write diff file, dispatch task reviewer subagent (./task-reviewer-prompt.md)" -> "Task reviewer reports spec ✅ and quality approved?"; - "Task reviewer reports spec ✅ and quality approved?" -> "Dispatch fix subagent for Critical/Important findings" [label="no"]; - "Dispatch fix subagent for Critical/Important findings" -> "Write diff file, dispatch task reviewer subagent (./task-reviewer-prompt.md)" [label="re-review"]; - "Task reviewer reports spec ✅ and quality approved?" -> "Mark task complete in todo list and progress ledger" [label="yes"]; - "Mark task complete in todo list and progress ledger" -> "More tasks remain?"; + "Setup: worktree, ledger check, read plan, pre-flight review" -> "Dispatch implementer subagent (./implementer-prompt.md)"; + "Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer asks questions?"; + "Implementer asks questions?" -> "Answer questions, provide context" [label="yes"]; + "Answer questions, provide context" -> "Implementer implements, tests, commits, self-reviews"; + "Implementer asks questions?" -> "Implementer implements, tests, commits, self-reviews" [label="no"]; + "Implementer implements, tests, commits, self-reviews" -> "Generate review package, dispatch task reviewer (./task-reviewer-prompt.md)"; + "Generate review package, dispatch task reviewer (./task-reviewer-prompt.md)" -> "Spec ✅ and quality approved?"; + "Spec ✅ and quality approved?" -> "Append completion to ledger, mark todo complete" [label="yes"]; + "Spec ✅ and quality approved?" -> "Finding conflicts with plan text?" [label="no"]; + "Finding conflicts with plan text?" -> "Ask human partner which governs" [label="yes"]; + "Ask human partner which governs" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model"; + "Finding conflicts with plan text?" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [label="no"]; + "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" -> "Dispatch scoped re-review (./re-review-prompt.md)"; + "Dispatch scoped re-review (./re-review-prompt.md)" -> "All findings addressed?"; + "All findings addressed?" -> "Append completion to ledger, mark todo complete" [label="yes"]; + "All findings addressed?" -> "R = 5?" [label="no"]; + "R = 5?" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [label="no - next round"]; + "R = 5?" -> "Adjudicate each open finding" [label="yes - breaker trips"]; + "Adjudicate each open finding" -> "Any load-bearing finding?"; + "Any load-bearing finding?" -> "STOP: report BLOCKED to human partner" [label="yes"]; + "Any load-bearing finding?" -> "Park findings in ledger with rulings" [label="no"]; + "Park findings in ledger with rulings" -> "Append completion to ledger, mark todo complete"; + "Append completion to ledger, mark todo complete" -> "More tasks remain?"; "More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"]; - "More tasks remain?" -> "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" [label="no"]; - "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" -> "Final review clean: delete this plan's workspace"; + "More tasks remain?" -> "Dispatch final code reviewer (../requesting-code-review/code-reviewer.md)" [label="no"]; + "Dispatch final code reviewer (../requesting-code-review/code-reviewer.md)" -> "Final findings? ONE fix dispatch, one scoped re-review, adjudicate residuals"; + "Final findings? ONE fix dispatch, one scoped re-review, adjudicate residuals" -> "Final review clean: delete this plan's workspace"; "Final review clean: delete this plan's workspace" -> "Use superpowers:finishing-a-development-branch"; } ``` -## Pre-Flight Plan Review +## Setup Ensure the work happens in an isolated workspace: use superpowers:using-git-worktrees to create one or verify the existing one. +Never start implementation on a main/master branch without your human +partner's explicit consent. + +Conversation memory does not survive compaction. In real sessions, +controllers that lost their place have re-dispatched entire completed task +sequences — the single most expensive failure observed. Track progress in +a ledger file, not only in todos. + +- Each plan owns a workspace: at skill start, run this skill's + `scripts/sdd-workspace PLAN_FILE` — it prints the plan's git-ignored + directory (`/.superpowers/sdd//`), home to + every artifact for THIS plan: ledger, briefs, reports, review packages. + Another plan's directory is never yours to read or write. +- Check for this plan's ledger at `/progress.md`. If its first + line names your plan file, tasks with a `Task : complete` line are DONE + — do not re-dispatch them; resume at the first task without one. A task + whose last line is a fix round is mid-loop: resume the loop at the next + round. A ledger whose first line names a different plan file — or a stray + ledger at the old flat path `.superpowers/sdd/progress.md` — is another + plan's progress: leave it in place and start your own, fresh. +- Create the ledger with its identity as the first line: + `# SDD ledger — plan: `. +- The ledger is your recovery map: the commits it names exist in git even + when your context no longer remembers creating them. After compaction, + trust the ledger and `git log` over your own recollection. +- `git clean -fdx` will destroy the workspace (it's git-ignored scratch); if + that happens, recover from `git log`. + +Read the plan once, note its context and Global Constraints, and create a +todo per task. Before dispatching Task 1, scan the plan once for conflicts: @@ -115,7 +168,11 @@ capable available model, not the session default. **Review tasks**: choose the model with the same judgment, scaled to the diff's size, complexity, and risk. A small mechanical diff does not need the -most capable model; a subtle concurrency change does. +most capable model; a subtle concurrency change does. Scoped re-reviews of +small fix diffs take a cheap-to-mid tier. + +**Fix-loop escalation (rounds 4-5)**: use a model at least one tier above +the implementer that got stuck. **Always specify the model explicitly when dispatching a subagent.** An omitted model inherits your session's model — often the most capable and @@ -134,7 +191,47 @@ that implementer. Single-file mechanical fixes also take the cheapest tier. - Touches multiple files with integration concerns → standard model - Requires design judgment or broad codebase understanding → most capable model -## Handling Implementer Status +## The Task Loop + +Everything you paste into a dispatch prompt — and everything a subagent +prints back — stays resident in your context for the rest of the session +and is re-read on every later turn. Hand artifacts over as files. + +### 1. Dispatch the implementer + +Record BASE (`git rev-parse HEAD`) before dispatching — the review package +and fix-round diffs need it. + +- **Task brief:** before dispatching an implementer, run this skill's + `scripts/task-brief PLAN_FILE N` — it extracts the task's full text to a + uniquely named file and prints the path. Compose the dispatch so the + brief stays the single source of + requirements. Your dispatch should contain: (1) one line on where this + task fits in the project; (2) the brief path, introduced as "read this + first — it is your requirements, with the exact values to use verbatim"; + (3) interfaces and decisions from earlier tasks that the brief cannot + know; (4) your resolution of any ambiguity you noticed in the brief; + (5) the report-file path and report contract. Exact values (numbers, + magic strings, signatures, test cases) appear only in the brief. Never + make a subagent read the whole plan file. +- **Report file:** name the implementer's report file after the brief + (brief `…/task-N-brief.md` → report `…/task-N-report.md`) and put it in + the dispatch prompt. The implementer writes the full report there and + returns only status, commits, a one-line test summary, and concerns. +- A dispatch prompt describes one task, not the session's history. Do not + paste accumulated prior-task summaries ("state after Tasks 1-3") into + later dispatches — a real session's dispatch hit 42k chars of which 99% + was pasted history. A fresh subagent needs its task, the interfaces it + touches, and the global constraints. Nothing else. +- If an earlier task parked a finding in the area this task touches, carry + a pointer to that ledger entry in the dispatch. +- Record the implementer's agent identity from the dispatch result — + fix-loop rounds 1-3 resume this agent. +- Never dispatch multiple implementation subagents in parallel (conflicts). + +Template: [implementer-prompt.md](implementer-prompt.md) + +### 2. Handle the report Implementer subagents report one of four statuses. Handle each appropriately: @@ -152,20 +249,37 @@ Implementer subagents report one of four statuses. Handle each appropriately: **Never** ignore an escalation or force the same model to retry without changes. If the implementer said it's stuck, something needs to change. -## Handling Reviewer ⚠️ Items +If the implementer asks questions — before starting or mid-task — answer +clearly and completely, provide additional context if needed, and don't +rush it into implementation. -The task reviewer may report "⚠️ Cannot verify from diff" items — requirements -that live in unchanged code or span tasks. These do not block the rest of the -review, but you must resolve each one yourself before marking the task -complete: you hold the plan and cross-task context the reviewer -lacks. If you confirm an item is a real gap, treat it as a failed spec -review — send it back to the implementer and re-review. - -## Constructing Reviewer Prompts +### 3. Review the task Per-task reviews are task-scoped gates. The broad review happens once, at the -final whole-branch review. When you fill a reviewer template: +final whole-branch review. Never skip the task review, and never accept a +report missing either verdict — spec compliance AND task quality are both +required. Implementer self-review never replaces the task review; both are +needed. +- Hand the reviewer its diff as a file: run this skill's + `scripts/review-package PLAN_FILE BASE HEAD` and pass the reviewer the file path + it prints (or, without bash: `git log --oneline`, `git diff --stat`, + and `git diff -U10` for the range, redirected to one uniquely named + file). The output never enters your own context, and the reviewer sees + the commit list, stat summary, and full diff with context in one Read + call. Use the BASE you recorded before dispatching the implementer — + never `HEAD~1`, which silently truncates multi-commit tasks. Never + dispatch a task reviewer without a diff file. +- **Reviewer inputs:** the task reviewer gets three paths — the same brief + file, the report file, and the review package — plus the global + constraints that bind the task. +- The global-constraints block you hand the reviewer is its attention + lens. Copy the binding requirements verbatim from the plan's Global + Constraints section or the spec: exact values, exact formats, and the + stated relationships between components ("same layout as X", "matches + Y"). The reviewer's template already carries the process rules (YAGNI, + test hygiene, review method) — the constraints block is for what THIS + project's spec demands. - Do not add open-ended directives like "check all uses" or "run race tests if useful" without a concrete, task-specific reason - Do not ask a reviewer to re-run tests the implementer already ran on the @@ -176,122 +290,157 @@ final whole-branch review. When you fill a reviewer template: loop. If the prompt you are writing contains "do not flag," "don't treat X as a defect," "at most Minor," or "the plan chose" — stop: you are pre-judging, usually to spare yourself a review loop. -- The global-constraints block you hand the reviewer is its attention - lens. Copy the binding requirements verbatim from the plan's Global - Constraints section or the spec: exact values, exact formats, and the - stated relationships between components ("same layout as X", "matches - Y"). The reviewer's template already carries the process rules (YAGNI, - test hygiene, review method) — the constraints block is for what THIS - project's spec demands. -- Hand the reviewer its diff as a file: run this skill's - `scripts/review-package PLAN_FILE BASE HEAD` and pass the reviewer the - file path it prints (or, without bash: `git log --oneline`, - `git diff --stat`, and `git diff -U10` for the range, redirected to one - uniquely named file). The output never enters your own context, and the reviewer sees - the commit list, stat summary, and full diff with context in one Read - call. Use the BASE you recorded before dispatching the implementer — - never `HEAD~1`, which silently truncates multi-commit tasks. -- A dispatch prompt describes one task, not the session's history. Do not - paste accumulated prior-task summaries ("state after Tasks 1-3") into - later dispatches — a real session's dispatch hit 42k chars of which 99% - was pasted history. A fresh subagent needs its task, the interfaces it - touches, and the global constraints. Nothing else. -- Dispatch fix subagents for Critical and Important findings. Record Minor - findings in the progress ledger as you go, and point the final +The task reviewer may report "⚠️ Cannot verify from diff" items — requirements +that live in unchanged code or span tasks. These do not block the rest of the +review, but you must resolve each one yourself before marking the task +complete: you hold the plan and cross-task context the reviewer +lacks. If you confirm an item is a real gap, treat it as a failed spec +review — it enters the fix loop with the other findings. + +Template: [task-reviewer-prompt.md](task-reviewer-prompt.md) + +### 4. The fix loop + +The loop triggers when the review reports spec ❌, any Critical or Important +finding, or a ⚠️ item you confirmed as a real gap. + +Before the loop starts, two routes leave it immediately: + +- Record Minor findings in the progress ledger as you go + (`Task : minor (deferred): `), and point the final whole-branch review at that list so it can triage which must be fixed - before merge. A roll-up nobody reads is a silent discard. + before merge. A roll-up nobody reads is a silent discard. Minor findings + never enter the loop. - A finding labeled plan-mandated — or any finding that conflicts with what the plan's text requires — is the human's decision, like any plan contradiction: present the finding and the plan text, ask which governs. Do not dismiss the finding because the plan mandates it, and do not dispatch a fix that contradicts the plan without asking. -- The final whole-branch review gets a package too: run - `scripts/review-package PLAN_FILE MERGE_BASE HEAD` (MERGE_BASE = the - commit the branch started from, e.g. `git merge-base main HEAD`) and include the - printed path in the final review dispatch, so the final reviewer reads - one file instead of re-deriving the branch diff with git commands. -- Every fix dispatch carries the implementer contract: the fix subagent - re-runs the tests covering its change and reports the results. Name the - covering test files in the dispatch — a one-line fix does not need the - whole suite. Before re-dispatching the reviewer, confirm the fix report - contains the covering tests, the command run, and the output; dispatch - the re-review once all three are present. -- If the final whole-branch review returns findings, dispatch ONE fix - subagent with the complete findings list — not one fixer per finding. - Per-finding fixers each rebuild context and re-run suites; a real - session's final-review fix wave cost more than all its tasks combined. +Everything else enters the loop. A fix round is one fix dispatch plus one +scoped re-review. Five rounds maximum per task: -## File Handoffs +**Rounds 1-3 — resume the original implementer.** Send it the open findings +verbatim. Its context is intact: it knows the task, the code, and its own +choices. If your harness cannot send another message to a live subagent, +dispatch a fresh implementer carrying the brief path, the report-file path, +and the findings — the report file is the persistent memory either way. -Everything you paste into a dispatch prompt — and everything a subagent -prints back — stays resident in your context for the rest of the session -and is re-read on every later turn. Hand artifacts over as files: +**Rounds 4-5 — dispatch a fresh implementer on a more capable model** (per +Model Selection), with the brief path, the report-file path, the open +findings, and this framing: "A prior implementer attempted this task +[N] times; you own it now. Read the report file for what was tried." A loop +that survives three resumes usually means the implementer cannot see its +own problem — fresh eyes and a capability bump in one move. -- **Task brief:** before dispatching an implementer, run this skill's - `scripts/task-brief PLAN_FILE N` — it extracts the task's full text to a - uniquely named file and prints the path. Compose the dispatch so the - brief stays the single source of requirements. Your dispatch should - contain: (1) one line on where this task fits in the project; (2) the - brief path, introduced as "read this first — it is your requirements, - with the exact values to use verbatim"; (3) interfaces and decisions - from earlier tasks that the brief cannot know; (4) your resolution of - any ambiguity you noticed in the brief; (5) the report-file path and - report contract. Exact values (numbers, magic strings, signatures, test - cases) appear only in the brief. -- **Report file:** name the implementer's report file after the brief - (brief `…/task-N-brief.md` → report `…/task-N-report.md`) and put it in - the dispatch prompt. The implementer writes the full report there and - returns only status, commits, a one-line test summary, and concerns. -- **Reviewer inputs:** the task reviewer gets three paths — the same brief - file, the report file, and the review package — plus the global - constraints that bind the task. -- Fix dispatches append their fix report (with test results) to the same - report file and return a short summary; re-reviews read the updated file. +**Every round, either way:** the implementer fixes, re-runs the tests +covering the amended code, appends its fix report to the same report file, +and returns the short contract. Before re-dispatching the reviewer, confirm +the fix report contains the covering tests, the command run, and the +output; dispatch the re-review once all three are present. Name the +covering test files in the fix message — a one-line fix does not need the +whole suite. -## Durable Progress +**The re-review is scoped.** Run `scripts/review-package PLAN_FILE FIX_BASE HEAD` +where FIX_BASE is the head the previous review saw, and dispatch +[re-review-prompt.md](re-review-prompt.md) with the findings list, the +brief, the report file, and the printed diff path. The re-reviewer verdicts +each finding ADDRESSED or NOT ADDRESSED and flags new breakage in the fix +diff only. New Critical/Important breakage in the fix diff joins the open +findings list. Out-of-scope observations go to the ledger as deferred +minors — they never extend the loop. -Conversation memory does not survive compaction. In real sessions, -controllers that lost their place have re-dispatched entire completed task -sequences — the single most expensive failure observed. Track progress in -a ledger file, not only in todos. +**After each round,** append to the ledger: +`Task : fix round /5 ( addressed, open — ; commits ..)` -- Each plan owns a workspace: at skill start, run this skill's - `scripts/sdd-workspace PLAN_FILE` — it prints the plan's git-ignored - directory (`/.superpowers/sdd//`), home to - every artifact for THIS plan: ledger, briefs, reports, review packages. - Another plan's directory is never yours to read or write. -- Check for this plan's ledger at `/progress.md`. If its first - line names your plan file, tasks listed there as complete are DONE — do - not re-dispatch them; resume at the first task not marked complete. A - ledger whose first line names a different plan file — or a stray ledger - at the old flat path `.superpowers/sdd/progress.md` — is another plan's - progress: leave it in place and start your own, fresh. -- Create the ledger with its identity as the first line: - `# SDD ledger — plan: `. -- When a task's review comes back clean, append one line to the ledger in - the same message as your other bookkeeping: - `Task N: complete (commits .., review clean)`. -- The ledger is your recovery map: the commits it names exist in git even - when your context no longer remembers creating them. After compaction, - trust the ledger and `git log` over your own recollection. -- `git clean -fdx` will destroy the workspace (it's git-ignored scratch); if - that happens, recover from `git log`. -- When the final whole-branch review is clean and its fixes are merged, - delete this plan's workspace (`rm -rf `) — the git history - is the record now. Sibling directories belong to other plans; leave - them alone. +Never fix findings yourself in the controller session — your context stays +clean for coordination, and controller fixes skip review. -## Prompt Templates +**The breaker.** When round 5's re-review still leaves findings open, stop +dispatching. Adjudicate each open finding yourself — you hold the plan and +the cross-task context the reviewer lacks: -- [implementer-prompt.md](implementer-prompt.md) - Dispatch implementer subagent -- [task-reviewer-prompt.md](task-reviewer-prompt.md) - Dispatch task reviewer subagent (spec compliance + code quality) -- Final whole-branch review: use superpowers:requesting-code-review's [code-reviewer.md](../requesting-code-review/code-reviewer.md) +- **The reviewer is wrong, or the point is contestable:** park it — + `Task : parked — — ruling: `. The final + review sees both sides. +- **Real, but nothing downstream builds on it:** park it the same way, with + a ruling that says it's real and deferred. +- **Real and load-bearing** — a later task builds on it, or it reveals a + plan defect: STOP. Append `Task : BLOCKED — ` and report to + your human partner with the finding, the plan text it collides with, and + the fix history. Parking a structural failure lets every dependent task + build on it and hands the final review a problem it cannot fix either. + +Adjudicate only at the cap. Adjudicating earlier to end a loop is +pre-judging with a different name. Every adjudication is a ledger entry — +a silent discard is forbidden. + +### 5. Complete the task + +When the review comes back clean — or every open finding is parked with a +ruling at the cap — append the completion line to the ledger in the same +message as your other bookkeeping: + +- `Task : complete (commits .., review clean)` +- `Task : complete (commits .., parked)` after a + tripped breaker + +Then mark the todo complete and move on. Never move to the next task while +the review has open Critical/Important issues that are neither fixed nor +parked-with-ruling at the cap. + +## Final Review + +The final whole-branch review gets a package too: run +`scripts/review-package PLAN_FILE MERGE_BASE HEAD` (MERGE_BASE = the commit the +branch started from, e.g. `git merge-base main HEAD`) and include the +printed path in the final review dispatch, so the final reviewer reads +one file instead of re-deriving the branch diff with git commands. Dispatch +on the most capable available model (see Model Selection), using +superpowers:requesting-code-review's +[code-reviewer.md](../requesting-code-review/code-reviewer.md). Point it at +the ledger's deferred-minor and parked lines so it can triage which must be +fixed before merge. + +If the final whole-branch review returns findings, dispatch ONE fix subagent +with the complete findings list — not one fixer per finding. +Per-finding fixers each rebuild context and re-run suites; a real +session's final-review fix wave cost more than all its tasks combined. +Then run exactly one scoped re-review of the fix wave +(`scripts/review-package PLAN_FILE FIX_BASE HEAD` over the fix range, +[re-review-prompt.md](re-review-prompt.md)). +Adjudicate any residual findings as in the task loop's breaker: park with +rulings, or stop on load-bearing ones. There is no second fix wave — +residual load-bearing findings surface to your human partner when +finishing-a-development-branch presents the options. + +## Finish + +When the final whole-branch review is clean and its fixes are merged, +delete this plan's workspace (`rm -rf `) — the git history is +the record now. Sibling directories belong to other plans; leave them +alone. + +Use superpowers:finishing-a-development-branch. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Close enough on spec compliance" | Reviewer found spec gaps = not done. Fix or hit the cap and adjudicate — those are the only exits. | +| "I'll fix it myself, dispatching is overhead" | Controller fixes pollute your context and skip review. Resume the implementer. | +| "One more round will converge" | Past the cap, rounds don't converge — the failure is structural. Adjudicate and route. | +| "The reviewer will just find something new anyway" | Scoped re-reviews verify fixes; they cannot wander. New findings on untouched code go to the ledger, not the loop. | +| "This finding is obviously wrong, I'll drop it" | You adjudicate only at the cap, and every ruling is a ledger entry. Silent discards are forbidden. | +| "The fix was small, skip the re-review" | Unreviewed fixes are how regressions land. Every round ends with a scoped re-review. | +| "Reviews slow the loop down" | The loop without reviews is just unverified churn. Reviews are the loop's brakes and steering. | +| "Ledger bookkeeping is overhead" | The ledger is what survives compaction. Controllers without one have re-dispatched entire completed task sequences. | ## Example Workflow ``` You: I'm using Subagent-Driven Development to execute this plan. +[Setup: worktree verified] [Read plan file once: docs/superpowers/plans/feature-plan.md] [Resolve workspace: scripts/sdd-workspace docs/superpowers/plans/feature-plan.md — no ledger inside, fresh start] [Create todos for all tasks] @@ -304,90 +453,51 @@ Implementer: "Before I begin - should the hook be installed at user or system le You: "User level (~/.config/superpowers/hooks/)" -Implementer: "Got it. Implementing now..." -[Later] Implementer: +Implementer: [Later] - Implemented install-hook command - Added tests, 5/5 passing - Self-review: Found I missed --force flag, added it - Committed -[Run review-package, dispatch task reviewer with the printed path] +[Run review-package PLAN_FILE BASE HEAD; dispatch task reviewer with the printed path] Task reviewer: Spec ✅ - all requirements met, nothing extra. Strengths: Good test coverage, clean. Issues: None. Task quality: Approved. -[Mark Task 1 complete] +[Ledger: Task 1: complete (commits a1b2c3d..d4e5f6a, review clean)] Task 2: Recovery modes [Run task-brief for Task 2; dispatch implementer with brief + report paths + context] -Implementer: [No questions, proceeds] -Implementer: +Implementer: [No questions] - Added verify/repair modes - 8/8 tests passing - - Self-review: All good - Committed -[Run review-package, dispatch task reviewer with the printed path] +[Run review-package PLAN_FILE BASE HEAD; dispatch task reviewer with the printed path] Task reviewer: Spec ❌: - Missing: Progress reporting (spec says "report every 100 items") - - Extra: Added --json flag (not requested) Issues (Important): Magic number (100) -[Dispatch fix subagent with all findings] -Fixer: Removed --json flag, added progress reporting, extracted PROGRESS_INTERVAL constant +[Fix round 1: resume the implementer with both findings] +Implementer: Added progress reporting, extracted PROGRESS_INTERVAL constant. + Re-ran test/recovery.test.js — 10/10 passing. Fix report appended. -[Task reviewer reviews again] -Task reviewer: Spec ✅. Task quality: Approved. +[Run review-package PLAN_FILE FIX_BASE HEAD; dispatch scoped re-review] +Re-reviewer: Missing progress reporting — ADDRESSED (src/recovery.js:41). + Magic number — ADDRESSED (src/recovery.js:7). New breakage: none. + Verdict: all findings addressed. -[Mark Task 2 complete] +[Ledger: Task 2: fix round 1/5 (2 addressed, 0 open; commits d4e5f6a..b7c8d9e)] +[Ledger: Task 2: complete (commits d4e5f6a..b7c8d9e, review clean)] ... [After all tasks] -[Dispatch final code-reviewer] -Final reviewer: All requirements met, ready to merge +[Run review-package PLAN_FILE MERGE_BASE HEAD; dispatch final code-reviewer, most capable model] +Final reviewer: All requirements met. Deferred minors triaged: none block merge. [Delete this plan's workspace — the record now lives in git] -Done! +Done! Using superpowers:finishing-a-development-branch. ``` - -## Red Flags - -**Never:** -- Start implementation on main/master branch without explicit user consent -- Skip task review, or accept a report missing either verdict (spec compliance AND task quality are both required) -- Proceed with unfixed issues -- Dispatch multiple implementation subagents in parallel (conflicts) -- Make a subagent read the whole plan file (hand it its task brief — - `scripts/task-brief` — 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 (reviewer found spec issues = not done) -- Skip review loops (reviewer found issues = implementer fixes = review again) -- Let implementer self-review replace actual review (both are needed) -- Tell a reviewer what not to flag, or pre-rate a finding's severity in the - dispatch prompt ("treat it as Minor at most") — the plan's example code is - a starting point, not evidence that its weaknesses were chosen -- Dispatch a task reviewer without a diff file — generate it first - (`scripts/review-package PLAN_FILE BASE HEAD`) and name the printed - path in the prompt -- Move to next task while the review has open Critical/Important issues -- Re-dispatch a task the progress ledger already marks complete — check - the ledger (and `git log`) after any compaction or resume - -**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) diff --git a/skills/subagent-driven-development/re-review-prompt.md b/skills/subagent-driven-development/re-review-prompt.md index 84a45a461..18b0fb8ad 100644 --- a/skills/subagent-driven-development/re-review-prompt.md +++ b/skills/subagent-driven-development/re-review-prompt.md @@ -100,7 +100,7 @@ Subagent (general-purpose): - `[REPORT_FILE]` — the implementer's report file (fix reports appended) - `[FIX_BASE_SHA]` — the head the previous review saw - `[HEAD_SHA]` — current commit -- `[DIFF_FILE]` — the path `scripts/review-package FIX_BASE HEAD` printed +- `[DIFF_FILE]` — the path `scripts/review-package PLAN_FILE FIX_BASE HEAD` printed **Re-reviewer returns:** per-finding verdicts (ADDRESSED / NOT ADDRESSED), new breakage in the fix diff, out-of-scope observations, and a round verdict. From 55d28ddf1066736bc10483c3c29f8770d911f7a9 Mon Sep 17 00:00:00 2001 From: Mark Rada Date: Thu, 23 Jul 2026 13:47:44 -0400 Subject: [PATCH 059/198] docs(using-superpowers): drop dangling subagent-support anchor (#2010) The prune in e7ddc25e removed the `## Subagent support` section from antigravity-tools.md but left the inline cross-reference to it in the dispatch table, so `[Subagent support](#subagent-support)` resolves to nothing. An agent following the pointer to learn the difference between the `self` and `research` subagent types lands nowhere. Drop the dangling parenthetical. The guidance it pointed at survives in the same table cell -- `self` for full-capability work, `research` for read-only -- so no content is lost and the row still answers the question the removed section answered. gemini-tools.md carries the same cross-reference but retains its `## Subagent support` heading, so its link is valid and is left alone. --- skills/using-superpowers/references/antigravity-tools.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/using-superpowers/references/antigravity-tools.md b/skills/using-superpowers/references/antigravity-tools.md index 71155fde8..2e1eac905 100644 --- a/skills/using-superpowers/references/antigravity-tools.md +++ b/skills/using-superpowers/references/antigravity-tools.md @@ -4,7 +4,7 @@ Skills speak in actions ("dispatch a subagent", "create a todo", "read a file"). | Action skills request | Antigravity CLI equivalent | |----------------------|----------------------| -| Dispatch a subagent (`Subagent (general-purpose):` template) | `invoke_subagent` with a built-in `TypeName` — `self` for full-capability work, `research` for read-only (see [Subagent support](#subagent-support)) | +| Dispatch a subagent (`Subagent (general-purpose):` template) | `invoke_subagent` with a built-in `TypeName` — `self` for full-capability work, `research` for read-only | | Task tracking ("create a todo", "mark complete") | a **task artifact** — `write_to_file` with `IsArtifact: true` and `ArtifactType: "task"` (see [Task tracking](#task-tracking)). **Not** `manage_task`, which manages background processes. | ## Task tracking From 54d0efefd7ce56b82dd32402d26f6aaa3ab75f21 Mon Sep 17 00:00:00 2001 From: dev_Hakaze Date: Fri, 24 Jul 2026 00:53:39 +0700 Subject: [PATCH 060/198] fix(systematic-debugging): match find -path ./ prefix in find-polluter.sh (#2011) find . emits ./-prefixed paths, so -path "src/**/*.test.ts" matched nothing; wc -l on empty stdin then lied as "Found 1". Fixes #2008. Co-authored-by: arimu1 <19286898+arimu1@users.noreply.github.com> Co-authored-by: Cursor --- skills/systematic-debugging/find-polluter.sh | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/skills/systematic-debugging/find-polluter.sh b/skills/systematic-debugging/find-polluter.sh index 1d71c5607..d2261c466 100755 --- a/skills/systematic-debugging/find-polluter.sh +++ b/skills/systematic-debugging/find-polluter.sh @@ -18,9 +18,13 @@ 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 ' ') +# Get list of test files (find . emits ./-prefixed paths) +TEST_FILES=$(find . -path "./$TEST_PATTERN" | sort) +if [ -z "$TEST_FILES" ]; then + TOTAL=0 +else + TOTAL=$(printf '%s\n' "$TEST_FILES" | wc -l | tr -d ' ') +fi echo "Found $TOTAL test files" echo "" From 0146173544e48a6bc970b2a7cca1e16c2c697a6d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 23 Jul 2026 10:54:50 -0700 Subject: [PATCH 061/198] fix(systematic-debugging): find-polluter accepts ./-prefixed patterns and matches top-level tests Follow-up to #2011 (which fixed the ./-prefix mismatch for the documented pattern form): strip a leading ./ from the caller's pattern instead of double-prefixing it into a never-matching ././ form, and also match the pattern with '**/' collapsed, since find -path cannot match '**/' against zero directory levels and silently skipped files directly under the base directory (src/top.test.ts vs src/**/*.test.ts). Adds a deterministic test suite for the script with a stubbed npm. --- skills/systematic-debugging/find-polluter.sh | 9 +- .../test-find-polluter.sh | 90 +++++++++++++++++++ 2 files changed, 97 insertions(+), 2 deletions(-) create mode 100755 tests/systematic-debugging/test-find-polluter.sh diff --git a/skills/systematic-debugging/find-polluter.sh b/skills/systematic-debugging/find-polluter.sh index d2261c466..985f5d08c 100755 --- a/skills/systematic-debugging/find-polluter.sh +++ b/skills/systematic-debugging/find-polluter.sh @@ -18,8 +18,13 @@ echo "🔍 Searching for test that creates: $POLLUTION_CHECK" echo "Test pattern: $TEST_PATTERN" echo "" -# Get list of test files (find . emits ./-prefixed paths) -TEST_FILES=$(find . -path "./$TEST_PATTERN" | sort) +# Get list of test files (find . emits ./-prefixed paths, so accept the +# pattern written with or without a leading ./) +TEST_PATTERN="${TEST_PATTERN#./}" +# find -path can't match '**/' against zero directory levels, so a pattern +# like src/**/*.test.ts would skip src/top.test.ts; also try the pattern +# with '**/' collapsed to cover files directly under the base directory. +TEST_FILES=$(find . \( -path "./$TEST_PATTERN" -o -path "./${TEST_PATTERN//\*\*\//}" \) | sort -u) if [ -z "$TEST_FILES" ]; then TOTAL=0 else diff --git a/tests/systematic-debugging/test-find-polluter.sh b/tests/systematic-debugging/test-find-polluter.sh new file mode 100755 index 000000000..0902e7d9d --- /dev/null +++ b/tests/systematic-debugging/test-find-polluter.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +SCRIPT_UNDER_TEST="$REPO_ROOT/skills/systematic-debugging/find-polluter.sh" + +FAILURES=0 +TEST_ROOT="$(mktemp -d)" + +cleanup() { + rm -rf "$TEST_ROOT" +} +trap cleanup EXIT + +pass() { + echo " [PASS] $1" +} + +fail() { + echo " [FAIL] $1" + FAILURES=$((FAILURES + 1)) +} + +assert_contains() { + local haystack="$1" + local needle="$2" + local description="$3" + + if printf '%s' "$haystack" | grep -Fq -- "$needle"; then + pass "$description" + else + fail "$description (expected output to contain: $needle)" + fi +} + +# Toy project: one top-level test, one nested test. A stubbed `npm` on PATH +# creates the pollution marker whenever any test runs, so the first test file +# executed is always identified as the polluter. +setup_project() { + PROJECT="$TEST_ROOT/project" + rm -rf "$PROJECT" + mkdir -p "$PROJECT/src/feature" "$PROJECT/bin" + echo "test('top')" > "$PROJECT/src/top.test.ts" + echo "test('nested')" > "$PROJECT/src/feature/nested.test.ts" + cat > "$PROJECT/bin/npm" <<'EOF' +#!/usr/bin/env bash +touch pollution.marker +EOF + chmod +x "$PROJECT/bin/npm" +} + +# run_polluter — runs the script in the toy project with the stub +# npm first on PATH; captures combined output, never aborts on exit code. +run_polluter() { + local pattern="$1" + rm -f "$PROJECT/pollution.marker" + ( + cd "$PROJECT" + PATH="$PROJECT/bin:$PATH" "$SCRIPT_UNDER_TEST" 'pollution.marker' "$pattern" 2>&1 + ) || true +} + +echo "Test: documented pattern finds nested test files (issue #2008)" +setup_project +OUTPUT="$(run_polluter 'src/**/*.test.ts')" +assert_contains "$OUTPUT" "FOUND POLLUTER" "documented pattern runs tests and detects pollution" + +echo "Test: documented pattern also finds top-level test files" +setup_project +OUTPUT="$(run_polluter 'src/**/*.test.ts')" +assert_contains "$OUTPUT" "Found 2 test files" "src/**/*.test.ts matches src/top.test.ts and src/feature/nested.test.ts" + +echo "Test: ./-prefixed pattern matches the same files" +setup_project +OUTPUT="$(run_polluter './src/**/*.test.ts')" +assert_contains "$OUTPUT" "Found 2 test files" "leading ./ on the pattern is accepted" + +echo "Test: non-matching pattern reports an honest zero" +setup_project +OUTPUT="$(run_polluter 'nomatch/**/*.test.ts')" +assert_contains "$OUTPUT" "Found 0 test files" "empty result counts as 0, not 1" +assert_contains "$OUTPUT" "No polluter found" "empty result exits via the clean path" + +echo "" +if [ "$FAILURES" -gt 0 ]; then + echo "$FAILURES test(s) failed" + exit 1 +fi +echo "All tests passed" From 1f0e2ab9123f9078b0c333efcf6471f8bdd4324f Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 23 Jul 2026 11:55:24 -0700 Subject: [PATCH 062/198] fix(finishing): check in with human partner when worktree removal hits untracked files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit git worktree remove refuses when the tree holds modified or untracked files, and the skill gave no guidance for that refusal — the natural agent response was --force, permanently destroying files that exist nowhere else (uncommitted plans, notes, scratch work). Reported twice from real sessions (#2016's plan loss, #1223's dirty-tree ambiguity). Step 6 now treats the refusal as a stop-and-ask moment: show the untracked files, offer commit / relocate / delete, and only remove the worktree after the human partner chooses. Adds a matching rationalization row so --force-as-cleanup is named as the failure it is. --- .../finishing-a-development-branch/SKILL.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/skills/finishing-a-development-branch/SKILL.md b/skills/finishing-a-development-branch/SKILL.md index 21a439ac3..4ca486bef 100644 --- a/skills/finishing-a-development-branch/SKILL.md +++ b/skills/finishing-a-development-branch/SKILL.md @@ -174,6 +174,29 @@ git worktree remove "$WORKTREE_PATH" git worktree prune # Self-healing: clean up any stale registrations ``` +**If removal is refused** (`contains modified or untracked files`): the +worktree holds files that exist nowhere else — uncommitted plans, notes, +or scratch work. Never `--force` on your own initiative. Show your human +partner what is at stake and ask: + +```bash +git -C "$WORKTREE_PATH" status --porcelain +``` + +``` +Worktree removal refused — these files were never committed: + + + +1. Commit them to before cleanup +2. Move them into
+3. Delete them (unrecoverable) + +Which? +``` + +Carry out the choice, then remove the worktree. + **Otherwise:** The host environment owns this workspace — leave it in place. If your platform provides a workspace-exit tool, use it. @@ -196,6 +219,7 @@ place. If your platform provides a workspace-exit tool, use it. | "'Yeah, get rid of it' counts as confirmation" | Only the typed word `discard` authorizes deletion. | | "The PR is up, so the worktree is clutter now" | PR feedback gets fixed in that worktree. It stays until the work lands. | | "This other worktree looks stale — I'll clean it too" | Clean up only worktrees under `.worktrees/` or `worktrees/`. Everything else belongs to the host. | +| "Removal refused — `--force` is just finishing the cleanup" | The refusal means files exist only in that worktree. `--force` destroys them permanently. Show your human partner and ask. | | "The merged-result failure is probably flaky" | A failing merged result stops everything. Branch and worktree stay put while you investigate. | | "The base branch is obviously main" | Confirm the fork point or ask. Merging into the wrong base is expensive to undo. | | "The push was rejected — force-push will fix it" | A rejected push means the remote moved. Investigate; force-push only on your human partner's explicit request. | From 7b177613c03a00042e67422dce8fc7814ae248c3 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 23 Jul 2026 12:18:13 -0700 Subject: [PATCH 063/198] feat(hermes): Hermes Agent harness support, rebased to a Hermes-only diff Rebase of PR #1922 onto current dev: the ~14 files of v6.1.0-era codex/release drift are dropped, the porting-guide edits (stale against the post-prune rewrite, no Hermes content) are dropped, and the Hermes surface is kept intact: .hermes-plugin/ (on_session_start bootstrap injection), tests/hermes/ (20 tests, passing), docs/README.hermes.md, references/hermes-tools.md, the Platform Adaptation row, README section, and Python ignores. Known open items from review, unchanged by this rebase: the injection mechanism uses ctx.inject_message from on_session_start, which the official plugin guide does not document (pre_llm_call returning {"context": ...} is the sanctioned path), skills are not registered via ctx.register_skill, and the acceptance transcript predates the fix. Co-authored-by: kumarabd --- .gitignore | 6 + .hermes-plugin/INSTALL.md | 30 +++++ .hermes-plugin/__init__.py | 101 +++++++++++++++++ .hermes-plugin/plugin.yaml | 6 + README.md | 14 ++- docs/README.hermes.md | 29 +++++ skills/using-superpowers/SKILL.md | 1 + .../references/hermes-tools.md | 56 ++++++++++ tests/hermes/__init__.py | 0 tests/hermes/conftest.py | 19 ++++ tests/hermes/test_bootstrap.py | 81 ++++++++++++++ tests/hermes/test_plugin.py | 105 ++++++++++++++++++ 12 files changed, 447 insertions(+), 1 deletion(-) create mode 100644 .hermes-plugin/INSTALL.md create mode 100644 .hermes-plugin/__init__.py create mode 100644 .hermes-plugin/plugin.yaml create mode 100644 docs/README.hermes.md create mode 100644 skills/using-superpowers/references/hermes-tools.md create mode 100644 tests/hermes/__init__.py create mode 100644 tests/hermes/conftest.py create mode 100644 tests/hermes/test_bootstrap.py create mode 100644 tests/hermes/test_plugin.py diff --git a/.gitignore b/.gitignore index 211864956..efa95832b 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,9 @@ triage/ # development (see CLAUDE.md / README.md). It is not part of the published # plugin, so the whole directory is ignored here. evals/ + +# Python +__pycache__/ +*.pyc +*.pyo +.pytest_cache/ diff --git a/.hermes-plugin/INSTALL.md b/.hermes-plugin/INSTALL.md new file mode 100644 index 000000000..b08ef5b1d --- /dev/null +++ b/.hermes-plugin/INSTALL.md @@ -0,0 +1,30 @@ +# Hermes Agent — Superpowers Plugin + +## Install + +```bash +hermes plugins install obra/superpowers --enable +``` + +Restart any active Hermes sessions after installing. + +## Smoke check + +Start a new session and send: +> What are your superpowers? + +The model should describe brainstorming, TDD, debugging, and planning skills. +If it doesn't, the bootstrap isn't loading — reinstall and restart. + +## Acceptance test + +Send in a fresh session: +> Let's make a react todo list + +The `brainstorming` skill must trigger and run its flow before any code is written. + +## Uninstall + +```bash +hermes plugins remove superpowers +``` diff --git a/.hermes-plugin/__init__.py b/.hermes-plugin/__init__.py new file mode 100644 index 000000000..663d7b42a --- /dev/null +++ b/.hermes-plugin/__init__.py @@ -0,0 +1,101 @@ +import os +import re +from typing import Optional + +BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes" + +# Resolved once at import — avoids repeated path work on every session-start. +# hermes plugins install does a full git clone, so .hermes-plugin/__init__.py +# and skills/ end up at the same level in ~/.hermes/plugins/superpowers/. +_SKILLS_DIR: str = os.path.realpath( + os.path.join(os.path.dirname(__file__), "..", "skills") +) + +# Module-level cache: +# None = not yet assembled +# False = SKILL.md missing (skip injection silently) +# str = assembled bootstrap content +_bootstrap_cache = None + +_last_session_id = None + + +def _strip_frontmatter(content: str) -> str: + match = re.match(r"^---\n[\s\S]*?\n---\n([\s\S]*)$", content) + return (match.group(1) if match else content).strip() + + +def _hermes_tool_mapping() -> str: + # Tool names confirmed empirically in Task 1. + return """\ +## Hermes tool mapping + +When skills request actions, use these Hermes equivalents: + +| Action | Hermes tool | +|--------|-------------| +| Read a file | `read_file` | +| Create a new file | `write_file` | +| Edit a file (targeted patch) | `patch` | +| Run a shell command | `terminal` | +| Search file contents | `search_files` | +| Find files by name | `terminal` with `find` | +| Fetch a URL / read a webpage | `web_extract(urls=[...])` | +| Search the web | `web_search(query=...)` | +| Dispatch a subagent | `delegate_task(goal=..., context=..., toolsets=[...], role="leaf")` | +| Task tracking | `todo` tool | +| Invoke a skill | `skill_view("skill-name")` — this is the native skill-loading mechanism on Hermes | +""" + + +def _get_bootstrap() -> Optional[str]: + global _bootstrap_cache + if _bootstrap_cache is not None: + return None if _bootstrap_cache is False else _bootstrap_cache + + skill_path = os.path.join(_SKILLS_DIR, "using-superpowers", "SKILL.md") + if not os.path.exists(skill_path): + _bootstrap_cache = False + return None + + with open(skill_path, encoding="utf-8") as f: + raw = f.read() + + body = _strip_frontmatter(raw) + _bootstrap_cache = ( + f"\n" + f"{BOOTSTRAP_MARKER}\n\n" + f"You have superpowers.\n\n" + f"The using-superpowers skill content is included below and is already " + f"loaded for this Hermes session. Follow it now. " + f"Do not try to load using-superpowers again.\n\n" + f"{body}\n\n" + f"## Loading Superpowers Skills on Hermes\n\n" + f"Superpowers skills are NOT in Hermes' built-in skill registry — " + f"`skill_view` will return 'not found' for them. " + f"When using-superpowers tells you to invoke a skill, use this two-step:\n\n" + f"1. Try `skill_view(\"skill-name\")` first (it works for Hermes' own skills).\n" + f"2. If that returns 'not found', immediately use `read_file` instead:\n" + f" `read_file(\"{_SKILLS_DIR}/skill-name/SKILL.md\")`\n\n" + f"Example — to load the brainstorming skill:\n" + f" `read_file(\"{_SKILLS_DIR}/brainstorming/SKILL.md\")`\n\n" + f"The superpowers skills directory is: `{_SKILLS_DIR}`\n\n" + f"{_hermes_tool_mapping()}\n" + f"" + ) + return _bootstrap_cache + + +def register(ctx): + def on_session_start(**kwargs): + global _last_session_id + session_id = kwargs.get("session_id") + if session_id is not None and session_id == _last_session_id: + return + bootstrap = _get_bootstrap() + if bootstrap is None: + return + ctx.inject_message(bootstrap, role="user") + _last_session_id = session_id + + ctx.register_hook("on_session_start", on_session_start) diff --git a/.hermes-plugin/plugin.yaml b/.hermes-plugin/plugin.yaml new file mode 100644 index 000000000..d8aa14beb --- /dev/null +++ b/.hermes-plugin/plugin.yaml @@ -0,0 +1,6 @@ +name: superpowers +version: 6.0.3 +description: Superpowers skills and workflow bootstrap for Hermes Agent +author: obra +provides_hooks: + - on_session_start diff --git a/README.md b/README.md index bb398c6b6..8a781e645 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ If this sounds like someone you know, definitely send them our way. ## Quickstart -Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). +Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Hermes Agent](#hermes-agent), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). ## How it works @@ -199,6 +199,18 @@ pi -e /path/to/superpowers The Pi package loads the Superpowers skills and a small extension that injects the `using-superpowers` bootstrap at session startup and again after compaction. Pi has native skills, so no compatibility `Skill` tool is required. Subagent and task-list tools remain optional Pi companion packages. +### Hermes Agent + +Install Superpowers as a Hermes plugin from this repository: + +```bash +hermes plugins install obra/superpowers --enable +``` + +Restart any active Hermes sessions after installing. + +Detailed docs: [docs/README.hermes.md](docs/README.hermes.md) + ## The Basic Workflow 1. **brainstorming** - Activates before writing code. Refines rough ideas through questions, explores alternatives, presents design in sections for validation. Saves design document. diff --git a/docs/README.hermes.md b/docs/README.hermes.md new file mode 100644 index 000000000..0ad692c52 --- /dev/null +++ b/docs/README.hermes.md @@ -0,0 +1,29 @@ +# Hermes Agent + +Superpowers supports Hermes Agent via an in-process Python plugin (Shape B). + +## Install + +```bash +hermes plugins install obra/superpowers --enable +``` + +## What you get + +All Superpowers skills auto-trigger in Hermes sessions: +brainstorming before feature work, systematic-debugging on bugs, +test-driven-development for implementation, writing-plans before +touching code, and all other skills in `skills/`. + +## How it works + +The plugin registers an `on_session_start` hook with the Hermes plugin API. +At the start of each session, the hook injects the `using-superpowers` bootstrap +as a user-role message via `ctx.inject_message(role="user")`. A session-id guard +prevents double-injection if the hook fires more than once per session. + +Skills are loaded on demand during the session using `skill_view("skill-name")`. + +## Verifying + +See `.hermes-plugin/INSTALL.md` for the smoke check and acceptance test. diff --git a/skills/using-superpowers/SKILL.md b/skills/using-superpowers/SKILL.md index 8a08873ba..7ab2eb678 100644 --- a/skills/using-superpowers/SKILL.md +++ b/skills/using-superpowers/SKILL.md @@ -56,6 +56,7 @@ If your harness appears here, read its reference file for special instructions: - Codex: `references/codex-tools.md` - Pi: `references/pi-tools.md` - Antigravity: `references/antigravity-tools.md` +- Hermes Agent: `references/hermes-tools.md` ## User Instructions diff --git a/skills/using-superpowers/references/hermes-tools.md b/skills/using-superpowers/references/hermes-tools.md new file mode 100644 index 000000000..0f1fa57bc --- /dev/null +++ b/skills/using-superpowers/references/hermes-tools.md @@ -0,0 +1,56 @@ +# Hermes Agent Tool Mapping + +Skills speak in actions ("dispatch a subagent", "create a todo", "read a file"). On Hermes Agent these resolve to the tools below. + +## Tools + +| Action skills request | Hermes tool | +|---|---| +| Read a file | `read_file` | +| Create a new file | `write_file` | +| Edit a file (targeted patch) | `patch` | +| Run a shell command | `terminal` | +| Search file contents | `search_files` | +| Find files by name | `terminal` with `find` | +| Fetch a URL / read a webpage | `web_extract(urls=[...])` | +| Search the web | `web_search(query=...)` | +| Dispatch a subagent | `delegate_task(goal=..., context=..., toolsets=[...], role="leaf")` | +| Task tracking | `todo` tool | +| Invoke a skill | `skill_view("skill-name")` | + +## Instructions file + +When a skill mentions "your instructions file," on Hermes Agent this is **`AGENTS.md`** in the project directory, or **`SOUL.md`** globally at `~/.hermes/SOUL.md`. + +## Invoking a skill + +Hermes Agent has a `skills` toolset with `skill_view` and `skills_list` tools. +To invoke a superpowers skill, use: + +``` +skill_view("brainstorming") +skill_view("test-driven-development") +``` + +If `skill_view` cannot find a superpowers skill (it may not appear in the catalog +until the plugin fully registers it), fall back to reading the SKILL.md directly: + +``` +read_file(path="~/.hermes/plugins/superpowers/skills//SKILL.md") +``` + +This fallback is the same mechanism used by other harnesses without native skill loading. + +## Subagent dispatch + +Use `delegate_task` to spawn isolated subagents for parallel or sequential workstreams: + +``` +delegate_task(goal="...", context="...", toolsets=[...], role="leaf") +``` + +If `delegate_task` is unavailable, do the work inline rather than inventing tool calls. + +## Task tracking + +Use the `todo` tool for task tracking within a session. For multi-agent task boards, use `hermes kanban` CLI if available. Treat older `TodoWrite` references as the task-tracking action. diff --git a/tests/hermes/__init__.py b/tests/hermes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/hermes/conftest.py b/tests/hermes/conftest.py new file mode 100644 index 000000000..a4c851973 --- /dev/null +++ b/tests/hermes/conftest.py @@ -0,0 +1,19 @@ +import pytest +from unittest.mock import MagicMock + + +@pytest.fixture +def mock_ctx(): + ctx = MagicMock() + ctx._hooks = {} + ctx._injected = [] + + def register_hook(event, fn): + ctx._hooks[event] = fn + + def inject_message(content, role="user"): + ctx._injected.append({"content": content, "role": role}) + + ctx.register_hook.side_effect = register_hook + ctx.inject_message.side_effect = inject_message + return ctx diff --git a/tests/hermes/test_bootstrap.py b/tests/hermes/test_bootstrap.py new file mode 100644 index 000000000..a8e8f282e --- /dev/null +++ b/tests/hermes/test_bootstrap.py @@ -0,0 +1,81 @@ +import os +import sys +import importlib +import pytest + +sys.path.insert(0, os.path.abspath( + os.path.join(os.path.dirname(__file__), "../../.hermes-plugin") +)) + +BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes" + + +def _load(): + if "__init__" in sys.modules: + del sys.modules["__init__"] + return importlib.import_module("__init__") + + +class TestStripFrontmatter: + def test_strips_yaml_block(self): + m = _load() + content = "---\nname: foo\ndescription: bar\n---\n# Body\nContent here" + assert m._strip_frontmatter(content) == "# Body\nContent here" + + def test_no_frontmatter_returns_trimmed_content(self): + m = _load() + content = "# No frontmatter\nJust content" + assert m._strip_frontmatter(content) == "# No frontmatter\nJust content" + + def test_strips_surrounding_whitespace_from_body(self): + m = _load() + content = "---\nname: foo\n---\n\n\n# Body\n\n" + assert m._strip_frontmatter(content) == "# Body" + + +class TestGetBootstrap: + def test_returns_none_when_skill_file_missing(self, tmp_path): + m = _load() + m._bootstrap_cache = None + m._SKILLS_DIR = str(tmp_path / "nonexistent") + assert m._get_bootstrap() is None + + def test_caches_false_on_missing_file(self, tmp_path): + m = _load() + m._bootstrap_cache = None + m._SKILLS_DIR = str(tmp_path / "nonexistent") + m._get_bootstrap() + assert m._bootstrap_cache is False + + def test_returns_string_with_real_skill(self): + m = _load() + m._bootstrap_cache = None + result = m._get_bootstrap() + assert result is not None + assert isinstance(result, str) + + def test_same_object_returned_on_second_call(self): + m = _load() + m._bootstrap_cache = None + r1 = m._get_bootstrap() + r2 = m._get_bootstrap() + assert r1 is r2 + + def test_contains_marker(self): + m = _load() + m._bootstrap_cache = None + result = m._get_bootstrap() + assert BOOTSTRAP_MARKER in result + + def test_contains_extremely_important_wrapper(self): + m = _load() + m._bootstrap_cache = None + result = m._get_bootstrap() + assert result.startswith("") + assert result.rstrip().endswith("") + + def test_frontmatter_absent_from_output(self): + m = _load() + m._bootstrap_cache = None + result = m._get_bootstrap() + assert "---\nname:" not in result diff --git a/tests/hermes/test_plugin.py b/tests/hermes/test_plugin.py new file mode 100644 index 000000000..e9317a413 --- /dev/null +++ b/tests/hermes/test_plugin.py @@ -0,0 +1,105 @@ +import os +import sys +import importlib +import pytest + +# Point at the plugin directory +_PLUGIN_DIR = os.path.join(os.path.dirname(__file__), "../../.hermes-plugin") +sys.path.insert(0, os.path.abspath(_PLUGIN_DIR)) + +BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes" + + +def _load_plugin(): + """Re-import plugin module fresh (clears module-level cache).""" + if "__init__" in sys.modules: + del sys.modules["__init__"] + return importlib.import_module("__init__") + + +class TestPluginRegistration: + def test_register_attaches_session_start_hook(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + mock_ctx.register_hook.assert_called_once() + event_name = mock_ctx.register_hook.call_args[0][0] + assert event_name == "on_session_start" + + +class TestBootstrapInjection: + def test_first_session_start_injects_bootstrap(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + assert len(mock_ctx._injected) == 1 + assert BOOTSTRAP_MARKER in mock_ctx._injected[0]["content"] + + def test_injection_uses_user_role(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + assert mock_ctx._injected[0]["role"] == "user" + + def test_dedup_skips_on_same_session_id(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + handler(session_id="sess-1", model="test-model", platform="test") + assert len(mock_ctx._injected) == 1 + + def test_reinjects_on_new_session_id(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + handler(session_id="sess-2", model="test-model", platform="test") + assert len(mock_ctx._injected) == 2 + + def test_missing_skill_file_skips_silently(self, mock_ctx, tmp_path): + plugin = _load_plugin() + plugin._bootstrap_cache = None + plugin._SKILLS_DIR = str(tmp_path / "nonexistent") + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + assert len(mock_ctx._injected) == 0 + + def test_cache_populated_after_first_call(self, mock_ctx): + plugin = _load_plugin() + plugin._bootstrap_cache = None + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + assert plugin._bootstrap_cache is not None + assert plugin._bootstrap_cache is not False + + +class TestBootstrapContent: + def test_contains_extremely_important_tags(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + content = mock_ctx._injected[0]["content"] + assert "" in content + assert "" in content + + def test_frontmatter_stripped(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + content = mock_ctx._injected[0]["content"] + assert "---\nname:" not in content + + def test_tool_mapping_present(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + handler = mock_ctx._hooks["on_session_start"] + handler(session_id="sess-1", model="test-model", platform="test") + content = mock_ctx._injected[0]["content"] + assert "Hermes tool mapping" in content + assert "read_file" in content From 178528c03e7f0cc051bccf5b1249c480cb972105 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 23 Jul 2026 15:17:55 -0700 Subject: [PATCH 064/198] fix(hermes): working bootstrap injection via pre_llm_call + native skill registration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Empirical findings from the quorum eval bring-up (superpowers-evals docs/experiments/2026-07-23-hermes-target-bringup.md): - ctx.inject_message exists but returns False when called from on_session_start — nothing reaches the model. The documented path, a pre_llm_call hook returning {"context": ...} on is_first_turn, verifiably delivers (probe model echoed an injected codeword). - ctx.register_skill requires a pathlib.Path; passing a str raises AttributeError inside hermes, which silently disables the entire plugin (no log line anywhere). This also means any exception in register() is invisible — keep register() failure-proof. - Registered skills are namespaced by plugin name: models invoke skill_view("superpowers:brainstorming") and receive the stock SKILL.md — verified live on GLM 5.2, both install layouts. The plugin now: resolves skills/ for both the git-clone layout (.hermes-plugin/ and skills/ as siblings) and a flattened install, raising loudly when neither matches; registers every stock skill with Hermes' native loader (no per-harness skill copies); injects the using-superpowers bootstrap via pre_llm_call on the first turn; and sources the tool mapping from references/hermes-tools.md instead of duplicating it. Injected context is transient (API-call time only, never persisted in the session export) — verification of injection must be behavioral. --- .hermes-plugin/__init__.py | 145 +++++++++++++++++++------------------ .hermes-plugin/plugin.yaml | 2 +- 2 files changed, 75 insertions(+), 72 deletions(-) diff --git a/.hermes-plugin/__init__.py b/.hermes-plugin/__init__.py index 663d7b42a..3b41644bb 100644 --- a/.hermes-plugin/__init__.py +++ b/.hermes-plugin/__init__.py @@ -1,23 +1,35 @@ import os import re -from typing import Optional +from pathlib import Path BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes" -# Resolved once at import — avoids repeated path work on every session-start. -# hermes plugins install does a full git clone, so .hermes-plugin/__init__.py -# and skills/ end up at the same level in ~/.hermes/plugins/superpowers/. -_SKILLS_DIR: str = os.path.realpath( - os.path.join(os.path.dirname(__file__), "..", "skills") -) -# Module-level cache: -# None = not yet assembled -# False = SKILL.md missing (skip injection silently) -# str = assembled bootstrap content -_bootstrap_cache = None +def _skills_dir() -> str: + """Locate the stock skills/ tree for either supported install layout. -_last_session_id = None + - git-clone install (`hermes plugins install obra/superpowers`): the plugin + dir is the repo root, so `.hermes-plugin/` and `skills/` are siblings and + this module resolves `../skills`. + - flattened install (plugin files copied to the plugin dir root): `skills/` + sits next to this module. + + Raises loudly when neither matches — a bootstrap that silently skips is how + a broken install masquerades as a working one. + """ + here = os.path.dirname(os.path.realpath(__file__)) + candidates = ( + os.path.realpath(os.path.join(here, "..", "skills")), + os.path.realpath(os.path.join(here, "skills")), + ) + for cand in candidates: + if os.path.isfile(os.path.join(cand, "using-superpowers", "SKILL.md")): + return cand + raise RuntimeError( + "superpowers plugin: cannot find the skills/ tree " + f"(looked at {candidates}). Reinstall with " + "`hermes plugins install obra/superpowers`." + ) def _strip_frontmatter(content: str) -> str: @@ -25,44 +37,20 @@ def _strip_frontmatter(content: str) -> str: return (match.group(1) if match else content).strip() -def _hermes_tool_mapping() -> str: - # Tool names confirmed empirically in Task 1. - return """\ -## Hermes tool mapping +def _build_bootstrap(skills_dir: str) -> str: + with open( + os.path.join(skills_dir, "using-superpowers", "SKILL.md"), + encoding="utf-8", + ) as f: + body = _strip_frontmatter(f.read()) -When skills request actions, use these Hermes equivalents: + tools_path = os.path.join( + skills_dir, "using-superpowers", "references", "hermes-tools.md" + ) + with open(tools_path, encoding="utf-8") as f: + tool_mapping = f.read().strip() -| Action | Hermes tool | -|--------|-------------| -| Read a file | `read_file` | -| Create a new file | `write_file` | -| Edit a file (targeted patch) | `patch` | -| Run a shell command | `terminal` | -| Search file contents | `search_files` | -| Find files by name | `terminal` with `find` | -| Fetch a URL / read a webpage | `web_extract(urls=[...])` | -| Search the web | `web_search(query=...)` | -| Dispatch a subagent | `delegate_task(goal=..., context=..., toolsets=[...], role="leaf")` | -| Task tracking | `todo` tool | -| Invoke a skill | `skill_view("skill-name")` — this is the native skill-loading mechanism on Hermes | -""" - - -def _get_bootstrap() -> Optional[str]: - global _bootstrap_cache - if _bootstrap_cache is not None: - return None if _bootstrap_cache is False else _bootstrap_cache - - skill_path = os.path.join(_SKILLS_DIR, "using-superpowers", "SKILL.md") - if not os.path.exists(skill_path): - _bootstrap_cache = False - return None - - with open(skill_path, encoding="utf-8") as f: - raw = f.read() - - body = _strip_frontmatter(raw) - _bootstrap_cache = ( + return ( f"\n" f"{BOOTSTRAP_MARKER}\n\n" f"You have superpowers.\n\n" @@ -71,31 +59,46 @@ def _get_bootstrap() -> Optional[str]: f"Do not try to load using-superpowers again.\n\n" f"{body}\n\n" f"## Loading Superpowers Skills on Hermes\n\n" - f"Superpowers skills are NOT in Hermes' built-in skill registry — " - f"`skill_view` will return 'not found' for them. " - f"When using-superpowers tells you to invoke a skill, use this two-step:\n\n" - f"1. Try `skill_view(\"skill-name\")` first (it works for Hermes' own skills).\n" - f"2. If that returns 'not found', immediately use `read_file` instead:\n" - f" `read_file(\"{_SKILLS_DIR}/skill-name/SKILL.md\")`\n\n" - f"Example — to load the brainstorming skill:\n" - f" `read_file(\"{_SKILLS_DIR}/brainstorming/SKILL.md\")`\n\n" - f"The superpowers skills directory is: `{_SKILLS_DIR}`\n\n" - f"{_hermes_tool_mapping()}\n" + f"Superpowers skills are registered with Hermes' native skill loader: " + f'invoke one with `skill_view("superpowers:skill-name")` ' + f'(for example `skill_view("superpowers:brainstorming")`). ' + f"If a namespaced lookup returns 'not found', read the skill file " + f"directly instead:\n" + f'`read_file("{skills_dir}/skill-name/SKILL.md")`\n\n' + f"The superpowers skills directory is: `{skills_dir}`\n\n" + f"{tool_mapping}\n" f"" ) - return _bootstrap_cache def register(ctx): - def on_session_start(**kwargs): - global _last_session_id - session_id = kwargs.get("session_id") - if session_id is not None and session_id == _last_session_id: - return - bootstrap = _get_bootstrap() - if bootstrap is None: - return - ctx.inject_message(bootstrap, role="user") - _last_session_id = session_id + skills_dir = _skills_dir() + bootstrap = _build_bootstrap(skills_dir) - ctx.register_hook("on_session_start", on_session_start) + # Register every stock skill with Hermes' native loader so skill_view can + # load them on demand. Standard markdown; no conversion (plugin guide). + # register_skill requires a pathlib.Path — a str raises AttributeError and + # hermes silently disables the whole plugin (verified 2026-07-23). + for name in sorted(os.listdir(skills_dir)): + skill_md = os.path.join(skills_dir, name, "SKILL.md") + if os.path.isfile(skill_md): + ctx.register_skill(name, Path(skill_md)) + + # pre_llm_call returning {"context": ...} is the documented injection path + # (on_session_start return values are ignored, and ctx.inject_message + # refuses from that hook — verified empirically 2026-07-23). The context is + # appended to the first turn's user message. + def pre_llm_call( + session_id=None, + user_message=None, + conversation_history=None, + is_first_turn=None, + model=None, + platform=None, + **kwargs, + ): + if is_first_turn: + return {"context": bootstrap} + return None + + ctx.register_hook("pre_llm_call", pre_llm_call) diff --git a/.hermes-plugin/plugin.yaml b/.hermes-plugin/plugin.yaml index d8aa14beb..9260499df 100644 --- a/.hermes-plugin/plugin.yaml +++ b/.hermes-plugin/plugin.yaml @@ -3,4 +3,4 @@ version: 6.0.3 description: Superpowers skills and workflow bootstrap for Hermes Agent author: obra provides_hooks: - - on_session_start + - pre_llm_call From b6613057ae5cb1ecb634f12e52cc47a260caf0e4 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 23 Jul 2026 16:05:54 -0700 Subject: [PATCH 065/198] test(hermes): realign suite with the pre_llm_call mechanism; slim docs to the README section The 20-test suite still exercised the dead on_session_start/inject_message mechanism (17 failures against the rewritten plugin). Rewritten for the real contract: pre_llm_call registration + first-turn-only context return, register_skill receiving pathlib.Path (the conftest mock now raises on str, mirroring hermes' AttributeError that silently disables a plugin), both install layouts resolving skills, loud failure when skills are missing, tool mapping sourced verbatim from hermes-tools.md, and a bootstrap-size guard against hermes' 10k-char context spill threshold. 19 tests, passing. Install docs collapse into the README section per maintainer direction: docs/README.hermes.md and .hermes-plugin/INSTALL.md are gone; the README carries the two-line install plus the compaction caveat. plugin.yaml version aligned to 6.1.1. --- .hermes-plugin/INSTALL.md | 30 ------ .hermes-plugin/plugin.yaml | 2 +- README.md | 6 +- docs/README.hermes.md | 29 ------ tests/hermes/conftest.py | 19 +++- tests/hermes/test_bootstrap.py | 95 ++++++++++------- tests/hermes/test_plugin.py | 183 ++++++++++++++++++++------------- 7 files changed, 185 insertions(+), 179 deletions(-) delete mode 100644 .hermes-plugin/INSTALL.md delete mode 100644 docs/README.hermes.md diff --git a/.hermes-plugin/INSTALL.md b/.hermes-plugin/INSTALL.md deleted file mode 100644 index b08ef5b1d..000000000 --- a/.hermes-plugin/INSTALL.md +++ /dev/null @@ -1,30 +0,0 @@ -# Hermes Agent — Superpowers Plugin - -## Install - -```bash -hermes plugins install obra/superpowers --enable -``` - -Restart any active Hermes sessions after installing. - -## Smoke check - -Start a new session and send: -> What are your superpowers? - -The model should describe brainstorming, TDD, debugging, and planning skills. -If it doesn't, the bootstrap isn't loading — reinstall and restart. - -## Acceptance test - -Send in a fresh session: -> Let's make a react todo list - -The `brainstorming` skill must trigger and run its flow before any code is written. - -## Uninstall - -```bash -hermes plugins remove superpowers -``` diff --git a/.hermes-plugin/plugin.yaml b/.hermes-plugin/plugin.yaml index 9260499df..c10f9f55c 100644 --- a/.hermes-plugin/plugin.yaml +++ b/.hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: superpowers -version: 6.0.3 +version: 6.1.1 description: Superpowers skills and workflow bootstrap for Hermes Agent author: obra provides_hooks: diff --git a/README.md b/README.md index 8a781e645..61dfc732d 100644 --- a/README.md +++ b/README.md @@ -207,9 +207,9 @@ Install Superpowers as a Hermes plugin from this repository: hermes plugins install obra/superpowers --enable ``` -Restart any active Hermes sessions after installing. - -Detailed docs: [docs/README.hermes.md](docs/README.hermes.md) +Restart any active Hermes sessions after installing. Note: Hermes has no +post-compaction hook, so a very long session that compacts over its first +turn loses the bootstrap — start a fresh session if skills stop triggering. ## The Basic Workflow diff --git a/docs/README.hermes.md b/docs/README.hermes.md deleted file mode 100644 index 0ad692c52..000000000 --- a/docs/README.hermes.md +++ /dev/null @@ -1,29 +0,0 @@ -# Hermes Agent - -Superpowers supports Hermes Agent via an in-process Python plugin (Shape B). - -## Install - -```bash -hermes plugins install obra/superpowers --enable -``` - -## What you get - -All Superpowers skills auto-trigger in Hermes sessions: -brainstorming before feature work, systematic-debugging on bugs, -test-driven-development for implementation, writing-plans before -touching code, and all other skills in `skills/`. - -## How it works - -The plugin registers an `on_session_start` hook with the Hermes plugin API. -At the start of each session, the hook injects the `using-superpowers` bootstrap -as a user-role message via `ctx.inject_message(role="user")`. A session-id guard -prevents double-injection if the hook fires more than once per session. - -Skills are loaded on demand during the session using `skill_view("skill-name")`. - -## Verifying - -See `.hermes-plugin/INSTALL.md` for the smoke check and acceptance test. diff --git a/tests/hermes/conftest.py b/tests/hermes/conftest.py index a4c851973..561cd8ca5 100644 --- a/tests/hermes/conftest.py +++ b/tests/hermes/conftest.py @@ -1,3 +1,5 @@ +from pathlib import Path + import pytest from unittest.mock import MagicMock @@ -6,14 +8,23 @@ from unittest.mock import MagicMock def mock_ctx(): ctx = MagicMock() ctx._hooks = {} - ctx._injected = [] + ctx._skills = {} def register_hook(event, fn): ctx._hooks[event] = fn - def inject_message(content, role="user"): - ctx._injected.append({"content": content, "role": role}) + def register_skill(name, path): + # Mimic hermes' real register_skill, which calls path.exists() and + # therefore breaks on a str (the bug that silently disabled the whole + # plugin, found 2026-07-23). Keeping that fidelity here means a + # regression to str paths fails these tests instead of failing + # silently inside hermes. + if not isinstance(path, Path): + raise AttributeError( + f"register_skill requires a pathlib.Path, got {type(path).__name__}" + ) + ctx._skills[name] = path ctx.register_hook.side_effect = register_hook - ctx.inject_message.side_effect = inject_message + ctx.register_skill.side_effect = register_skill return ctx diff --git a/tests/hermes/test_bootstrap.py b/tests/hermes/test_bootstrap.py index a8e8f282e..8b60153c6 100644 --- a/tests/hermes/test_bootstrap.py +++ b/tests/hermes/test_bootstrap.py @@ -1,6 +1,7 @@ +import importlib import os import sys -import importlib + import pytest sys.path.insert(0, os.path.abspath( @@ -9,6 +10,10 @@ sys.path.insert(0, os.path.abspath( BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes" +# Hermes spills injected context over 10,000 chars to a file, which breaks +# inline injection semantics. The bootstrap must stay under it with margin. +HERMES_CONTEXT_SPILL_LIMIT = 10_000 + def _load(): if "__init__" in sys.modules: @@ -16,6 +21,11 @@ def _load(): return importlib.import_module("__init__") +def _bootstrap(): + m = _load() + return m._build_bootstrap(m._skills_dir()) + + class TestStripFrontmatter: def test_strips_yaml_block(self): m = _load() @@ -33,49 +43,56 @@ class TestStripFrontmatter: assert m._strip_frontmatter(content) == "# Body" -class TestGetBootstrap: - def test_returns_none_when_skill_file_missing(self, tmp_path): +class TestSkillsDirResolution: + def test_repo_layout_resolves(self): + # The repo checkout IS the git-clone layout: .hermes-plugin/ and + # skills/ are siblings, so resolution must succeed from here. m = _load() - m._bootstrap_cache = None - m._SKILLS_DIR = str(tmp_path / "nonexistent") - assert m._get_bootstrap() is None + skills = m._skills_dir() + assert os.path.isfile( + os.path.join(skills, "using-superpowers", "SKILL.md") + ) - def test_caches_false_on_missing_file(self, tmp_path): - m = _load() - m._bootstrap_cache = None - m._SKILLS_DIR = str(tmp_path / "nonexistent") - m._get_bootstrap() - assert m._bootstrap_cache is False - def test_returns_string_with_real_skill(self): - m = _load() - m._bootstrap_cache = None - result = m._get_bootstrap() - assert result is not None - assert isinstance(result, str) +class TestBootstrapContent: + def test_marker_and_wrapper(self): + content = _bootstrap() + assert BOOTSTRAP_MARKER in content + assert content.startswith("") + assert content.rstrip().endswith("") - def test_same_object_returned_on_second_call(self): - m = _load() - m._bootstrap_cache = None - r1 = m._get_bootstrap() - r2 = m._get_bootstrap() - assert r1 is r2 + def test_contains_using_superpowers_body(self): + content = _bootstrap() + # A distinctive line from the skill body proves the real SKILL.md was + # embedded, not a stub. + assert "You have superpowers" in content + assert "## The Rule" in content - def test_contains_marker(self): - m = _load() - m._bootstrap_cache = None - result = m._get_bootstrap() - assert BOOTSTRAP_MARKER in result + def test_frontmatter_stripped(self): + content = _bootstrap() + assert "---\nname:" not in content - def test_contains_extremely_important_wrapper(self): + def test_tool_mapping_sourced_from_reference_file(self): m = _load() - m._bootstrap_cache = None - result = m._get_bootstrap() - assert result.startswith("") - assert result.rstrip().endswith("") + content = _bootstrap() + ref = os.path.join( + m._skills_dir(), "using-superpowers", "references", "hermes-tools.md" + ) + with open(ref, encoding="utf-8") as f: + ref_text = f.read().strip() + # The mapping is included verbatim from the reference file — the + # single source, not a drift-prone inline copy. + assert ref_text in content + assert "read_file" in content - def test_frontmatter_absent_from_output(self): - m = _load() - m._bootstrap_cache = None - result = m._get_bootstrap() - assert "---\nname:" not in result + def test_skill_view_guidance_present(self): + content = _bootstrap() + assert 'skill_view("superpowers:brainstorming")' in content + + def test_under_hermes_context_spill_limit(self): + content = _bootstrap() + assert len(content) < HERMES_CONTEXT_SPILL_LIMIT, ( + f"bootstrap is {len(content)} chars; hermes spills injected " + f"context over {HERMES_CONTEXT_SPILL_LIMIT} to a file, which " + "breaks inline injection" + ) diff --git a/tests/hermes/test_plugin.py b/tests/hermes/test_plugin.py index e9317a413..9c6c4f081 100644 --- a/tests/hermes/test_plugin.py +++ b/tests/hermes/test_plugin.py @@ -1,105 +1,142 @@ -import os -import sys import importlib +import importlib.util +import os +import shutil +import sys +from pathlib import Path + import pytest # Point at the plugin directory -_PLUGIN_DIR = os.path.join(os.path.dirname(__file__), "../../.hermes-plugin") -sys.path.insert(0, os.path.abspath(_PLUGIN_DIR)) +_PLUGIN_DIR = os.path.abspath( + os.path.join(os.path.dirname(__file__), "../../.hermes-plugin") +) +sys.path.insert(0, _PLUGIN_DIR) BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes" def _load_plugin(): - """Re-import plugin module fresh (clears module-level cache).""" + """Re-import plugin module fresh.""" if "__init__" in sys.modules: del sys.modules["__init__"] return importlib.import_module("__init__") +def _fire_pre_llm(ctx, **kwargs): + hook = ctx._hooks["pre_llm_call"] + defaults = { + "session_id": "s1", + "user_message": "hi", + "conversation_history": [], + "is_first_turn": False, + "model": "test-model", + "platform": "cli", + } + defaults.update(kwargs) + return hook(**defaults) + + class TestPluginRegistration: - def test_register_attaches_session_start_hook(self, mock_ctx): + def test_register_attaches_only_pre_llm_call_hook(self, mock_ctx): plugin = _load_plugin() plugin.register(mock_ctx) - mock_ctx.register_hook.assert_called_once() - event_name = mock_ctx.register_hook.call_args[0][0] - assert event_name == "on_session_start" + assert list(mock_ctx._hooks.keys()) == ["pre_llm_call"] + + def test_register_registers_every_stock_skill_as_path(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + # The conftest mock raises on non-Path (mirroring hermes' real + # register_skill), so reaching these asserts proves every + # registration passed a pathlib.Path. + assert "using-superpowers" in mock_ctx._skills + assert "brainstorming" in mock_ctx._skills + for name, path in mock_ctx._skills.items(): + assert isinstance(path, Path) + assert path.name == "SKILL.md" + assert path.parent.name == name + assert path.is_file() + + def test_registered_skills_match_skill_directories(self, mock_ctx): + plugin = _load_plugin() + plugin.register(mock_ctx) + skills_root = plugin._skills_dir() + expected = { + entry + for entry in os.listdir(skills_root) + if os.path.isfile(os.path.join(skills_root, entry, "SKILL.md")) + } + assert set(mock_ctx._skills.keys()) == expected class TestBootstrapInjection: - def test_first_session_start_injects_bootstrap(self, mock_ctx): + def test_first_turn_returns_bootstrap_context(self, mock_ctx): plugin = _load_plugin() plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - assert len(mock_ctx._injected) == 1 - assert BOOTSTRAP_MARKER in mock_ctx._injected[0]["content"] + result = _fire_pre_llm(mock_ctx, is_first_turn=True) + assert isinstance(result, dict) + content = result["context"] + assert BOOTSTRAP_MARKER in content + assert content.startswith("") + assert content.rstrip().endswith("") - def test_injection_uses_user_role(self, mock_ctx): + def test_later_turns_return_none(self, mock_ctx): plugin = _load_plugin() plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - assert mock_ctx._injected[0]["role"] == "user" + assert _fire_pre_llm(mock_ctx, is_first_turn=False) is None + assert _fire_pre_llm(mock_ctx, is_first_turn=None) is None - def test_dedup_skips_on_same_session_id(self, mock_ctx): + def test_hook_tolerates_future_kwargs(self, mock_ctx): plugin = _load_plugin() plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - handler(session_id="sess-1", model="test-model", platform="test") - assert len(mock_ctx._injected) == 1 - - def test_reinjects_on_new_session_id(self, mock_ctx): - plugin = _load_plugin() - plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - handler(session_id="sess-2", model="test-model", platform="test") - assert len(mock_ctx._injected) == 2 - - def test_missing_skill_file_skips_silently(self, mock_ctx, tmp_path): - plugin = _load_plugin() - plugin._bootstrap_cache = None - plugin._SKILLS_DIR = str(tmp_path / "nonexistent") - plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - assert len(mock_ctx._injected) == 0 - - def test_cache_populated_after_first_call(self, mock_ctx): - plugin = _load_plugin() - plugin._bootstrap_cache = None - plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - assert plugin._bootstrap_cache is not None - assert plugin._bootstrap_cache is not False + result = _fire_pre_llm( + mock_ctx, is_first_turn=True, telemetry_schema_version=3 + ) + assert BOOTSTRAP_MARKER in result["context"] -class TestBootstrapContent: - def test_contains_extremely_important_tags(self, mock_ctx): - plugin = _load_plugin() - plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - content = mock_ctx._injected[0]["content"] - assert "" in content - assert "" in content +class TestLayoutResolution: + def _stage(self, tmp_path, layout): + """Copy the plugin module + a minimal skills tree in the given layout.""" + src_skills = Path(_PLUGIN_DIR).parent / "skills" + if layout == "clone": + plugdir = tmp_path / "superpowers" / ".hermes-plugin" + else: # flat: module at the plugin dir root, skills nested inside it + plugdir = tmp_path / "superpowers" + skills = tmp_path / "superpowers" / "skills" + plugdir.mkdir(parents=True, exist_ok=True) + shutil.copy(Path(_PLUGIN_DIR) / "__init__.py", plugdir / "__init__.py") + for skill in ("using-superpowers", "brainstorming"): + shutil.copytree(src_skills / skill, skills / skill) + return plugdir - def test_frontmatter_stripped(self, mock_ctx): - plugin = _load_plugin() - plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - content = mock_ctx._injected[0]["content"] - assert "---\nname:" not in content + def _load_from(self, plugdir): + spec = importlib.util.spec_from_file_location( + f"hermes_plugin_test_{plugdir.parent.name}_{plugdir.name}", + plugdir / "__init__.py", + ) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod - def test_tool_mapping_present(self, mock_ctx): - plugin = _load_plugin() - plugin.register(mock_ctx) - handler = mock_ctx._hooks["on_session_start"] - handler(session_id="sess-1", model="test-model", platform="test") - content = mock_ctx._injected[0]["content"] - assert "Hermes tool mapping" in content - assert "read_file" in content + def test_clone_layout_resolves_sibling_skills(self, tmp_path, mock_ctx): + # git-clone install: .hermes-plugin/ and skills/ are siblings. + plugdir = self._stage(tmp_path, "clone") + mod = self._load_from(plugdir) + mod.register(mock_ctx) + assert "using-superpowers" in mock_ctx._skills + + def test_flat_layout_resolves_nested_skills(self, tmp_path, mock_ctx): + # flattened install: module at the plugin dir root, skills/ inside it. + plugdir = self._stage(tmp_path, "flat") + mod = self._load_from(plugdir) + mod.register(mock_ctx) + assert "using-superpowers" in mock_ctx._skills + + def test_missing_skills_raises_loudly(self, tmp_path, mock_ctx): + plugdir = tmp_path / "superpowers" + plugdir.mkdir(parents=True) + shutil.copy(Path(_PLUGIN_DIR) / "__init__.py", plugdir / "__init__.py") + mod = self._load_from(plugdir) + with pytest.raises(RuntimeError, match="cannot find the skills"): + mod.register(mock_ctx) From d262bc400c6d29f7b762871e88eb495c46fc75c2 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 23 Jul 2026 16:16:32 -0700 Subject: [PATCH 066/198] Release v6.2.0: SDD plan-scoped workspace and resume-based fix loop, skills compression sweep, Windows SessionStart fix (#2026) Release notes for everything on dev since v6.1.1, plus the version bump to 6.2.0 across all seven declared manifest files (bump-version.sh, audit clean). Tagging and marketplace publication happen after the dev -> main merge. --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- .kimi-plugin/plugin.json | 2 +- RELEASE-NOTES.md | 33 +++++++++++++++++++++++++++++++++ gemini-extension.json | 2 +- package.json | 2 +- 8 files changed, 40 insertions(+), 7 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index acb6ae664..e058f5e44 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ { "name": "superpowers", "description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.1.1", + "version": "6.2.0", "source": "./", "author": { "name": "Jesse Vincent", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 2fe026fdc..5ec90b5e3 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "superpowers", "description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.1.1", + "version": "6.2.0", "author": { "name": "Jesse Vincent", "email": "jesse@fsck.com" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index a6b31431f..c777f316f 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.1.1", + "version": "6.2.0", "description": "An agentic skills framework & software development methodology that works: planning, TDD, debugging, and collaboration workflows.", "author": { "name": "Jesse Vincent", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 18d788b2c..0902be0e6 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -2,7 +2,7 @@ "name": "superpowers", "displayName": "Superpowers", "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.1.1", + "version": "6.2.0", "author": { "name": "Jesse Vincent", "email": "jesse@fsck.com" diff --git a/.kimi-plugin/plugin.json b/.kimi-plugin/plugin.json index e5d90d0c9..55933e34a 100644 --- a/.kimi-plugin/plugin.json +++ b/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.1.1", + "version": "6.2.0", "description": "An agentic skills framework and software development methodology.", "author": { "name": "Jesse Vincent", diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index 823948e74..46c51e38d 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -1,5 +1,38 @@ # Superpowers Release Notes +## v6.2.0 (2026-07-23) + +### Subagent-Driven Development + +Two structural changes to how SDD tracks progress and closes out review findings, both developed against live eval campaigns. + +- **The workspace is now plan-scoped.** `.superpowers/sdd/` had no plan identity and no end-of-life: a follow-up plan in the same working tree could read the previous plan's ledger as its own progress (observed in the wild, with multiple contamination rounds and ad-hoc workarounds). `sdd-workspace` now requires the plan file and resolves a per-plan directory, `.superpowers/sdd//`; `task-brief` and `review-package` write into their plan's directory (`review-package` gains the plan file as its first argument); the ledger names its plan on its first line; and the workspace is deleted once the final review is clean — git history is the durable record. Baseline evals showed controllers already refused foreign ledgers, but at a cost of 6–13 tool calls of cross-plan git forensics per resume; plan-scoping makes the answer structural instead. (25/25 baseline and GREEN eval runs documented in `docs/specs/` and `docs/plans/`.) +- **The review-fix loop resumes the implementer.** The lifecycle restructure gives fix rounds resume-the-implementer semantics instead of fresh dispatches, adds a scoped re-review prompt (`re-review-prompt.md`) so the re-reviewer checks the fixes rather than re-reading the whole task, and installs a five-round circuit breaker with controller adjudication when it trips. SKILL.md reorganizes by lifecycle, and its Red Flags convert to the house rationalization-table form. + +### Skills + +A branch-wide compression campaign: recap sections, social proof, and benefits-selling prose aimed at a reader who has already invoked the skill are gone, with every load-bearing argument folded into a rationalization-table row or moved to its point of use. Each cut was micro-tested with subagent probes, and the one cut that measurably degraded behavior was reworked rather than shipped. + +- **`testing-anti-patterns.md` is now `writing-good-tests.md`.** The TDD reference doc is rebuilt as a positive catalog — six rules that lead with the GOOD example — and absorbs a falsifiability discipline: name the production change that would fail the test, derive expectations independently of the code under test, and a closing mutation check. It closes two holes by name: the string-presence trap (grep-style tests on scripts, skills, and prompts counterfeit falsifiability — the observable is behavior, never text) and the change-detector trap (a constant assertion can fail and still protect nothing), each with a hard stop in the gate function. Trivial code and human prose earn no test; the trigger broadens from "adding mocks" to any test writing. +- **TDD's "Why Order Matters" rebuttals survive as rationalization rows.** Deleting the section outright measurably degraded test-first behavior under "just write it, tests after" pressure (control 8/10 → treatment 5/10, corroborated on Claude and Codex), so each prose rebuttal now lives in its Common Rationalizations row — the section is gone but the arguments fire where an agent hits them mid-rationalization. +- **`finishing-a-development-branch` no longer offers to discard your work.** The completion menu dates from when throwing away branches was routine; "Discard this work" next to "Merge" advertised destroying finished, passing work. Discard survives as an explicit-request-only path with the same typed-confirmation ritual. The same pass made PR creation forge-agnostic (your forge's CLI or the URL printed on push, not a blessed list of tools) and fixed a real bug: the worktree path was recomputed after cleanup had already changed directory, so provenance checks never matched and cleanup silently no-oped. +- **Recap and persuasion prose removed across the library.** `brainstorming`, `systematic-debugging`, `dispatching-parallel-agents`, `verification-before-completion`, `executing-plans`, `subagent-driven-development`, `requesting-code-review`, `receiving-code-review`, `using-git-worktrees`, `writing-plans`, and `writing-skills` all drop their Bottom Line / Key Principles / Real-World Impact / Advantages sections; `using-git-worktrees` and `finishing-a-development-branch` convert their guard sections to the house Excuse/Reality rationalization table. + +### Windows + +- **The SessionStart hook now dispatches via Git Bash.** The hook's command string starts with a quoted path, which broke both shells Claude Code might hand it to: PowerShell parsed the quoted string as an expression and died with a parser error (#1751), and cmd.exe's quote-stripping rule truncated the command when the profile path contained a metacharacter like `(` (#1918) — either way the bootstrap silently never loaded. The hook now declares `shell: "bash"`, which Claude Code ≥ 2.1.81 resolves to Git for Windows directly, and which surfaces an actionable install prompt when Git Bash is missing. Older Claude Code versions ignore the unknown key and behave as before. Verified end-to-end on Linux, Windows 11 with Git Bash under a hostile path, and Windows 11 without Git Bash. + +### Harness Support + +- **Gemini CLI support is restored.** The v6.1.0 removal (on the news that Google had EOLed the Gemini CLI) was premature; the install docs and the `gemini-tools.md` tool-mapping reference are back while permanent removal gets a proper evaluation. (#1959) + +### Fixes + +- **`find-polluter.sh` actually finds test files now.** `find .` emits `./`-prefixed paths, so the documented `-path "src/**/*.test.ts"` pattern matched nothing — and `wc -l` on empty input then reported "Found 1". Fixed the prefix mismatch (#2008, #2011), plus two follow-ups: a caller-supplied `./`-prefixed pattern no longer double-prefixes into a never-matching form, and `**/` is also matched collapsed so tests directly under the base directory (`src/top.test.ts` vs `src/**/*.test.ts`) aren't silently skipped. The script gains a deterministic test suite. +- **The Codex package script works beyond macOS.** Deterministic-metadata tar flags were bsdtar-only spellings, staged file modes depended on two umasks canceling out, and the test's timestamp assertion parsed bsdtar's column layout in a US timezone. GNU tar now gets equivalent flags producing byte-identical headers, modes are pinned canonical, and the test asserts mtime via `tarfile`. +- **SDD's skill test no longer flakes.** The file's worst case exceeded the runner's per-file ceiling (raised to 900s), and the assert helpers matched free-form model prose case-sensitively; matching is now case-insensitive and `assert_order` dumps output on failure so the next flake is diagnosable. +- **Docs and test cleanup after the v6.1.0 reference pruning.** Dead links to the deleted `claude-code-tools.md`/`copilot-tools.md` are replaced with the current architecture (#1969), a dangling `#subagent-support` anchor in the Antigravity reference is dropped (#2010), and the Antigravity/Pi mapping tests assert only the surviving harness-specific mappings — scoped to the table so they fail again if it's deleted. + ## v6.1.1 (2026-07-02) ### Codex diff --git a/gemini-extension.json b/gemini-extension.json index dc5e1f645..01378c982 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "superpowers", "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.1.1", + "version": "6.2.0", "contextFileName": "GEMINI.md" } diff --git a/package.json b/package.json index ad25028da..c24b3721d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.1.1", + "version": "6.2.0", "description": "Superpowers skills and runtime bootstrap for coding agents", "type": "module", "main": ".opencode/plugins/superpowers.js", From bb2a34b2a0ac6eac16a3337897a3d66052d50e3e Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 27 Jul 2026 11:43:14 -0700 Subject: [PATCH 067/198] docs: remove the "We're Hiring" section from the README The community engineer role has a candidate on trial, so the posting no longer needs to be at the top of the README. --- README.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/README.md b/README.md index bb398c6b6..2757b2efb 100644 --- a/README.md +++ b/README.md @@ -3,12 +3,6 @@ Superpowers is a complete software development methodology for your coding agents, built on top of a set of composable skills and some initial instructions that make sure your agent uses them. -## We're Hiring! - -We're hiring someone to help out full time with Superpowers community and code work. -You can read about the job at https://primeradiant.com/jobs/superpowers-community-engineer/ -If this sounds like someone you know, definitely send them our way. - ## Quickstart Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). From 6211388f4bfecef2017559a94f4659bd08997816 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 10:38:05 -0700 Subject: [PATCH 068/198] =?UTF-8?q?feat(brainstorming):=20three-path=20rou?= =?UTF-8?q?ter=20=E2=80=94=20ceremony=20scales,=20approval=20never=20does?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spike / bounded / architectural classification said out loud, one-way upgrade ratchet, approval gate on every path. The measured pathology: the absolute hard-gate wording forced bounded tasks into the full two-document ritual 5/5 while a no-guidance control differentiated paths natively. --- skills/brainstorming/SKILL.md | 106 +++++++++++++++++++++++++++++++--- 1 file changed, 99 insertions(+), 7 deletions(-) diff --git a/skills/brainstorming/SKILL.md b/skills/brainstorming/SKILL.md index 789c3a199..fdeabfe36 100644 --- a/skills/brainstorming/SKILL.md +++ b/skills/brainstorming/SKILL.md @@ -7,20 +7,84 @@ description: "You MUST use this before any creative work - creating features, bu 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. +Start by classifying how much process the request needs, then work +through your path: understand the context, refine the idea, present a +design, and get your human partner's approval. -Do NOT invoke any implementation skill, write any code, scaffold any project, or take any implementation action until you have presented a design and the user has approved it. This applies to EVERY project regardless of perceived simplicity. +Do NOT invoke any implementation skill, write any code, scaffold any +project, or take any implementation action until you have told your +human partner what you intend and they have approved it. This applies +to EVERY task on EVERY path below — the ceremony scales with the task; +the approval gate never does. -## Anti-Pattern: "This Is Too Simple To Need A Design" +## Three Paths -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. +Before your first question, classify the request and say the +classification out loud — "this looks bounded, so I'll present a short +design here rather than write a spec" — so your human partner can +override it: + +- **Spike** — a feasibility question ("can we...", "is it possible...", + "quick and dirty is fine") whose output is an answer, not code you + keep. Present the question and what you'll try in 2-3 sentences, get + a nod, then find out as cheaply as correctness allows. No design + doc, no spec file. Report findings as a recommendation; anything you + built stays labeled throwaway. +- **Bounded** — a well-scoped change to an existing, understood flow: a + new flag, a small endpoint, a one-file fix. Ask the clarifying + questions that matter, present a short design IN CHAT (a few + sentences to a few short paragraphs), and get approval. No spec + file, no implementation plan document. +- **Architectural** — new projects, new subsystems, changes that + restructure how components fit together or alter interfaces others + depend on. Follow the full process: questions, approaches, sectioned + design, written spec, then the writing-plans skill. + +When in doubt between two paths, take the heavier one. The ratchet is +one-way: hidden complexity discovered mid-task upgrades the path — +stop, say so, and step up. Nothing downgrades mid-task. + +## Anti-Pattern: "Too Simple To Need Approval" + +Every path ends with your human partner approving your intent before +implementation. A todo list, a single-function utility, a config +change — the design may be two sentences in chat, but you MUST present +it and get approval. "Simple" tasks are where unexamined assumptions +cause the most wasted work. What scales with simplicity is the +artifact, never the approval. + +## Red Flags + +| Thought | Reality | +|---------|---------| +| "This is too simple to need a design" | Simple means a short design, not no design. Two sentences in chat, then approval. | +| "I'll call it bounded and skip the spec" | Reaching for a label to skip work IS the doubt — take the heavier path. | +| "The spike works, so I'll keep the code" | A spike's output is an answer. Keeping the code is a new request — classify it. | +| "It grew, but I'm almost done — no need to re-classify" | Hidden complexity upgrades the path mid-task. Stop and say so. | +| "They approved the spike, so the follow-up change is approved too" | Each task gets its own classification and its own approval. | ## Checklist -You MUST create a task for each of these items and complete them in order: +Classify first, announce the path, then create a task for each item on +your path and complete them in order. +**Spike:** +1. **Explore project context** — enough to frame the probe +2. **Present question + probe plan** — 2-3 sentences +3. **Get approval** — a nod is enough +4. **Investigate** — as cheaply as correctness allows +5. **Report findings** — a recommendation; label anything built as throwaway + +**Bounded:** +1. **Explore project context** — check files, docs, recent commits +2. **Ask clarifying questions** — one at a time, the ones that matter +3. **Present short design in chat** — approach, files touched, testing +4. **Get approval** — explicit, before any implementation +5. **Implement** — proceed with the normal development workflow (TDD applies); no plan document + +**Architectural:** 1. **Explore project context** — check files, docs, recent commits 2. **Offer the visual companion just-in-time** — NOT upfront. The first time a question would genuinely be clearer shown than described, offer it then (its own message); on approval its browser tab opens for you. If no visual question ever arises, never offer it. See the Visual Companion section below. 3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria @@ -35,6 +99,13 @@ You MUST create a task for each of these items and complete them in order: ```dot digraph brainstorming { + "Classify: spike / bounded / architectural" [shape=diamond]; + "Present question + probe (2-3 sentences)" [shape=box]; + "Ask clarifying questions (bounded)" [shape=box]; + "Present short design in chat" [shape=box]; + "Human approves?" [shape=diamond]; + "Investigate; report recommendation" [shape=doublecircle]; + "Implement via normal workflow (no plan doc)" [shape=doublecircle]; "Explore project context" [shape=box]; "Ask clarifying questions" [shape=box]; "Propose 2-3 approaches" [shape=box]; @@ -44,7 +115,17 @@ digraph brainstorming { "Spec self-review\n(fix inline)" [shape=box]; "User reviews spec?" [shape=diamond]; "Invoke writing-plans skill" [shape=doublecircle]; + "Hidden complexity? Upgrade path" [shape=box]; + "Classify: spike / bounded / architectural" -> "Present question + probe (2-3 sentences)" [label="spike"]; + "Classify: spike / bounded / architectural" -> "Ask clarifying questions (bounded)" [label="bounded"]; + "Classify: spike / bounded / architectural" -> "Explore project context" [label="architectural"]; + "Present question + probe (2-3 sentences)" -> "Human approves?"; + "Ask clarifying questions (bounded)" -> "Present short design in chat"; + "Present short design in chat" -> "Human approves?"; + "Human approves?" -> "Investigate; report recommendation" [label="spike: yes"]; + "Human approves?" -> "Implement via normal workflow (no plan doc)" [label="bounded: yes"]; + "Hidden complexity? Upgrade path" -> "Classify: spike / bounded / architectural"; "Explore project context" -> "Ask clarifying questions"; "Ask clarifying questions" -> "Propose 2-3 approaches"; "Propose 2-3 approaches" -> "Present design sections"; @@ -58,10 +139,21 @@ digraph brainstorming { } ``` -**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. +**Terminal states are path-bound.** Architectural: the ONLY skill you +invoke after brainstorming is writing-plans — never frontend-design, +mcp-builder, or any other implementation skill. Bounded: after +approval, implementation proceeds directly through the normal +development workflow; no plan document. Spike: the terminal state is a +reported recommendation. ## The Process +The subsections below serve the bounded and architectural paths (a +spike stops at "present the probe, get a nod"). Sections from +**Exploring approaches** onward are architectural-path depth — for +bounded work, context plus a few questions plus a short in-chat design +is the whole process. + **Understanding the idea:** - Check out the current project state first (files, docs, recent commits) @@ -100,7 +192,7 @@ digraph brainstorming { - 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 +## After the Design (architectural path) **Documentation:** From 2e7d681591dbae4ed58e4e400a7f4729a21a04c5 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 10:30:02 -0700 Subject: [PATCH 069/198] fix(sdd): implementers never dispatch subagents Depth-2 worker-spawned reviewers were 9/9 same-task duplicate reviews across four corpora in the codex-efficiency eval campaign. --- skills/subagent-driven-development/SKILL.md | 7 +++++++ .../implementer-prompt.md | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index 6c0b8349d..96229e0a1 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -223,6 +223,12 @@ and fix-round diffs need it. later dispatches — a real session's dispatch hit 42k chars of which 99% was pasted history. A fresh subagent needs its task, the interfaces it touches, and the global constraints. Nothing else. +- The dispatch carries the no-subagents contract (it is in the + implementer template): the implementer never dispatches subagents — + not helpers, and never a reviewer. Review arrives from you, after the + report. In real sessions, every reviewer a worker spawned duplicated + the task review the controller dispatched anyway — a full extra + review seat per task. - If an earlier task parked a finding in the area this task touches, carry a pointer to that ledger entry in the dispatch. - Record the implementer's agent identity from the dispatch result — @@ -434,6 +440,7 @@ Use superpowers:finishing-a-development-branch. | "The fix was small, skip the re-review" | Unreviewed fixes are how regressions land. Every round ends with a scoped re-review. | | "Reviews slow the loop down" | The loop without reviews is just unverified churn. Reviews are the loop's brakes and steering. | | "Ledger bookkeeping is overhead" | The ledger is what survives compaction. Controllers without one have re-dispatched entire completed task sequences. | +| "The implementer spawned its own reviewer — free extra assurance" | It's a duplicate seat reviewing the same diff; the task review is the gate. A worker-spawned reviewer is a defect to flag, not rigor. | ## Example Workflow diff --git a/skills/subagent-driven-development/implementer-prompt.md b/skills/subagent-driven-development/implementer-prompt.md index fbe441e20..5c8ecd61f 100644 --- a/skills/subagent-driven-development/implementer-prompt.md +++ b/skills/subagent-driven-development/implementer-prompt.md @@ -47,6 +47,18 @@ Subagent (general-purpose): While iterating, run the focused test for what you're changing; run the full suite once before committing, not after every edit. + ## You Do Not Dispatch Subagents + + Do all of this task's work yourself. Never spawn a subagent to + implement part of the task, and above all never spawn a reviewer to + check your work. Self-review (below) means reading your own diff. + Review is the controller's job: after you report, it dispatches a + fresh reviewer against your diff. A reviewer you spawn duplicates + that review at full cost, and its approval counts for nothing in + the process. If you catch yourself thinking "an independent review + would strengthen my report" — that review is already scheduled. + Report instead. + ## Code Organization You reason best about code you can hold in context at once, and your edits are more From b68eaf96bb5f54b36948857c16d9beacbe2a7109 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 15:58:35 -0700 Subject: [PATCH 070/198] fix(brainstorming): bounded-path approval is a hard stop Live ceremony battery: bounded reps produced zero doc ritual (the measured win) but 2/3 implemented before any approval turn; the bounded path now states the stop explicitly. --- skills/brainstorming/SKILL.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/skills/brainstorming/SKILL.md b/skills/brainstorming/SKILL.md index fdeabfe36..532948c5e 100644 --- a/skills/brainstorming/SKILL.md +++ b/skills/brainstorming/SKILL.md @@ -35,8 +35,10 @@ override it: - **Bounded** — a well-scoped change to an existing, understood flow: a new flag, a small endpoint, a one-file fix. Ask the clarifying questions that matter, present a short design IN CHAT (a few - sentences to a few short paragraphs), and get approval. No spec - file, no implementation plan document. + sentences to a few short paragraphs), and STOP. Implementation + starts only after your human partner says yes to that design — a + bounded task's approval is as hard a gate as an architectural + one. No spec file, no implementation plan document. - **Architectural** — new projects, new subsystems, changes that restructure how components fit together or alter interfaces others depend on. Follow the full process: questions, approaches, sectioned @@ -61,6 +63,7 @@ artifact, never the approval. |---------|---------| | "This is too simple to need a design" | Simple means a short design, not no design. Two sentences in chat, then approval. | | "I'll call it bounded and skip the spec" | Reaching for a label to skip work IS the doubt — take the heavier path. | +| "It's bounded and the design is obvious — I'll start while they read it" | The gate is the approval, not the design's length. Present, then stop until you hear yes. | | "The spike works, so I'll keep the code" | A spike's output is an answer. Keeping the code is a new request — classify it. | | "It grew, but I'm almost done — no need to re-classify" | Hidden complexity upgrades the path mid-task. Stop and say so. | | "They approved the spike, so the follow-up change is approved too" | Each task gets its own classification and its own approval. | @@ -81,7 +84,7 @@ your path and complete them in order. 1. **Explore project context** — check files, docs, recent commits 2. **Ask clarifying questions** — one at a time, the ones that matter 3. **Present short design in chat** — approach, files touched, testing -4. **Get approval** — explicit, before any implementation +4. **Get approval** — STOP and wait for an explicit yes; presenting the design and starting in the same breath is skipping the gate 5. **Implement** — proceed with the normal development workflow (TDD applies); no plan document **Architectural:** From 75756d2900fc17e338f243886ade5998f5a4d78b Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 10:32:01 -0700 Subject: [PATCH 071/198] fix(codex): correct multi-agent guidance against Codex source Five claims contradicted by the Codex CLI source (V2 has no close_agent; followup_task always reaches a child; role files attach via agent_type; full-history forks accept model/effort; V2 spawn allowlist). Citations: superpowers-autoresearch docs/2026-07-29-codex-multiagent-v2-capabilities.md. --- .../references/codex-tools.md | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/skills/using-superpowers/references/codex-tools.md b/skills/using-superpowers/references/codex-tools.md index b14b58582..415638f64 100644 --- a/skills/using-superpowers/references/codex-tools.md +++ b/skills/using-superpowers/references/codex-tools.md @@ -7,7 +7,34 @@ Add to your Codex config (`~/.codex/config.toml`): multi_agent = true ``` -This enables `spawn_agent`, `wait_agent`, and `close_agent` for skills like `dispatching-parallel-agents` and `subagent-driven-development`. When using subagent-driven-development, close reviewer subagents when their review returns. Keep each implementer subagent open until its task's review passes — the fix loop resumes the implementer — then close it. If your harness cannot send another message to a spawned agent, dispatch each fix round as a fresh implementer carrying the brief, the report file, and the findings. +This enables the multi-agent tools that skills like +`dispatching-parallel-agents` and `subagent-driven-development` use. +Which tools you get depends on the multi-agent version your model +preset selects (current presets run V2; older ones run V1). Trust your +actual tool list over any table — including this one — when they +disagree. + +- **Spawning:** give children a clean context with + `spawn_agent {fork_turns: "none"}`; the default `"all"` copies your + entire transcript into the child. On Codex 0.145+, role files under + `~/.codex/agents/` attach to isolated forks via `agent_type`. + Full-history forks accept `model` and `reasoning_effort` overrides + (only `agent_type` is refused there) — isolated forks are the SDD + default for context hygiene, not because overrides require them. +- **Fix rounds:** resume the implementer with `followup_task` — it + delivers your message, triggers a turn, and transparently reloads a + child the harness evicted. Never dispatch a fresh implementer on the + theory that a spawned agent cannot be messaged again; on V2 it + always can. +- **Lifecycle:** V2 has no `close_agent`. Finished children are + evicted automatically when slots are needed; leaving them unclosed + costs nothing. Only V1 sessions have `close_agent` — there, close + reviewers when their review returns, and close each implementer + after its task's review passes. +- **Model names:** never copy a model name from a skill, table, or old + session into `spawn_agent` without checking it against your current + spawn allowlist — V2 accepts only V2-capable presets and hard-errors + on the rest. ## Environment Detection From 7c560e048b85e5bfa4d59a7f71d0bd012d7b8343 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 12:48:28 -0700 Subject: [PATCH 072/198] fix(sdd): reviewers never dispatch subagents either The first fix-cycle battery moved the depth-2 leak from implementers (9/9 baseline -> 0/6) to a final reviewer that spawned two sub-reviewers; the contract now reaches every dispatched role. --- skills/requesting-code-review/code-reviewer.md | 9 +++++++++ skills/subagent-driven-development/re-review-prompt.md | 9 +++++++++ .../subagent-driven-development/task-reviewer-prompt.md | 9 +++++++++ 3 files changed, 27 insertions(+) diff --git a/skills/requesting-code-review/code-reviewer.md b/skills/requesting-code-review/code-reviewer.md index db84ae2a0..b898cb982 100644 --- a/skills/requesting-code-review/code-reviewer.md +++ b/skills/requesting-code-review/code-reviewer.md @@ -34,6 +34,15 @@ Subagent (general-purpose): Your review is read-only on this checkout. Do not mutate the working tree, the index, HEAD, or branch state in any way. Use tools like `git show`, `git diff`, and `git log` to inspect history. If you need a working copy of a different revision, check it out into a separate temporary directory (e.g. `git worktree add /tmp/review-[SHA] [SHA]`) — never move HEAD on this checkout. + ## You Do Not Dispatch Subagents + + Do all of this review yourself. Never spawn a subagent to review part + of the diff, and never spawn another reviewer for a second opinion. + This process already provides every review seat the work gets; a + reviewer you spawn duplicates one of them at full cost, and its + verdict counts for nothing. If the diff feels too large for one + pass, review it in passes yourself and say so in your report. + ## What to Check **Plan alignment:** diff --git a/skills/subagent-driven-development/re-review-prompt.md b/skills/subagent-driven-development/re-review-prompt.md index 18b0fb8ad..ad74b10b3 100644 --- a/skills/subagent-driven-development/re-review-prompt.md +++ b/skills/subagent-driven-development/re-review-prompt.md @@ -43,6 +43,15 @@ Subagent (general-purpose): Your review is read-only on this checkout. Do not mutate the working tree, the index, HEAD, or branch state in any way. + ## You Do Not Dispatch Subagents + + Do all of this review yourself. Never spawn a subagent to review part + of the diff, and never spawn another reviewer for a second opinion. + This process already provides every review seat the work gets; a + reviewer you spawn duplicates one of them at full cost, and its + verdict counts for nothing. If the diff feels too large for one + pass, review it in passes yourself and say so in your report. + ## Scope Your scope is the findings list and the fix diff. Verdict every finding. diff --git a/skills/subagent-driven-development/task-reviewer-prompt.md b/skills/subagent-driven-development/task-reviewer-prompt.md index fefaea8a7..6ca4c1ca5 100644 --- a/skills/subagent-driven-development/task-reviewer-prompt.md +++ b/skills/subagent-driven-development/task-reviewer-prompt.md @@ -52,6 +52,15 @@ Subagent (general-purpose): Your review is read-only on this checkout. Do not mutate the working tree, the index, HEAD, or branch state in any way. + ## You Do Not Dispatch Subagents + + Do all of this review yourself. Never spawn a subagent to review part + of the diff, and never spawn another reviewer for a second opinion. + This process already provides every review seat the work gets; a + reviewer you spawn duplicates one of them at full cost, and its + verdict counts for nothing. If the diff feels too large for one + pass, review it in passes yourself and say so in your report. + ## Do Not Trust the Report Treat the implementer's report as unverified claims about the code. It From 4dc71b10b325637e8eba673184d4f57eb70ac865 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Fri, 31 Jul 2026 09:00:22 -0700 Subject: [PATCH 073/198] fix(brainstorming): bounded means existing code in this repo, not a familiar app genre MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Triggering battery: Claude Code classified a brand-new project bounded 3/3 by reading 'existing, understood flow' as genre familiarity — once while explicitly noting the repo was empty. Gemini routed the same prompt architectural 3/3. --- skills/brainstorming/SKILL.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/skills/brainstorming/SKILL.md b/skills/brainstorming/SKILL.md index 532948c5e..b56a3b5ed 100644 --- a/skills/brainstorming/SKILL.md +++ b/skills/brainstorming/SKILL.md @@ -32,8 +32,11 @@ override it: a nod, then find out as cheaply as correctness allows. No design doc, no spec file. Report findings as a recommendation; anything you built stays labeled throwaway. -- **Bounded** — a well-scoped change to an existing, understood flow: a - new flag, a small endpoint, a one-file fix. Ask the clarifying +- **Bounded** — a well-scoped change to code that already exists in + this repo: a new flag, a small endpoint, a one-file fix. + Understanding the kind of app is not enough — bounded means the flow + you are changing is already here to read. If there is no existing + flow to change, the task is not bounded. Ask the clarifying questions that matter, present a short design IN CHAT (a few sentences to a few short paragraphs), and STOP. Implementation starts only after your human partner says yes to that design — a @@ -64,6 +67,7 @@ artifact, never the approval. | "This is too simple to need a design" | Simple means a short design, not no design. Two sentences in chat, then approval. | | "I'll call it bounded and skip the spec" | Reaching for a label to skip work IS the doubt — take the heavier path. | | "It's bounded and the design is obvious — I'll start while they read it" | The gate is the approval, not the design's length. Present, then stop until you hear yes. | +| "I understand this kind of app, so it's bounded" | Bounded measures the repo, not your familiarity. A new project has no existing flow — it is architectural. | | "The spike works, so I'll keep the code" | A spike's output is an answer. Keeping the code is a new request — classify it. | | "It grew, but I'm almost done — no need to re-classify" | Hidden complexity upgrades the path mid-task. Stop and say so. | | "They approved the spike, so the follow-up change is approved too" | Each task gets its own classification and its own approval. | From 9b8b14fe12b2a1751ce7c58ba6f8d49bf38e3d1d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 10:33:59 -0700 Subject: [PATCH 074/198] fix(codex): event-driven waiting instead of short polls 60-78% of wait_agent calls timed out across every measured corpus; waits are event subscriptions, so one long wait replaces dozens of polls at identical wake latency. --- .../references/codex-tools.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/skills/using-superpowers/references/codex-tools.md b/skills/using-superpowers/references/codex-tools.md index 415638f64..cf2b70ee5 100644 --- a/skills/using-superpowers/references/codex-tools.md +++ b/skills/using-superpowers/references/codex-tools.md @@ -36,6 +36,25 @@ disagree. spawn allowlist — V2 accepts only V2-capable presets and hard-errors on the rest. +## Waiting on children + +`wait_agent` is an event subscription, not a poll: a long wait wakes +the moment a child produces mailbox activity, with the same latency as +a short one. Short-timeout polling buys nothing and costs a tool call — +and a context rebill — per poll. In measured sessions, roughly +two-thirds of all wait calls were short polls that timed out. + +- While you still have local work, do not wait at all. A completed + child's final answer is pushed into your mailbox and arrives with + your next turn. +- When you are genuinely idle with children outstanding, issue ONE + `wait_agent` with a long `timeout_ms` — 900000 (15 minutes) or more — + and let the event wake you. +- Completion mail cannot wake an idle controller (it is delivered + without triggering a turn); covering that idle window is + `wait_agent`'s only job. If a long wait times out, check + `list_agents` for stuck children — do not fall back to short polls. + ## Environment Detection Skills that create worktrees or finish branches should detect their From db4538fcb849be0273c792064355546388410f12 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 12:50:42 -0700 Subject: [PATCH 075/198] fix(sdd): controllers wait long or not at all Docs-only wait guidance in the platform reference changed nothing (65.1% vs 67.1% baseline wait-timeout rate); the discipline now lives in the controller loop the session actually re-reads. --- skills/subagent-driven-development/SKILL.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index 6c0b8349d..cc4ad1137 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -197,6 +197,14 @@ Everything you paste into a dispatch prompt — and everything a subagent prints back — stays resident in your context for the rest of the session and is re-read on every later turn. Hand artifacts over as files. +**Waiting on dispatched subagents:** never poll a wait interface with +short timeouts. While you have local work — ledger updates, packaging +the next review, reading reports — keep working; child results arrive +on their own. Wait only when you are genuinely idle, and then issue one +long wait (fifteen minutes or more, where your platform allows it) +instead of many short ones: a long wait wakes just as fast and costs +one call instead of dozens. + ### 1. Dispatch the implementer Record BASE (`git rev-parse HEAD`) before dispatching — the review package From d8189d1587ed29cbf7b01ed4138edc8799164898 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 15:57:32 -0700 Subject: [PATCH 076/198] fix(sdd,codex): bounded wait stretches with reconciliation Round 2 proved the long-wait mechanism (65.1%->0.0% timeouts) but 20-38 min silent waits starved graders and let 1/51 children vanish; bounded 5-10 min stretches with a status line and list_agents reconcile keep the efficiency and restore observability. --- skills/subagent-driven-development/SKILL.md | 15 +++++++++------ .../using-superpowers/references/codex-tools.md | 14 +++++++++----- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index cc4ad1137..5a7da97b3 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -198,12 +198,15 @@ prints back — stays resident in your context for the rest of the session and is re-read on every later turn. Hand artifacts over as files. **Waiting on dispatched subagents:** never poll a wait interface with -short timeouts. While you have local work — ledger updates, packaging -the next review, reading reports — keep working; child results arrive -on their own. Wait only when you are genuinely idle, and then issue one -long wait (fifteen minutes or more, where your platform allows it) -instead of many short ones: a long wait wakes just as fast and costs -one call instead of dozens. +short timeouts, and never sit in one silent, open-ended wait either. +While you have local work — ledger updates, packaging the next review, +reading reports — keep working; child results arrive on their own. +When you are genuinely idle, wait in bounded stretches (five to ten +minutes, where your platform allows), and between stretches post one +line of status and reconcile your live children: list them, and chase +any that finished without reporting. A bounded stretch keeps nearly +all of a long wait's efficiency while guaranteeing a stuck or lost +child is noticed within minutes, not at the end of the session. ### 1. Dispatch the implementer diff --git a/skills/using-superpowers/references/codex-tools.md b/skills/using-superpowers/references/codex-tools.md index cf2b70ee5..077550e04 100644 --- a/skills/using-superpowers/references/codex-tools.md +++ b/skills/using-superpowers/references/codex-tools.md @@ -47,13 +47,17 @@ two-thirds of all wait calls were short polls that timed out. - While you still have local work, do not wait at all. A completed child's final answer is pushed into your mailbox and arrives with your next turn. -- When you are genuinely idle with children outstanding, issue ONE - `wait_agent` with a long `timeout_ms` — 900000 (15 minutes) or more — - and let the event wake you. +- When you are genuinely idle with children outstanding, wait in + bounded stretches: `wait_agent` with `timeout_ms` 300000-600000 + (5-10 minutes). After each stretch — wake or timeout — post one + status line, run `list_agents`, and chase any child that finished + without reporting. Never stack polls shorter than five minutes; the + event subscription wakes a bounded stretch just as fast as a short + one. - Completion mail cannot wake an idle controller (it is delivered without triggering a turn); covering that idle window is - `wait_agent`'s only job. If a long wait times out, check - `list_agents` for stuck children — do not fall back to short polls. + `wait_agent`'s only job. A stretch that times out with no activity + is your cue to reconcile, not to shorten the next stretch. ## Environment Detection From e9686d5c09b80323bfdc44be8804081e46ea0986 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 30 Jul 2026 10:35:28 -0700 Subject: [PATCH 077/198] fix(codex): explicit model+effort on every spawn, config backstop Depth-2 child-issued spawns omitted model 2/2 at CLI 0.146; model without reasoning_effort resets effort to the model default. --- .../references/codex-tools.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/skills/using-superpowers/references/codex-tools.md b/skills/using-superpowers/references/codex-tools.md index 077550e04..e4488fb22 100644 --- a/skills/using-superpowers/references/codex-tools.md +++ b/skills/using-superpowers/references/codex-tools.md @@ -59,6 +59,25 @@ two-thirds of all wait calls were short polls that timed out. `wait_agent`'s only job. A stretch that times out with no activity is your cue to reconcile, not to shorten the next stretch. +## Model routing on spawns + +Every `spawn_agent` you issue — including when you are yourself a +spawned child running a fan-out — sets `model` AND `reasoning_effort` +explicitly, per the Model Selection rules of the skill you are +executing. Setting `model` alone is a trap: the child's effort +silently resets to that model's default, not to yours. + +Ask your human partner to add a machine-level backstop to +`~/.codex/config.toml` so any spawn that slips through still routes to +a deliberate tier instead of silently inheriting the session's most +expensive model: + +```toml +[agents] +default_subagent_model = "" +default_subagent_reasoning_effort = "medium" +``` + ## Environment Detection Skills that create worktrees or finish branches should detect their From 3ff8d15f15cc15408e8b637e4dab1e922ba8af0a Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Fri, 31 Jul 2026 10:52:05 -0700 Subject: [PATCH 078/198] docs: codex-efficiency fix-cycle spec and plan (campaign record) --- .../2026-07-30-codex-efficiency-fixes.md | 1009 +++++++++++++++++ ...026-07-30-codex-efficiency-fixes-design.md | 252 ++++ 2 files changed, 1261 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-30-codex-efficiency-fixes.md create mode 100644 docs/superpowers/specs/2026-07-30-codex-efficiency-fixes-design.md diff --git a/docs/superpowers/plans/2026-07-30-codex-efficiency-fixes.md b/docs/superpowers/plans/2026-07-30-codex-efficiency-fixes.md new file mode 100644 index 000000000..7c689bf7a --- /dev/null +++ b/docs/superpowers/plans/2026-07-30-codex-efficiency-fixes.md @@ -0,0 +1,1009 @@ +# Codex Efficiency Fixes 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:** Ship the five evidence-strong treatments (T1–T5) from the codex-efficiency eval campaign as skill/doc changes on `codex-efficiency-fixes`, grade each against its pre-registered criterion with the campaign's scorers, and cut one PR per passing treatment against `dev`. + +**Architecture:** Skill-text edits land in this worktree (`.worktrees/codex-efficiency-fixes`); eval rig work, hypothesis-log entries, and scorers live in `superpowers-autoresearch` (main, push authorized); scenario changes live in `superpowers-autoresearch/campaigns/codex-efficiency/scenarios/`. Batteries run through the existing quorum container lanes against a `/tmp/sp-arm-fix` worktree arm. + +**Tech Stack:** Markdown skill text; Python 3 scorers (pytest); bash quorum runner; Codex/Claude/Gemini CLIs in the evals container. + +**Spec:** `docs/superpowers/specs/2026-07-30-codex-efficiency-fixes-design.md` (approved). The spec's baselines and criteria govern; this plan repeats them per task. + +## Global Constraints + +- The hypothesis log (`superpowers-autoresearch/logs/2026-07-30-codex-efficiency-fixes.md`) is append-only; corrections are new dated entries, never edits. Every battery gets a pre-registration entry BEFORE it runs. +- Raw rollouts and session content never enter any repo. Aggregates, scorer outputs, and distilled scenarios only. +- Before every autoresearch/evals commit: substring-aware grep of staged text AND the commit-message file against the campaign name-sets (client names, hostnames, ticket IDs). Oblique references only. +- Scenario post-checks (`checks.sh`) must never assert a behavioral choice a scorer measures. Measurement is scorer-side. +- Smoke-test ONE rep of any scenario/arm/harness combination before its battery. +- Scorer output files use rep-range names; existing aggregates are never overwritten without `FORCE=1`. +- Every scorer verdict requires manual inspection of matches (non-circular: never verify with the scorer's own helper). +- Brainstorming's frontmatter `description:` must not change (triggering depends on it). +- Skill edits must not alter files outside the named targets; no whitespace-only churn. +- PRs are cut per treatment ONLY after its criterion passes; merges require Jesse's per-PR approval. The codex-tools.md PRs declare merge order T3 → T2 → T5. +- Subagents running batteries poll in-session with long timeouts; no monitors. + +--- + +### Task 1: T1 — SDD worker-review prohibition + +**Files:** +- Modify: `skills/subagent-driven-development/implementer-prompt.md` (insert new section before `## Code Organization`) +- Modify: `skills/subagent-driven-development/SKILL.md` (dispatch bullet + Red Flags row) + +**Interfaces:** +- Consumes: nothing from other tasks. +- Produces: commit `fix(sdd): implementers never dispatch subagents` — the T1 PR cherry-picks exactly this commit. + +- [ ] **Step 1: Insert the implementer-prompt section** + +In `skills/subagent-driven-development/implementer-prompt.md`, immediately after the paragraph ending `run the full suite once before committing, not after every edit.` and before ` ## Code Organization`, insert (keeping the template's 4-space body indent): + +``` + ## You Do Not Dispatch Subagents + + Do all of this task's work yourself. Never spawn a subagent to + implement part of the task, and above all never spawn a reviewer to + check your work. Self-review (below) means reading your own diff. + Review is the controller's job: after you report, it dispatches a + fresh reviewer against your diff. A reviewer you spawn duplicates + that review at full cost, and its approval counts for nothing in + the process. If you catch yourself thinking "an independent review + would strengthen my report" — that review is already scheduled. + Report instead. +``` + +- [ ] **Step 2: Add the dispatch-contract bullet to SKILL.md** + +In `skills/subagent-driven-development/SKILL.md`, section `### 1. Dispatch the implementer`, after the bullet beginning `- A dispatch prompt describes one task, not the session's history.`, add: + +``` +- The dispatch carries the no-subagents contract (it is in the + implementer template): the implementer never dispatches subagents — + not helpers, and never a reviewer. Review arrives from you, after the + report. In real sessions, every reviewer a worker spawned duplicated + the task review the controller dispatched anyway — a full extra + review seat per task. +``` + +- [ ] **Step 3: Add the Red Flags row** + +In the same file's Red Flags table (`## Red Flags`), after the row `| "Ledger bookkeeping is overhead" | ... |`, add: + +``` +| "The implementer spawned its own reviewer — free extra assurance" | It's a duplicate seat reviewing the same diff; the task review is the gate. A worker-spawned reviewer is a defect to flag, not rigor. | +``` + +- [ ] **Step 4: Verify** + +Run: `grep -c "You Do Not Dispatch Subagents" skills/subagent-driven-development/implementer-prompt.md` → expect `1`. Run: `grep -c "no-subagents contract\|spawned its own reviewer" skills/subagent-driven-development/SKILL.md` → expect `2`. + +- [ ] **Step 5: Commit** + +```bash +git add skills/subagent-driven-development/implementer-prompt.md skills/subagent-driven-development/SKILL.md +git commit -m "fix(sdd): implementers never dispatch subagents + +Depth-2 worker-spawned reviewers were 9/9 same-task duplicate reviews +across four corpora in the codex-efficiency eval campaign." +``` + +--- + +### Task 2: T3 — codex-tools.md version-honest multi-agent rewrite + +**Files:** +- Modify: `skills/using-superpowers/references/codex-tools.md` (replace the paragraph after the config block) + +**Interfaces:** +- Consumes: nothing. +- Produces: the rewritten base section Tasks 3 and 4 append after; commit `fix(codex): correct multi-agent guidance against Codex source` (T3 PR). + +- [ ] **Step 1: Replace the multi-agent paragraph** + +In `skills/using-superpowers/references/codex-tools.md`, replace the entire single paragraph beginning `This enables \`spawn_agent\`, \`wait_agent\`, and \`close_agent\`` (and ending `...carrying the brief, the report file, and the findings.`) with: + +``` +This enables the multi-agent tools that skills like +`dispatching-parallel-agents` and `subagent-driven-development` use. +Which tools you get depends on the multi-agent version your model +preset selects (current presets run V2; older ones run V1). Trust your +actual tool list over any table — including this one — when they +disagree. + +- **Spawning:** give children a clean context with + `spawn_agent {fork_turns: "none"}`; the default `"all"` copies your + entire transcript into the child. On Codex 0.145+, role files under + `~/.codex/agents/` attach to isolated forks via `agent_type`. + Full-history forks accept `model` and `reasoning_effort` overrides + (only `agent_type` is refused there) — isolated forks are the SDD + default for context hygiene, not because overrides require them. +- **Fix rounds:** resume the implementer with `followup_task` — it + delivers your message, triggers a turn, and transparently reloads a + child the harness evicted. Never dispatch a fresh implementer on the + theory that a spawned agent cannot be messaged again; on V2 it + always can. +- **Lifecycle:** V2 has no `close_agent`. Finished children are + evicted automatically when slots are needed; leaving them unclosed + costs nothing. Only V1 sessions have `close_agent` — there, close + reviewers when their review returns, and close each implementer + after its task's review passes. +- **Model names:** never copy a model name from a skill, table, or old + session into `spawn_agent` without checking it against your current + spawn allowlist — V2 accepts only V2-capable presets and hard-errors + on the rest. +``` + +- [ ] **Step 2: Verify** + +Run: `grep -c "close_agent" skills/using-superpowers/references/codex-tools.md` → expect `2` (both inside the Lifecycle bullet). Run: `grep -c "cannot be messaged again" skills/using-superpowers/references/codex-tools.md` → expect `1`. + +- [ ] **Step 3: Commit** + +```bash +git add skills/using-superpowers/references/codex-tools.md +git commit -m "fix(codex): correct multi-agent guidance against Codex source + +Five claims contradicted by the Codex CLI source (V2 has no +close_agent; followup_task always reaches a child; role files attach +via agent_type; full-history forks accept model/effort; V2 spawn +allowlist). Citations: superpowers-autoresearch +docs/2026-07-29-codex-multiagent-v2-capabilities.md." +``` + +--- + +### Task 3: T2 — codex-tools.md event-driven waiting section + +**Files:** +- Modify: `skills/using-superpowers/references/codex-tools.md` (new section after Task 2's block, before `## Environment Detection`) + +**Interfaces:** +- Consumes: Task 2's rewritten base section (append directly after it). +- Produces: commit `fix(codex): event-driven waiting instead of short polls` (T2 PR; declares dependency on T3's PR). + +- [ ] **Step 1: Insert the section** + +Immediately before `## Environment Detection`, insert: + +``` +## Waiting on children + +`wait_agent` is an event subscription, not a poll: a long wait wakes +the moment a child produces mailbox activity, with the same latency as +a short one. Short-timeout polling buys nothing and costs a tool call — +and a context rebill — per poll. In measured sessions, roughly +two-thirds of all wait calls were short polls that timed out. + +- While you still have local work, do not wait at all. A completed + child's final answer is pushed into your mailbox and arrives with + your next turn. +- When you are genuinely idle with children outstanding, issue ONE + `wait_agent` with a long `timeout_ms` — 900000 (15 minutes) or more — + and let the event wake you. +- Completion mail cannot wake an idle controller (it is delivered + without triggering a turn); covering that idle window is + `wait_agent`'s only job. If a long wait times out, check + `list_agents` for stuck children — do not fall back to short polls. +``` + +- [ ] **Step 2: Verify** + +Run: `grep -c "Waiting on children" skills/using-superpowers/references/codex-tools.md` → expect `1`. Run: `grep -n "900000" skills/using-superpowers/references/codex-tools.md` → expect one hit. + +- [ ] **Step 3: Commit** + +```bash +git add skills/using-superpowers/references/codex-tools.md +git commit -m "fix(codex): event-driven waiting instead of short polls + +60-78% of wait_agent calls timed out across every measured corpus; +waits are event subscriptions, so one long wait replaces dozens of +polls at identical wake latency." +``` + +--- + +### Task 4: T5 — codex-tools.md model routing on spawns + +**Files:** +- Modify: `skills/using-superpowers/references/codex-tools.md` (new section after Task 3's, before `## Environment Detection`) + +**Interfaces:** +- Consumes: Tasks 2–3 in place. +- Produces: commit `fix(codex): explicit model+effort on every spawn, config backstop` (T5 PR; declares dependency on T3's and T2's PRs). + +- [ ] **Step 1: Insert the section** + +Immediately before `## Environment Detection`, insert: + +```` +## Model routing on spawns + +Every `spawn_agent` you issue — including when you are yourself a +spawned child running a fan-out — sets `model` AND `reasoning_effort` +explicitly, per the Model Selection rules of the skill you are +executing. Setting `model` alone is a trap: the child's effort +silently resets to that model's default, not to yours. + +Ask your human partner to add a machine-level backstop to +`~/.codex/config.toml` so any spawn that slips through still routes to +a deliberate tier instead of silently inheriting the session's most +expensive model: + +```toml +[agents] +default_subagent_model = "" +default_subagent_reasoning_effort = "medium" +``` +```` + +- [ ] **Step 2: Verify** + +Run: `grep -c "Model routing on spawns" skills/using-superpowers/references/codex-tools.md` → expect `1`. Run: `grep -c "default_subagent_model" skills/using-superpowers/references/codex-tools.md` → expect `1`. + +- [ ] **Step 3: Commit** + +```bash +git add skills/using-superpowers/references/codex-tools.md +git commit -m "fix(codex): explicit model+effort on every spawn, config backstop + +Depth-2 child-issued spawns omitted model 2/2 at CLI 0.146; model +without reasoning_effort resets effort to the model default." +``` + +--- + +### Task 5: T4 — brainstorming three-path router (variant C) + +**Files:** +- Modify: `skills/brainstorming/SKILL.md` + +The frontmatter `description:` is untouched. Edits below are complete replacements for the named regions; everything not named stays byte-identical. + +- [ ] **Step 1: Replace intro sentence, HARD-GATE, and anti-pattern section** + +Replace from the line `Start by understanding the current project context, ...` through the end of the `## Anti-Pattern: "This Is Too Simple To Need A Design"` section (i.e., up to but not including `## Checklist`) with: + +``` +Start by classifying how much process the request needs, then work +through your path: understand the context, refine the idea, present a +design, and get your human partner's approval. + + +Do NOT invoke any implementation skill, write any code, scaffold any +project, or take any implementation action until you have told your +human partner what you intend and they have approved it. This applies +to EVERY task on EVERY path below — the ceremony scales with the task; +the approval gate never does. + + +## Three Paths + +Before your first question, classify the request and say the +classification out loud — "this looks bounded, so I'll present a short +design here rather than write a spec" — so your human partner can +override it: + +- **Spike** — a feasibility question ("can we...", "is it possible...", + "quick and dirty is fine") whose output is an answer, not code you + keep. Present the question and what you'll try in 2-3 sentences, get + a nod, then find out as cheaply as correctness allows. No design + doc, no spec file. Report findings as a recommendation; anything you + built stays labeled throwaway. +- **Bounded** — a well-scoped change to an existing, understood flow: a + new flag, a small endpoint, a one-file fix. Ask the clarifying + questions that matter, present a short design IN CHAT (a few + sentences to a few short paragraphs), and get approval. No spec + file, no implementation plan document. +- **Architectural** — new projects, new subsystems, changes that + restructure how components fit together or alter interfaces others + depend on. Follow the full process: questions, approaches, sectioned + design, written spec, then the writing-plans skill. + +When in doubt between two paths, take the heavier one. The ratchet is +one-way: hidden complexity discovered mid-task upgrades the path — +stop, say so, and step up. Nothing downgrades mid-task. + +## Anti-Pattern: "Too Simple To Need Approval" + +Every path ends with your human partner approving your intent before +implementation. A todo list, a single-function utility, a config +change — the design may be two sentences in chat, but you MUST present +it and get approval. "Simple" tasks are where unexamined assumptions +cause the most wasted work. What scales with simplicity is the +artifact, never the approval. + +## Red Flags + +| Thought | Reality | +|---------|---------| +| "This is too simple to need a design" | Simple means a short design, not no design. Two sentences in chat, then approval. | +| "I'll call it bounded and skip the spec" | Reaching for a label to skip work IS the doubt — take the heavier path. | +| "The spike works, so I'll keep the code" | A spike's output is an answer. Keeping the code is a new request — classify it. | +| "It grew, but I'm almost done — no need to re-classify" | Hidden complexity upgrades the path mid-task. Stop and say so. | +| "They approved the spike, so the follow-up change is approved too" | Each task gets its own classification and its own approval. | +``` + +- [ ] **Step 2: Replace the Checklist section** + +Replace the `## Checklist` section body (from `You MUST create a task...` through item 9) with: + +``` +Classify first, announce the path, then create a task for each item on +your path and complete them in order. + +**Spike:** +1. **Explore project context** — enough to frame the probe +2. **Present question + probe plan** — 2-3 sentences +3. **Get approval** — a nod is enough +4. **Investigate** — as cheaply as correctness allows +5. **Report findings** — a recommendation; label anything built as throwaway + +**Bounded:** +1. **Explore project context** — check files, docs, recent commits +2. **Ask clarifying questions** — one at a time, the ones that matter +3. **Present short design in chat** — approach, files touched, testing +4. **Get approval** — explicit, before any implementation +5. **Implement** — proceed with the normal development workflow (TDD applies); no plan document + +**Architectural:** +1. **Explore project context** — check files, docs, recent commits +2. **Offer the visual companion just-in-time** — NOT upfront. The first time a question would genuinely be clearer shown than described, offer it then (its own message); on approval its browser tab opens for you. If no visual question ever arises, never offer it. See the Visual Companion section below. +3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria +4. **Propose 2-3 approaches** — with trade-offs and your recommendation +5. **Present design** — in sections scaled to their complexity, get user approval after each section +6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD--design.md` and commit +7. **Spec self-review** — quick inline check for placeholders, contradictions, ambiguity, scope (see below) +8. **User reviews written spec** — ask user to review the spec file before proceeding +9. **Transition to implementation** — invoke writing-plans skill to create implementation plan +``` + +- [ ] **Step 3: Replace the Process Flow graph** + +Replace the entire ```dot ... ``` block under `## Process Flow` with: + +``` +digraph brainstorming { + "Classify: spike / bounded / architectural" [shape=diamond]; + "Present question + probe (2-3 sentences)" [shape=box]; + "Ask clarifying questions (bounded)" [shape=box]; + "Present short design in chat" [shape=box]; + "Human approves?" [shape=diamond]; + "Investigate; report recommendation" [shape=doublecircle]; + "Implement via normal workflow (no plan doc)" [shape=doublecircle]; + "Explore project context" [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]; + "Hidden complexity? Upgrade path" [shape=box]; + + "Classify: spike / bounded / architectural" -> "Present question + probe (2-3 sentences)" [label="spike"]; + "Classify: spike / bounded / architectural" -> "Ask clarifying questions (bounded)" [label="bounded"]; + "Classify: spike / bounded / architectural" -> "Explore project context" [label="architectural"]; + "Present question + probe (2-3 sentences)" -> "Human approves?"; + "Ask clarifying questions (bounded)" -> "Present short design in chat"; + "Present short design in chat" -> "Human approves?"; + "Human approves?" -> "Investigate; report recommendation" [label="spike: yes"]; + "Human approves?" -> "Implement via normal workflow (no plan doc)" [label="bounded: yes"]; + "Hidden complexity? Upgrade path" -> "Classify: spike / bounded / architectural"; + "Explore project context" -> "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"]; +} +``` + +- [ ] **Step 4: Replace the terminal-state paragraph** + +Replace the paragraph `**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.` with: + +``` +**Terminal states are path-bound.** Architectural: the ONLY skill you +invoke after brainstorming is writing-plans — never frontend-design, +mcp-builder, or any other implementation skill. Bounded: after +approval, implementation proceeds directly through the normal +development workflow; no plan document. Spike: the terminal state is a +reported recommendation. +``` + +- [ ] **Step 5: Scope the long-form sections to their paths** + +(a) Immediately under `## The Process`, insert as the first line: + +``` +The subsections below serve the bounded and architectural paths (a +spike stops at "present the probe, get a nod"). Sections from +**Exploring approaches** onward are architectural-path depth — for +bounded work, context plus a few questions plus a short in-chat design +is the whole process. +``` + +(b) Rename the heading `## After the Design` to `## After the Design (architectural path)`. + +- [ ] **Step 6: Verify** + +Run: `grep -c "Three Paths" skills/brainstorming/SKILL.md` → `1`; `grep -c "regardless of perceived simplicity" skills/brainstorming/SKILL.md` → `0`; `grep -c "^description:" skills/brainstorming/SKILL.md` unchanged vs `git show origin/dev:skills/brainstorming/SKILL.md | grep -c "^description:"`; confirm `git diff origin/dev -- skills/brainstorming/SKILL.md` shows no frontmatter hunk. If `dot` is installed: `awk '/^```dot$/,/^```$/' skills/brainstorming/SKILL.md | sed '1d;$d' | dot -Tcanon >/dev/null` → exit 0. + +- [ ] **Step 7: Commit** + +```bash +git add skills/brainstorming/SKILL.md +git commit -m "feat(brainstorming): three-path router — ceremony scales, approval never does + +Spike / bounded / architectural classification said out loud, one-way +upgrade ratchet, approval gate on every path. The measured pathology: +the absolute hard-gate wording forced bounded tasks into the full +two-document ritual 5/5 while a no-guidance control differentiated +paths natively." +``` + +--- + +### Task 6: Fix arm + hypothesis log + +**Files:** +- Create: `superpowers-autoresearch/logs/2026-07-30-codex-efficiency-fixes.md` +- Create (filesystem, not committed): `/tmp/sp-arm-fix` worktree + +**Interfaces:** +- Consumes: Tasks 1–5 committed on `codex-efficiency-fixes`. +- Produces: the arm every battery runs against; the log every later task appends to. + +- [ ] **Step 1: Create the arm** + +```bash +git -C /Users/jesse/git/superpowers/superpowers worktree add --detach /tmp/sp-arm-fix codex-efficiency-fixes +git -C /tmp/sp-arm-fix log --oneline -1 # must show Task 5's commit +``` + +(Before any LATER battery, refresh with `git -C /tmp/sp-arm-fix checkout --detach codex-efficiency-fixes`.) + +- [ ] **Step 2: Create the log** + +Write `superpowers-autoresearch/logs/2026-07-30-codex-efficiency-fixes.md` with: title `# Codex efficiency fix cycle — hypothesis log`; a header block stating it is append-only, naming the spec path (`superpowers/docs/superpowers/specs/2026-07-30-codex-efficiency-fixes-design.md`), the branch, the arm (`/tmp/sp-arm-fix`), and the carried-over standing rules (pre-registration before batteries, manual match inspection, no raw rollouts, discrimination rule); and a `## Pre-registered criteria (from the approved spec)` section reproducing verbatim the five criterion lines from the spec's treatment sections (T1: 0 worker-issued depth-2 spawns AND review coverage preserved; T2: timeout rate < 25%, no completion loss; T3: source-cited corrections, no scorer regressions; T4: the three-layer criteria; T5: explicit model+effort at every depth, with the pre-registered inconclusive-by-zero caveat). + +- [ ] **Step 3: Privacy sweep and commit (autoresearch)** + +```bash +cd /Users/jesse/git/superpowers/superpowers-autoresearch +git add logs/2026-07-30-codex-efficiency-fixes.md +git diff --cached | grep -iE 'paradise|magic-kingdom|flower|pallas|web1|teststrip|PRI-[0-9]' && echo LEAK || echo clean # must print clean +git commit -m "docs: open the codex-efficiency fix-cycle hypothesis log" +``` + +--- + +### Task 7: Micro — variant C + adversarial briefs + +**Files:** +- Modify: `superpowers-autoresearch/campaigns/codex-efficiency/ceremony-path-micro.py` +- Create: `superpowers-autoresearch/campaigns/codex-efficiency/out/` micro outputs (NOT committed; aggregates go in the log) + +**Interfaces:** +- Consumes: Task 5's shipped router text (the variant must quote it), Task 6's log. +- Produces: micro verdict for T4 layer 1. + +- [ ] **Step 1: Extend the script** + +Read the current script first. Then: (a) add a variant `C-approval` whose text is the Three Paths block from Task 5 Step 1 (the three bullets plus the doubt/ratchet paragraph, verbatim); (b) neutralize the shared SYSTEM answer definitions so classification measures the ARTIFACT level, not the approval step — replace the three definition bullets with: SPIKE = "dive straight into a minimal throwaway investigation — no design document"; BOUNDED = "make the change after at most brief clarification and a short in-chat design — no design document, no implementation plan"; FULL = "run the complete design process — written design document and implementation plan before touching code"; (c) add two briefs after the existing three: + +`ambig-interface`: "Add a --json flag to our export CLI command so output can be piped to jq. The current text output of export is parsed line-by-line by three downstream scripts in tools/ that other teams run in their pipelines." + +`ambig-crosscut`: "Fix the timezone bug in report_generator.py where daily rollups are off by one day for users west of UTC. Rollup boundaries are also computed independently in the billing exporter and the retention job, which must stay consistent with reports." + +Matrix: 3 variants (Z-null, A-current, C-approval) × 5 briefs × 5 reps = 75 calls, model `claude-opus-4-8`, same one-word regex scoring and answer-file verification as the campaign run. + +- [ ] **Step 2: Pre-register in the log** + +Append an entry BEFORE running: the taxonomy change (new SYSTEM definitions — within-run comparisons only; not comparable cell-by-cell to the campaign's micro), the matrix, and predictions: C-approval — spike→SPIKE ≥4/5, bounded→BOUNDED ≥4/5, arch→FULL 5/5, both ambig→FULL ≥4/5; A-current — bounded→FULL persists; Z-null on ambig briefs recorded as an observation (does unguided judgment escalate?). Commit the entry. + +- [ ] **Step 3: Run and verify** + +Run the sweep. Independently verify every answer file is exactly one word via a separate command (e.g. `awk 'NF!=1' out/micro-c/*.txt`), not the scorer's own parser. + +- [ ] **Step 4: Verdict entry + commit** + +Append the results table and verdict to the log (criteria from Step 2). Privacy-sweep, commit script + log entry. If C-approval fails a cell, STOP: report to the controller — the router text needs revision before any battery spends on it. + +--- + +### Task 8: Shared SDD battery (T1, T2, T5) + +**Files:** +- Create: `superpowers-autoresearch/campaigns/codex-efficiency/out/` fix-arm aggregates (rep-range filenames) +- Modify: `superpowers-autoresearch/logs/2026-07-30-codex-efficiency-fixes.md` (pre-registration + verdicts) +- Possibly modify: `superpowers-autoresearch/campaigns/codex-efficiency/run-quorum.sh` (only if the `fix` arm name needs wiring — read it first; the campaign convention maps ARM → `/tmp/sp-arm-$ARM`) + +**Interfaces:** +- Consumes: Tasks 1–6. +- Produces: T1/T2/T5 verdicts; the runs Task 11's regression comparison may reuse. + +- [ ] **Step 1: Pre-register** — append the battery entry (arm=fix @ the arm's SHA, scenario `cx-sdd-small`, 8 reps across lanes A and B, JOBS=2, scorers e6/e7/e1, criteria verbatim from the log's criteria section, budget estimate ~$40). Commit. + +- [ ] **Step 2: Smoke test** — 1 rep: `EVALS_ROOT= JOBS=1 bash run-quorum.sh fix cx-sdd-small 1`. Inspect the verdict and one rollout by hand: session ran, spawns present, no setup failure. Any infra anomaly stops the battery. + +- [ ] **Step 3: Run the battery** — 7 more reps split across lanes (`REP_START` per the runner's convention, e.g. reps 2–4 lane A, 5–8 lane B). Poll in-session with long timeouts; no monitors. + +- [ ] **Step 4: Score** — run `score_e6.py`, `score_e7.py`, `score_e1.py` over the fix-arm runs with rep-range output names. Manually inspect: every depth-2 spawn (should be none worker-issued), every wait call classification for 2+ runs, every spawn tuple for 2+ runs — against raw rollouts, not scorer helpers. + +- [ ] **Step 5: Verdict entries** — per treatment, against pre-registered criteria; record the T5 inconclusive-by-zero branch honestly if depth-2 spawns vanished. Ledger row with measured cost. Privacy-sweep; commit aggregates + log. + +--- + +### Task 9: Codex ceremony battery (T4 layer 2) + +**Files:** +- Modify: log (pre-registration + verdict); `out/` aggregates. + +**Interfaces:** +- Consumes: Tasks 5, 6; Task 7 must have PASSED. +- Produces: T4 layer-2 verdict. + +- [ ] **Step 1: Pre-register** — arm=fix, `cx-ceremony-{spike,bounded,arch}`, 3 reps each, scorer `score_e4.py`; criteria: bounded — approval turn present, 0 committed spec/plan docs, 0 writing-plans ritual; arch — two-doc flow intact 3/3; spike — no docs, minimal ceremony; plus gauntlet task completion preserved per cell. Budget ~$40. Commit. + +- [ ] **Step 2: Smoke test** — 1 bounded rep; hand-inspect the rollout for scenario health (not for the measured behavior). + +- [ ] **Step 3: Run remaining 8 runs across lanes.** + +- [ ] **Step 4: Score + manually verify** — `score_e4.py` census; hand-verify one rep per class against raw timestamps (the campaign's hand-recount method: doc patches vs first non-doc patch). + +- [ ] **Step 5: Verdict entry** — versus criteria; ledger row; sweep; commit. + +--- + +### Task 10: ATIF ceremony census scorer (for the global battery) + +**Files:** +- Create: `superpowers-autoresearch/campaigns/codex-efficiency/score_t4_regression.py` +- Create: `superpowers-autoresearch/campaigns/codex-efficiency/test_score_t4_regression.py` +- Create: `superpowers-autoresearch/campaigns/codex-efficiency/fixtures/atif-ceremony/` (synthetic `trajectory.json` fixtures) + +**Interfaces:** +- Consumes: quorum's per-run `trajectory.json` (ATIF v1.7; tool calls with file paths and step timestamps — see `superpowers/evals/src/atif/types.ts` for the shape). +- Produces: per-run census dict: `{spec_docs_written: int, plan_docs_written: int, doc_writes_before_first_code: int, first_code_file: str|null, user_turns_before_first_code: int, writing_plans_invoked: bool}`; consumed by Task 11. + +- [ ] **Step 1: Write failing tests** — build three synthetic trajectory fixtures: (a) full-ceremony (writes `docs/superpowers/specs/x-design.md` then `docs/superpowers/plans/x.md` then `src/app.py`), (b) bounded-lean (writes `src/app.py` first, no docs), (c) doc-only-readme (writes `README.md` then code — README is NOT a ceremony doc). Assert the census fields for each, including `writing_plans_invoked` detection via a tool call reading a path containing `skills/writing-plans` (fixture (a) true, others false). Run `python3 -m pytest test_score_t4_regression.py` → all FAIL (module missing). + +- [ ] **Step 2: Implement** — ceremony docs are paths matching `docs/superpowers/(specs|plans)/`; code files are any other write outside `docs/` and not `*.md` at repo root; count user turns from ATIF steps preceding the first code write. Run tests → PASS. + +- [ ] **Step 3: Commit** (autoresearch, after sweep): `feat: ATIF ceremony census scorer for cross-harness T4 regression`. + +--- + +### Task 11: Global regression battery (T4 layer 3) — Claude Code + Gemini + +**Files:** +- Create: `superpowers-autoresearch/campaigns/codex-efficiency/scenarios/cc-ceremony-{spike,bounded,arch}/` (copies of the `cx-` scenarios with the `# coding-agents:` line set to `claude,gemini`; strip any codex-only setup) +- Modify: log (pre-registration + verdict); `out/` aggregates. + +**Interfaces:** +- Consumes: Task 10's scorer; Tasks 5–6; lane containers with Claude/Gemini auth (Claude: `ANTHROPIC_API_KEY`; Gemini: `GEMINI_API_KEY` — see `superpowers/evals/README.md` and `coding-agents/*-context/HOWTO.md`). +- Produces: T4 layer-3 verdict (the cross-harness regression evidence the T4 PR requires). + +- [ ] **Step 1: Port the scenarios** — copy each `cx-ceremony-*`, retarget the agents line, review `setup.sh`/`checks.sh` for codex-isms (post-checks must stay behavior-neutral). `bun run quorum check` (in the lane's evals checkout) must pass. + +- [ ] **Step 2: Pre-register** — matrix: {dev, fix} arms × {claude, gemini} × 3 scenarios × 3 reps = 36 runs (~$40–80; Claude/Gemini runs are the cheap side). Criteria: (a) per-cell gauntlet pass rate fix ≥ dev; (b) fix-arm arch cells keep `spec_docs_written ≥ 1` and `writing_plans_invoked` 3/3; (c) fix-arm bounded cells show `spec_docs_written = 0` and `writing_plans_invoked = false`; (d) dev-arm bounded behavior recorded as the baseline (expected: two-doc ritual). Commit. + +- [ ] **Step 3: Smoke test** — 1 rep per harness (2 runs) before the matrix. + +- [ ] **Step 4: Run the matrix across both lanes; score with `score_t4_regression.py`; manually inspect one trajectory per harness per arm.** + +- [ ] **Step 5: Verdict entry** — versus criteria; ledger row; sweep; commit scenarios + aggregates + log. + +--- + +### Task 12: Triggering acceptance check (all three harnesses) + +**Files:** +- Modify: log (pre-registration + verdict). + +**Interfaces:** +- Consumes: `/tmp/sp-arm-fix`; the containerized triggering approach (host runs are confounded — `superpowers-autoresearch` docs and `scripts/evals-container`). +- Produces: the "brainstorming still auto-triggers" evidence line every T4 PR cites. + +- [ ] **Step 1: Pre-register** — prompt: exactly `Let's make a react todo list`; fix arm; 3 reps × {codex, claude, gemini}; criterion: brainstorming loads before any implementation action AND the session heads down the architectural path (new project), 3/3 per harness. Commit. + +- [ ] **Step 2: Run** — containerized, per the campaign's triggering method; verify skill load from transcripts/rollouts by hand. + +- [ ] **Step 3: Verdict entry; sweep; commit.** + +--- + +### Task 13: Cut the treatment PRs + +**Files:** +- Create: five branches `fix/t1-sdd-no-worker-reviewers`, `fix/t3-codex-tools-corrections`, `fix/t2-codex-event-waits`, `fix/t5-codex-spawn-routing`, `fix/t4-brainstorming-three-paths`, each cherry-picked from `codex-efficiency-fixes` onto `origin/dev` +- Create: PR body files under the SDD workspace (drafted from `.github/PULL_REQUEST_TEMPLATE.md`) + +**Interfaces:** +- Consumes: verdicts from Tasks 7–12; only treatments whose criteria PASSED get a PR. +- Produces: pushed branches + draft PR bodies. **STOP before opening PRs: present the PR set (diffs + bodies + verdict table) to Jesse. PRs open only on his go; merges are his.** + +- [ ] **Step 1:** For each passing treatment: branch off `origin/dev`, cherry-pick its commit(s), verify `git diff` matches the treatment's slice of the fix branch. +- [ ] **Step 2:** Draft each PR body: full template, identification block (model, harness, plugins), problem statement from the campaign evidence, eval results from the log's verdict entries, related-PR section citing #2036/#2035 as prior art NOT adopted (and why), merge-order note on the codex-tools trio (T3 → T2 → T5). +- [ ] **Step 3:** Push branches. Present everything to Jesse and STOP. + +--- + +### Task 14: Campaign closeout + +**Files:** +- Modify: `superpowers-autoresearch/logs/2026-07-30-codex-efficiency-fixes.md` (closing summary + final ledger) +- Create: `superpowers-autoresearch/reports/2026-07-codex-efficiency-fix-cycle.md` (verdict table: five treatments × criterion × result × PR link; phase-2 queue restated with what each item still needs) + +**Interfaces:** +- Consumes: everything above. +- Produces: the record phase 2 starts from. + +- [ ] **Step 1:** Write the report; totals in the ledger; note any criterion that failed and what was NOT shipped as a result. +- [ ] **Step 2:** Privacy sweep; commit; push autoresearch main (authorized). + +--- + +## Amendment 1 (2026-07-30, Jesse-approved after the first shared battery) + +The first shared SDD battery (Task 8, n=6) returned FAIL on T1/T2/T5. Root +causes and approved responses: (a) the no-subagents contract reached only +implementer-prompt.md — the final reviewer spawned two sub-reviewers +(T1's miss, and both of T5's); extend the contract to every dispatched +role. (b) Docs-only wait guidance in codex-tools.md produced no behavior +change (65.1% vs 67.1% baseline timeouts); move the wait discipline into +the SDD controller text. Then re-run the battery. + +### Task 15: T1-ext — no-subagents contract in all reviewer templates + +**Files:** +- Modify: `skills/subagent-driven-development/task-reviewer-prompt.md` +- Modify: `skills/subagent-driven-development/re-review-prompt.md` +- Modify: `skills/requesting-code-review/code-reviewer.md` + +**Interfaces:** +- Consumes: Task 1's implementer-prompt contract (same intent, reviewer flavor). +- Produces: commit `fix(sdd): reviewers never dispatch subagents either` — joins the T1 PR with Task 1's commit. + +- [ ] **Step 1: Insert the reviewer-flavor section into both SDD reviewer templates** + +In `skills/subagent-driven-development/task-reviewer-prompt.md`, immediately after the paragraph ending `Do not mutate the working + tree, the index, HEAD, or branch state in any way.` and before ` ## Do Not Trust the Report`, insert (4-space body indent): + +``` + ## You Do Not Dispatch Subagents + + Do all of this review yourself. Never spawn a subagent to review part + of the diff, and never spawn another reviewer for a second opinion. + This process already provides every review seat the work gets; a + reviewer you spawn duplicates one of them at full cost, and its + verdict counts for nothing. If the diff feels too large for one + pass, review it in passes yourself and say so in your report. +``` + +In `skills/subagent-driven-development/re-review-prompt.md`, insert the SAME block immediately after the identical read-only paragraph and before ` ## Scope`. + +- [ ] **Step 2: Insert into code-reviewer.md** + +In `skills/requesting-code-review/code-reviewer.md`, immediately after the `## Read-Only Review` section's paragraph and before ` ## What to Check`, insert the SAME block (matching that template's body indent). + +- [ ] **Step 3: Verify** + +`grep -c "You Do Not Dispatch Subagents" skills/subagent-driven-development/task-reviewer-prompt.md skills/subagent-driven-development/re-review-prompt.md skills/requesting-code-review/code-reviewer.md` → each file reports `1`. + +- [ ] **Step 4: Commit** + +```bash +git add skills/subagent-driven-development/task-reviewer-prompt.md skills/subagent-driven-development/re-review-prompt.md skills/requesting-code-review/code-reviewer.md +git commit -m "fix(sdd): reviewers never dispatch subagents either + +The first fix-cycle battery moved the depth-2 leak from implementers +(9/9 baseline -> 0/6) to a final reviewer that spawned two +sub-reviewers; the contract now reaches every dispatched role." +``` + +### Task 16: T2-strong — wait discipline in the SDD controller text + +**Files:** +- Modify: `skills/subagent-driven-development/SKILL.md` + +**Interfaces:** +- Consumes: nothing new. +- Produces: commit `fix(sdd): controllers wait long or not at all` — joins the T2 PR. + +- [ ] **Step 1: Insert the wait-discipline paragraph** + +In `skills/subagent-driven-development/SKILL.md`, in `## The Task Loop`, immediately after the paragraph ending `Hand artifacts over as files.` insert: + +``` +**Waiting on dispatched subagents:** never poll a wait interface with +short timeouts. While you have local work — ledger updates, packaging +the next review, reading reports — keep working; child results arrive +on their own. Wait only when you are genuinely idle, and then issue one +long wait (fifteen minutes or more, where your platform allows it) +instead of many short ones: a long wait wakes just as fast and costs +one call instead of dozens. +``` + +- [ ] **Step 2: Verify** + +`grep -c "Waiting on dispatched subagents" skills/subagent-driven-development/SKILL.md` → `1`. + +- [ ] **Step 3: Commit** + +```bash +git add skills/subagent-driven-development/SKILL.md +git commit -m "fix(sdd): controllers wait long or not at all + +Docs-only wait guidance in the platform reference changed nothing +(65.1% vs 67.1% baseline wait-timeout rate); the discipline now lives +in the controller loop the session actually re-reads." +``` + +### Task 8b: re-run the shared SDD battery + +Repeat Task 8 exactly (same scenario, criteria, scorers, n=8, both lanes) +against a refreshed `/tmp/sp-arm-fix` containing Tasks 15-16. New +pre-registration entry required (new arm SHA). Blocked until Docker is +restored. The Task 8 n=6 battery remains in the log as the round-1 +result; 8b's entries are additions, not corrections. + +--- + +## Amendment 2 (2026-07-30, after battery round 2 and the ceremony battery) + +Round-2 findings driving this amendment: (a) T2's long-wait fix eliminated +wait timeouts (65.1%→0.0%) but produced 20-38 min silent transcripts that +starve graders/humans and let one child in 51 vanish unnoticed — Jesse +chose bounded waits + reconcile; (b) T4's bounded path killed the doc +ritual (0 docs vs 2/rep dev baseline) but 2/3 bounded reps implemented +BEFORE any approval — the router's approval invariant needs teeth (this +enforces the variant-C invariant Jesse selected, so it proceeds without a +new design decision). + +### Task 17: T2 round 3 — bounded waits + reconcile + +**Files:** +- Modify: `skills/subagent-driven-development/SKILL.md` (replace Task 16's paragraph) +- Modify: `skills/using-superpowers/references/codex-tools.md` (revise two bullets of `## Waiting on children`) + +- [ ] **Step 1: Replace the SKILL.md wait paragraph** + +Replace the entire paragraph beginning `**Waiting on dispatched subagents:**` (Task 16's insertion) with: + +``` +**Waiting on dispatched subagents:** never poll a wait interface with +short timeouts, and never sit in one silent, open-ended wait either. +While you have local work — ledger updates, packaging the next review, +reading reports — keep working; child results arrive on their own. +When you are genuinely idle, wait in bounded stretches (five to ten +minutes, where your platform allows), and between stretches post one +line of status and reconcile your live children: list them, and chase +any that finished without reporting. A bounded stretch keeps nearly +all of a long wait's efficiency while guaranteeing a stuck or lost +child is noticed within minutes, not at the end of the session. +``` + +- [ ] **Step 2: Revise codex-tools.md's waiting bullets** + +In `## Waiting on children`, replace the second bullet (`- When you are genuinely idle with children outstanding, issue ONE ... let the event wake you.`) with: + +``` +- When you are genuinely idle with children outstanding, wait in + bounded stretches: `wait_agent` with `timeout_ms` 300000-600000 + (5-10 minutes). After each stretch — wake or timeout — post one + status line, run `list_agents`, and chase any child that finished + without reporting. Never stack polls shorter than five minutes; the + event subscription wakes a bounded stretch just as fast as a short + one. +``` + +and replace the third bullet (`- Completion mail cannot wake an idle controller ... do not fall back to short polls.`) with: + +``` +- Completion mail cannot wake an idle controller (it is delivered + without triggering a turn); covering that idle window is + `wait_agent`'s only job. A stretch that times out with no activity + is your cue to reconcile, not to shorten the next stretch. +``` + +- [ ] **Step 3: Verify** — `grep -c "bounded stretches" skills/subagent-driven-development/SKILL.md skills/using-superpowers/references/codex-tools.md` → 1 and 1; `grep -c "900000" skills/using-superpowers/references/codex-tools.md` → 0. + +- [ ] **Step 4: Commit** + +```bash +git add skills/subagent-driven-development/SKILL.md skills/using-superpowers/references/codex-tools.md +git commit -m "fix(sdd,codex): bounded wait stretches with reconciliation + +Round 2 proved the long-wait mechanism (65.1%->0.0% timeouts) but +20-38 min silent waits starved graders and let 1/51 children vanish; +bounded 5-10 min stretches with a status line and list_agents +reconcile keep the efficiency and restore observability." +``` + +### Task 18: T4 round 2 — approval-gate teeth on the bounded path + +**Files:** +- Modify: `skills/brainstorming/SKILL.md` + +- [ ] **Step 1: Strengthen the bounded bullet in `## Three Paths`** + +Replace the sentence `Ask the clarifying + questions that matter, present a short design IN CHAT (a few + sentences to a few short paragraphs), and get approval. No spec + file, no implementation plan document.` with: + +``` +Ask the clarifying + questions that matter, present a short design IN CHAT (a few + sentences to a few short paragraphs), and STOP. Implementation + starts only after your human partner says yes to that design — a + bounded task's approval is as hard a gate as an architectural + one. No spec file, no implementation plan document. +``` + +- [ ] **Step 2: Strengthen Bounded checklist item 4** + +Replace `4. **Get approval** — explicit, before any implementation` with: + +``` +4. **Get approval** — STOP and wait for an explicit yes; presenting the design and starting in the same breath is skipping the gate +``` + +- [ ] **Step 3: Add a Red Flags row** + +After the row `| "I'll call it bounded and skip the spec" | ... |` add: + +``` +| "It's bounded and the design is obvious — I'll start while they read it" | The gate is the approval, not the design's length. Present, then stop until you hear yes. | +``` + +- [ ] **Step 4: Verify** — `grep -c "as hard a gate" skills/brainstorming/SKILL.md` → 1; `grep -c "start while they read it" skills/brainstorming/SKILL.md` → 1; frontmatter untouched (`git diff HEAD -- skills/brainstorming/SKILL.md` shows no frontmatter hunk after the edit vs prior commit). + +- [ ] **Step 5: Commit** + +```bash +git add skills/brainstorming/SKILL.md +git commit -m "fix(brainstorming): bounded-path approval is a hard stop + +Live ceremony battery: bounded reps produced zero doc ritual (the +measured win) but 2/3 implemented before any approval turn; the +bounded path now states the stop explicitly." +``` + +### Task 8c: shared SDD battery round 3 + +Repeat Task 8b (new pre-registration, refreshed arm, n=8, same criteria) +after Tasks 17-18. T2's clause under test: no completion loss AND +timeout rate < 25%, now with bounded stretches. T1/T5 re-verified as +regression guards on the same runs. + +### Task 9b: ceremony battery round 2 (bounded focus) + +After Tasks 17-18 and arm refresh: bounded 3 reps + arch 3 reps + spike +1 smoke rep (spike text untouched; the shared Red Flags row is the only +common edit). Criteria: bounded — 0 ceremony docs AND strict +pre-implementation approval 3/3; arch — two-doc flow 3/3 with +completion (pre-register a quorum_max_time bump for the arch scenario, +disclosed as a scenario-budget accommodation mirroring the round-2 +silent-wait finding, not a treatment change); spike — smoke healthy. + +--- + +## Amendment 3 (2026-07-30, Jesse: prefer non-blocking subscriptions) + +### Task 19: wait guidance — non-blocking delivery preferred + +**Files:** +- Modify: `skills/subagent-driven-development/SKILL.md` (one sentence added inside the wait paragraph) + +- [ ] **Step 1: Insert the preference sentence** + +In the `**Waiting on dispatched subagents:**` paragraph, immediately after the sentence ending `child results arrive +on their own.` insert: + +``` +Prefer non-blocking delivery wherever your platform offers it — +completion notifications, results pushed into your next turn — and +treat blocking waits as the fallback for platforms (or idle moments) +that cannot wake you otherwise. +``` + +(The following sentence `When you are genuinely idle, wait in bounded +stretches...` continues the paragraph unchanged.) + +- [ ] **Step 2: Verify** — `grep -c "non-blocking delivery" skills/subagent-driven-development/SKILL.md` → 1. + +- [ ] **Step 3: Commit** + +```bash +git add skills/subagent-driven-development/SKILL.md +git commit -m "fix(sdd): prefer non-blocking child-result delivery over any wait + +Blocking waits are the fallback for platforms that cannot wake an +idle controller, not the default; harnesses with completion +notifications never need to block at all." +``` + +Grading note (pre-registered here): no codex behavioral delta is +expected — codex V2 cannot wake an idle controller, so the preference +ladder collapses to the already-graded bounded-stretch text there; the +sentence is additive for notification-capable harnesses. Round 3 +grades 6faceb2; the T2 PR discloses this post-battery clarification +explicitly. + +--- + +## Amendment 4 (2026-07-31, after the triggering check) + +Task 12 findings: gemini routes a new project architectural 3/3; claude +triggers brainstorming 3/3 but self-classifies the new project "bounded" +3/3 through the bounded bullet's "existing, understood flow" wording +("understood" read as familiarity with the app genre, not presence of +code in the repo); codex leg blocked on exhausted subscription credits. +Jesse's rulings: tighten the bounded wording and re-run; he will +provision an OPENAI_API_KEY so the codex leg can run before the T4 PR. + +### Task 20: router tightening — bounded measures the repo + +**Files:** +- Modify: `skills/brainstorming/SKILL.md` + +- [ ] **Step 1: Tighten the bounded bullet's definition** + +In `## Three Paths`, replace the bounded bullet's opening `- **Bounded** — a well-scoped change to an existing, understood flow: a + new flag, a small endpoint, a one-file fix.` with: + +``` +- **Bounded** — a well-scoped change to code that already exists in + this repo: a new flag, a small endpoint, a one-file fix. + Understanding the kind of app is not enough — bounded means the flow + you are changing is already here to read. If there is no existing + flow to change, the task is not bounded. +``` + +(The rest of the bullet — `Ask the clarifying questions that matter...` — continues unchanged.) + +- [ ] **Step 2: Add the familiarity Red Flags row** + +After the row `| "It's bounded and the design is obvious — I'll start while they read it" | ... |` add: + +``` +| "I understand this kind of app, so it's bounded" | Bounded measures the repo, not your familiarity. A new project has no existing flow — it is architectural. | +``` + +- [ ] **Step 3: Verify** — `grep -c "already here to read" skills/brainstorming/SKILL.md` → 1; `grep -c "measures the repo" skills/brainstorming/SKILL.md` → 1; frontmatter untouched. + +- [ ] **Step 4: Commit** + +```bash +git add skills/brainstorming/SKILL.md +git commit -m "fix(brainstorming): bounded means existing code in this repo, not a familiar app genre + +Triggering battery: Claude Code classified a brand-new project bounded +3/3 by reading 'existing, understood flow' as genre familiarity — once +while explicitly noting the repo was empty. Gemini routed the same +prompt architectural 3/3." +``` + +### Task 12b: triggering re-run (claude + gemini) and codex leg + +After Task 20 and arm refresh: claude 3 reps + gemini 1 smoke rep on +`triggering-react-todo`; criteria: claude — brainstorming loads before +implementation AND architectural classification 3/3; gemini smoke stays +architectural. New pre-registration; same detection and hand-verification +method as Task 12. The codex leg (3 reps, same criteria) runs once +Jesse's OPENAI_API_KEY lands: add a `codex_api` credential entry to the +evals `credentials.yaml` (api_key_env: OPENAI_API_KEY, harnesses: +[codex]) if the codex adapter supports API-key auth — verify the +adapter's auth modes first; if it is subscription-only, report BLOCKED +with specifics instead of forcing it. diff --git a/docs/superpowers/specs/2026-07-30-codex-efficiency-fixes-design.md b/docs/superpowers/specs/2026-07-30-codex-efficiency-fixes-design.md new file mode 100644 index 000000000..5bb1307d9 --- /dev/null +++ b/docs/superpowers/specs/2026-07-30-codex-efficiency-fixes-design.md @@ -0,0 +1,252 @@ +# Codex Efficiency Fixes — Design + +Date: 2026-07-30 +Status: approved by Jesse (in-session) +Branch: `codex-efficiency-fixes` off `dev` + +## Sources + +- Eval campaign closeout: `superpowers-autoresearch/reports/2026-07-codex-efficiency-campaign.md` + (treatment table §4; every treatment below has a scorer and a measured + `dev` baseline). +- Codex source recon: `superpowers-autoresearch/docs/2026-07-29-codex-multiagent-v2-capabilities.md` + (file:line citations against the Codex CLI source; grounds T2, T3, T5). +- Published experiment write-ups: `superpowers-evals/docs/experiments/`. +- Drew's spinout stack (PRs #2036, #2035) is **evidence, not adopted text**: + Jesse wants to dig into those fixes in more detail before adopting any + of them; they inform the problem statements only. + +## Goal + +Ship the five evidence-strong treatments from the codex-efficiency eval +campaign as superpowers skill/doc changes, each graded against its +pre-registered criterion by the campaign's scorers before its PR is cut. +Phase 2 (everything else in the closeout treatment table) follows, each +item gated on new baseline work first. + +## Scope decisions (settled with Jesse) + +- **Phase 1 = the evidence-strong five** (T1–T5 below). Phase 2 items + each need a failing baseline before any fix ships (discrimination + rule: inconclusive-by-zero is a stop). +- **One branch, PR per treatment.** Development and batteries happen on + `codex-efficiency-fixes`; when a treatment beats its criterion, it is + cut into its own PR against `dev` with its eval evidence. No merge + without Jesse's per-PR approval. +- **T4 ships cross-harness with a global regression battery** (Claude + Code, Codex, Gemini), variant C shape: ceremony scales, approval never + does. + +## The five treatments + +### T1. SDD worker-review prohibition + +**Evidence:** 9/9 depth-2 spawns across 4 corpora were implementer-issued +reviewers; all 9 were same-task duplicates of the review the controller +dispatches anyway. The dispatch contract never says review is not the +worker's job; "self-review" in the implementer prompt gets reified into a +reviewer subagent on harnesses where children can spawn (Codex). + +**Changes:** +- `skills/subagent-driven-development/implementer-prompt.md`: an explicit + "You do not dispatch subagents" clause — self-review means reading your + own diff; the controller owns all review dispatch; a reviewer you spawn + duplicates a review the process already provides. +- `skills/subagent-driven-development/SKILL.md`: one dispatch-contract + line in the task loop, plus a Red Flags row: "An independent review + would strengthen my report" → review is the controller's next step; + your reviewer is a duplicate seat. +- Harness-agnostic wording (no-op where children cannot spawn). + +**Graded by:** `score_e6.py` (depth-2 spawns by spawner role, duplicate +review families); `score_e5.py` for the same-scope variant. +**Baseline:** 9/9 worker-issued, 0 counter-examples. +**Criterion:** 0 worker-issued depth-2 spawns AND review coverage +preserved (every task still gets exactly one controller-dispatched task +review). + +### T2. Event-driven waiting + +**Evidence:** 60–78% of `wait_agent` calls time out in every corpus +(dev 67.1%, spinout 60.2%). Source recon: V2 waits are event +subscriptions, not polls — one long wait has the same wake latency as a +10s poll at ~1/90th the calls; a completed child's FINAL_ANSWER is pushed +into the parent's mailbox and drained into the next model request with no +wait at all. + +**Changes** (`skills/using-superpowers/references/codex-tools.md`): +- Never short-timeout poll. +- While local work remains, do not wait — child results arrive with your + next turn via the mailbox. +- When genuinely idle, issue ONE `wait_agent` with a long `timeout_ms` + (900000+; harness max 3600000). +- V2 caveat stated: completion mail carries `trigger_turn=false` and will + not wake an idle controller — that is the one job `wait_agent` has. + +**Graded by:** `score_e7.py` (timeout rate, inter-poll cadence, +cache-rebill estimate — the rebill figure stays labeled as an estimate). +**Baseline:** dev 67.1% timeout rate. +**Criterion:** timeout rate < 25% with no loss of task completion. + +### T3. codex-tools.md corrections + +**Evidence:** five claims in the current guidance are contradicted by the +Codex source (all file:line-cited in the capabilities doc): +1. `close_agent` does not exist in multi-agent V2 (V1-only). V2 LRU-evicts + finished children automatically; not closing costs nothing; + `followup_task` transparently reloads an evicted child. +2. Fix rounds can always resume the implementer via `followup_task` — + dev's "if your harness cannot send another message to a spawned agent, + dispatch each fix round as a fresh implementer" branch is dead on V2. +3. Role files (`~/.codex/agents/**.toml`) DO attach to spawns via + `agent_type` on isolated forks (0.145+). +4. Full-history forks accept `model`/`reasoning_effort` overrides; only + `agent_type` is refused. (Isolated forks remain the SDD guidance for + context-hygiene reasons, stated accurately.) +5. Dispatch guidance must never name non-V2 model presets — the V2 spawn + allowlist is v2 presets only; others hard-error. + +**Changes:** rewrite the multi-agent paragraph of +`skills/using-superpowers/references/codex-tools.md` to be +version-honest (V1 vs V2 behavior labeled where they differ). + +**Graded by:** source citation (already verified); no scorer regressions +on the shared battery. `score_e8.py` is retained as a V1/V2 schema +detector, not a hygiene grader — no `close_agent` checklist ships. + +### T4. Brainstorming three-path router (variant C: approval always) + +**Evidence:** micro — the current HARD-GATE text pushes a bounded task to +FULL ceremony 5/5, while Z-null (no guidance) and a three-path router +both differentiate 5/5: the absolute wording suppresses discrimination +the model draws natively. FULL battery — ceremony volume scales +moderately (16.7 vs 24.0 tool calls, bounded vs arch), but the +two-document ritual (spec file → plan file) ran unconditionally in every +rep. The measured waste is the unconditional artifact ritual, not the +approval gate. + +**Design (variant C):** three paths scale the ARTIFACT; every path keeps +human approval before implementation: +- **Spike** (feasibility question, explicitly throwaway): present the + question and the intended probe in 2–3 sentences, get a nod, go. No + docs. Findings return as a recommendation; anything built stays labeled + throwaway. +- **Bounded** (well-scoped change to an existing, understood flow): + present a short design in chat, get approval, implement. No spec file, + no writing-plans invocation. +- **Architectural** (restructures components, new subsystem, public + interface change): the full current flow — spec doc, review, + writing-plans. + +**Guards (all ship with the router):** +- Classification is said out loud ("this looks bounded, so I'll present a + short design here rather than write a spec") so the human can override. +- When in doubt between two paths, take the heavier one. +- One-way ratchet: hidden complexity discovered mid-path upgrades the + path; never downgrade mid-task. +- New Red Flags rows targeting classification-as-escape-hatch ("I'll call + it bounded to skip the doc"). + +**Changes** (`skills/brainstorming/SKILL.md`): HARD-GATE keeps "no +implementation before approval" and drops "regardless of perceived +simplicity" as the ceremony driver; anti-pattern section reframed (the +sin is skipping approval, not skipping documents); checklist steps 6–9 +become the architectural path; process-flow graph gains the router; Red +Flags rows added. This is carefully-tuned content — the edit follows +writing-skills methodology and ships only with the full eval evidence +below. + +**Graded by (three layers):** +1. **Micro** (`ceremony-path-micro.py`, adapted): variant C literal text, + plus adversarially ambiguous briefs the campaign never tested (a task + that pattern-matches bounded but hides a public interface change). + Criteria: spike/bounded/arch differentiate (≥4/5 per cell); ambiguous + briefs escalate to FULL (≥4/5); arch never downgrades (5/5). +2. **Codex ceremony battery:** `cx-ceremony-{spike,bounded,arch}` on the + fix arm, 3 reps each, `score_e4.py` census. Criteria: bounded reps + show an approval turn but zero committed spec files and zero + writing-plans ritual; arch reps keep the full two-doc flow; spike reps + stay minimal. +3. **Global regression battery:** the same three ceremony scenarios on + Claude Code and Gemini (rig work: those scenarios are currently + codex-gated), 3 reps each; plus the triggering acceptance check + ("Let's make a react todo list" auto-triggers brainstorming into the + full/architectural path) on all three harnesses. + +### T5. Explicit model on child-issued spawns + +**Evidence:** root spawns are 100% explicit-model at CLI 0.146 (dev +14/14); the live gap is depth-2 — 2/2 child-issued spawns omitted +`model`. Source recon: `model` without `reasoning_effort` resets effort +to the MODEL's default, not the parent's. + +**Changes** (`skills/using-superpowers/references/codex-tools.md`): +- Every spawn you issue — including as a child — sets `model` AND + `reasoning_effort`; the effort-reset trap is named. +- Advise `[agents].default_subagent_model` and + `[agents].default_subagent_reasoning_effort` in `~/.codex/config.toml` + as the machine-level backstop for anything that slips through. + +**Graded by:** `score_e1.py` (per-spawn explicit-model rate, by depth) on +the shared battery. +**Baseline:** depth-2: 0/2 explicit. +**Criterion:** every spawn at every depth carries explicit model + +effort. Pre-registered caveat: if T1 eliminates depth-2 spawns entirely, +T5 grades as root-spawn regression (hold 100%) plus doc correctness and +is recorded inconclusive-by-zero at depth-2 — the config backstop is then +the operative mechanism. + +## Grading plan + +- **Shared SDD battery** carries T1, T2, T5: `cx-sdd-small`, fix-branch + arm (`/tmp/sp-arm-fix`), 8 reps across both container lanes. Dev + baselines are already measured; no baseline re-runs. +- **T4 batteries** as listed above (micro + codex ceremony + global + regression). +- **Pre-registration:** every battery gets a hypothesis-log entry + (prediction, scorer, criterion) in + `superpowers-autoresearch/logs/2026-07-30-codex-efficiency-fixes.md` + BEFORE it runs. Standing rules carry over: append-only log, manual + inspection of scorer matches on fix-arm runs (non-circular + verification), no raw rollouts committed, correctness rides beside + cost in every verdict. +- **Attribution:** orthogonal scorers on one combined branch; unexpected + regressions bisect by treatment commit. +- **Budget:** shared battery ~$40, codex ceremony ~$40, global + regression ~$40–80, micros ~$5 → phase 1 ≈ $150–200 of the ~$850 + remaining from the campaign's $1000. + +## Process + +- Work happens in the `codex-efficiency-fixes` worktree (branched off + `dev`); execution via subagent-driven-development from a written plan. +- Skill-text changes follow writing-skills methodology. +- Scenario/rig changes (un-gating ceremony scenarios for Claude + Code/Gemini, adversarial micro briefs) land in `superpowers-evals` + main, as authorized. +- PR-per-treatment against `dev`, each with its eval evidence and the + standard identification block; merges only on Jesse's per-PR approval. + +## Phase 2 queue (baseline-first; not in this plan's tasks) + +Each item requires a failing baseline before any fix ships: +1. **Dispatch routing / long-session drift** — needs a long-session + elicitation rig (fresh sessions don't reproduce the pathology at CLI + 0.146). Drew's stack informs the treatment shape. +2. **Verification leases / evidence receipts** — needs the + substring-aware duplicate counter added to `score_e3.py` first + (current baseline 1/23 exact-string pairs is too weak). +3. **Remediation cap** — small-n baseline (2/3 reps) needs more reps. +4. **Cross-task-race probe redesign** — `score_e5.py`'s probe is + inconclusive-by-zero by design tradeoff; needs a stronger probe. +5. **E5 D4 shell-command parser** — fix-review-scope classifier cannot + parse compound commands; scorer work, not skill work. + +## Out of scope + +- Adopting Drew's spinout stack (#2036/#2035) or its text. +- RoboRev, Codex token telemetry (separate codebases). +- A `close_agent` hygiene checklist (V2 has no such tool — closed as + do-not-ship in the campaign). +- Claude Code/Gemini-specific efficiency treatments beyond the T4 + regression battery. From 39f9602432c8115f1673e01e16cf2e79ea16bf12 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 2 Aug 2026 11:14:01 -0700 Subject: [PATCH 079/198] =?UTF-8?q?fix(sdd):=20rule=20and=20continue=20?= =?UTF-8?q?=E2=80=94=20non-catastrophic=20conflicts=20get=20ledgered=20rul?= =?UTF-8?q?ings,=20not=20blocking=20questions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A donated session sat dormant 8h48m waiting for a plan-conflict answer that cost ~zero tokens to decide. Wrong-ruling rework is bounded; stalls are not. This encodes the never-stall doctrine: plan conflicts, ambiguities, and cap exceptions get a controller ruling recorded in the ledger and work proceeds; only irreversible/destructive actions, security-sensitive actions, out-of-worktree side effects (merge/push/ publish), and totally-broken plans remain hard stops. Rulings surface in the Finish report instead of as mid-run questions. Evals: 3/3 no-stall vs control 3/3 stall-at-preflight on a seeded-conflict SDD plan; catastrophic guard 5/5 (every rep reaching a seeded DROP TABLE step refused it); re-validated 3/3 after rebase onto the current fix-PR text; composes cleanly with the evidence-bearing preflight treatment. Claude-Session: https://claude.ai/code/session_0185AJr98gHx5EmwqNeft4Sy --- skills/subagent-driven-development/SKILL.md | 61 ++++++++++++++------- 1 file changed, 42 insertions(+), 19 deletions(-) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index 6c0b8349d..341693503 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -14,7 +14,21 @@ Execute plan by dispatching a fresh implementer subagent per task, a task review **Narration:** between tool calls, narrate at most one short line — the ledger and the tool results carry the record. -**Continuous execution:** Do not pause to check in with your human partner 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. +**Continuous execution:** Do not pause to check in with your human partner between tasks. Execute all tasks from the plan without stopping. The only reasons to stop are the four named below, or all tasks complete. "Should I continue?" prompts and progress summaries waste their time — they asked you to execute the plan, so execute it. + +**Rulings, not stalls.** A running plan does not wait on a human. Conflicts, +ambiguities, plan defects, a cap you would have asked to exceed — decide +them. The spec is the binding authority, the plan is its argument, and your +judgment settles what neither answers. Record every decision in the ledger as +`Ruling: — — `, and keep +going. A wrong ruling costs rework your human partner can see and undo; a +session parked on a question costs their whole day and buys nothing. + +Four things stop you, and only these: an irreversible or destructive +operation; a security-sensitive action; a side effect outside this worktree +that norms say you ask about first (a merge, a push to a shared branch, a +publish); and a plan so broken that every path forward is a guess. For those, +stop and ask. ## When to Use @@ -57,14 +71,14 @@ digraph process { "Generate review package, dispatch task reviewer (./task-reviewer-prompt.md)" [shape=box]; "Spec ✅ and quality approved?" [shape=diamond]; "Finding conflicts with plan text?" [shape=diamond]; - "Ask human partner which governs" [shape=box]; + "Rule on the conflict, ledger the ruling" [shape=box]; "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [shape=box]; "Dispatch scoped re-review (./re-review-prompt.md)" [shape=box]; "All findings addressed?" [shape=diamond]; "R = 5?" [shape=diamond]; "Adjudicate each open finding" [shape=box]; "Any load-bearing finding?" [shape=diamond]; - "STOP: report BLOCKED to human partner" [shape=box]; + "Rule and continue; stop only if every path forward is a guess" [shape=box]; "Park findings in ledger with rulings" [shape=box]; "Append completion to ledger, mark todo complete" [shape=box]; } @@ -85,8 +99,8 @@ digraph process { "Generate review package, dispatch task reviewer (./task-reviewer-prompt.md)" -> "Spec ✅ and quality approved?"; "Spec ✅ and quality approved?" -> "Append completion to ledger, mark todo complete" [label="yes"]; "Spec ✅ and quality approved?" -> "Finding conflicts with plan text?" [label="no"]; - "Finding conflicts with plan text?" -> "Ask human partner which governs" [label="yes"]; - "Ask human partner which governs" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model"; + "Finding conflicts with plan text?" -> "Rule on the conflict, ledger the ruling" [label="yes"]; + "Rule on the conflict, ledger the ruling" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model"; "Finding conflicts with plan text?" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [label="no"]; "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" -> "Dispatch scoped re-review (./re-review-prompt.md)"; "Dispatch scoped re-review (./re-review-prompt.md)" -> "All findings addressed?"; @@ -95,7 +109,7 @@ digraph process { "R = 5?" -> "Fix round R of 5: R≤3 resume implementer; R≥4 fresh implementer, more capable model" [label="no - next round"]; "R = 5?" -> "Adjudicate each open finding" [label="yes - breaker trips"]; "Adjudicate each open finding" -> "Any load-bearing finding?"; - "Any load-bearing finding?" -> "STOP: report BLOCKED to human partner" [label="yes"]; + "Any load-bearing finding?" -> "Rule and continue; stop only if every path forward is a guess" [label="yes"]; "Any load-bearing finding?" -> "Park findings in ledger with rulings" [label="no"]; "Park findings in ledger with rulings" -> "Append completion to ledger, mark todo complete"; "Append completion to ledger, mark todo complete" -> "More tasks remain?"; @@ -148,9 +162,8 @@ Before dispatching Task 1, scan the plan once for conflicts: - anything the plan explicitly mandates that the review rubric treats as a defect (a test that asserts nothing, verbatim duplication of a logic block) -Present everything you find to your human partner as one batched question — -each finding beside the plan text that mandates it, asking which governs — -before execution begins, not one interrupt per discovery mid-plan. If the +Rule on everything you find before execution begins — each finding against +the plan text that mandates it — and record each ruling in the ledger. If the scan is clean, proceed without comment. The review loop remains the net for conflicts that only emerge from implementation. @@ -245,7 +258,7 @@ Implementer subagents report one of four statuses. Handle each appropriately: 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 +4. If the plan itself is wrong, rule on the correction, ledger it, and re-dispatch with the ruling carried in the dispatch **Never** ignore an escalation or force the same model to retry without changes. If the implementer said it's stuck, something needs to change. @@ -312,10 +325,11 @@ Before the loop starts, two routes leave it immediately: before merge. A roll-up nobody reads is a silent discard. Minor findings never enter the loop. - A finding labeled plan-mandated — or any finding that conflicts with - what the plan's text requires — is the human's decision, like any plan - contradiction: present the finding and the plan text, ask which governs. - Do not dismiss the finding because the plan mandates it, and do not - dispatch a fix that contradicts the plan without asking. + what the plan's text requires — is yours to rule on: weigh the finding + against the plan text, decide with the spec as the binding authority, and + ledger the ruling before you act on it. Do not dismiss the finding because + the plan mandates it, and do not dispatch a fix that contradicts the plan + without a recorded ruling. Everything else enters the loop. A fix round is one fix dispatch plus one scoped re-review. Five rounds maximum per task: @@ -365,10 +379,11 @@ the cross-task context the reviewer lacks: - **Real, but nothing downstream builds on it:** park it the same way, with a ruling that says it's real and deferred. - **Real and load-bearing** — a later task builds on it, or it reveals a - plan defect: STOP. Append `Task : BLOCKED — ` and report to - your human partner with the finding, the plan text it collides with, and - the fix history. Parking a structural failure lets every dependent task - build on it and hands the final review a problem it cannot fix either. + plan defect: rule on the smallest change that unblocks the dependent work, + ledger it as `Task : ruling — — `, + and carry it into the next task's dispatch. Parking a structural failure + silently lets every dependent task build on it. Stop only when the defect + leaves every path forward a guess. Adjudicate only at the cap. Adjudicating earlier to end a loop is pre-judging with a different name. Every adjudication is a ledger entry — @@ -409,12 +424,20 @@ Then run exactly one scoped re-review of the fix wave (`scripts/review-package PLAN_FILE FIX_BASE HEAD` over the fix range, [re-review-prompt.md](re-review-prompt.md)). Adjudicate any residual findings as in the task loop's breaker: park with -rulings, or stop on load-bearing ones. There is no second fix wave — +rulings, or rule on the load-bearing ones and ledger what you decided. Only +the four classes above stop you here. There is no second fix wave — residual load-bearing findings surface to your human partner when finishing-a-development-branch presents the options. ## Finish +Before you delete anything, collect every `Ruling:` line from the ledger into +your final message under "Rulings I made", in the order you made them, each +with what it costs if wrong. That list is the only place the decisions you +took on your human partner's behalf reach them — they read it and rework +whatever you got wrong. A ruling that dies with the workspace was a decision +made in secret. + When the final whole-branch review is clean and its fixes are merged, delete this plan's workspace (`rm -rf `) — the git history is the record now. Sibling directories belong to other plans; leave them From e7a42859859c23307ae221857822da483936ad9d Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 2 Aug 2026 19:36:55 -0700 Subject: [PATCH 080/198] fix(sdd): batch small same-shape tasks into one dispatch Plans sometimes enumerate many tiny, same-shape edits (one-line fixes, constant changes, a field added across files) as separate tasks. The current loop dispatches a fresh implementer plus review per task, so a 12-micro-task plan costs ~24 subagent seats for what one subagent could do in a single pass. In controlled evals on a micro-task plan, batching cut cost 73% and dispatches 87% with better completion than control; on a 5-non-trivial-task plan the rule correctly never batched (dispatch counts and completion identical to control). Claude-Session: https://claude.ai/code/session_0185AJr98gHx5EmwqNeft4Sy --- skills/subagent-driven-development/SKILL.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index 6c0b8349d..2659f4a88 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -193,6 +193,14 @@ that implementer. Single-file mechanical fixes also take the cheapest tier. ## The Task Loop +**Batch small same-shape work.** When the plan lists several tasks that are +each a small, independent edit of the same kind — the same one-line fix, +constant change, or field addition repeated across files — do not dispatch +one subagent per task. Compose ONE dispatch brief listing every file and +its change, send the whole batch to a single subagent, and review its diff +as one unit. Reserve one-dispatch-per-task for work that needs its own +judgment, its own tests, or its own review surface. + Everything you paste into a dispatch prompt — and everything a subagent prints back — stays resident in your context for the rest of the session and is re-read on every later turn. Hand artifacts over as files. From 61f669ebc93fec2fe32f8bc4089efefd85b5daec Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 3 Aug 2026 09:03:05 -0700 Subject: [PATCH 081/198] fix(sdd): preflight emits its pairwise checks as a ledger table and rules on what it surfaces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pre-Task-1 conflict scan currently permits 'the scan is clean' with no evidence the scan happened — mined sessions show controllers skipping straight to dispatch and plan conflicts surfacing mid-execution as blocking questions. Requiring the scan to emit one row per task pair sharing a file/interface and one row per task's self-consistency turns the claim into an artifact; in controlled evals the table appeared 3/3 with conflicts surfaced pre-dispatch, and the mechanism held 3/3 when composed with the never-stall ruling change (#2077). Claude-Session: https://claude.ai/code/session_0185AJr98gHx5EmwqNeft4Sy --- skills/subagent-driven-development/SKILL.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index 6c0b8349d..aab457b2e 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -142,17 +142,24 @@ a ledger file, not only in todos. Read the plan once, note its context and Global Constraints, and create a todo per task. -Before dispatching Task 1, scan the plan once for conflicts: +Before dispatching Task 1, scan the plan once for conflicts, writing down +what you checked as you check it: - tasks that contradict each other or the plan's Global Constraints - anything the plan explicitly mandates that the review rubric treats as a defect (a test that asserts nothing, verbatim duplication of a logic block) -Present everything you find to your human partner as one batched question — -each finding beside the plan text that mandates it, asking which governs — -before execution begins, not one interrupt per discovery mid-plan. If the -scan is clean, proceed without comment. The review loop remains the net for -conflicts that only emerge from implementation. +The scan's output is a table, not a verdict. One row for every pair of tasks +that share a file or an interface: the two tasks, what one produces against +what the other consumes, and what you found. One row for every task: whether +its own text agrees with itself — the tests it specifies against the code it +specifies, the files it creates against the files it later touches. "The scan +is clean" without those rows is not a scan you ran. + +Write the table to the ledger. Rule on each conflict it surfaces — the spec +is the binding authority, the plan is its argument — record the ruling beside +its row, and dispatch Task 1. The review loop remains the net for conflicts +that only emerge from implementation. ## Model Selection From 538d65120be78ad147fc82ea392da2ed0edc4cdc Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Tue, 4 Aug 2026 11:17:05 -0700 Subject: [PATCH 082/198] =?UTF-8?q?fix(planning):=20the=20spec=20travels?= =?UTF-8?q?=20with=20the=20plan=20=E2=80=94=20Spec:=20header=20pointer=20+?= =?UTF-8?q?=20SDD=20reads=20it=20at=20setup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In controlled evals, an identical seeded-incoherence plan yielded 0-1/5 correct conflict resolutions when executed specless (controllers ruled the conflicts 'internally explained') and 4-5/5 with the spec merely present and named — even with no other skill-text changes. Cross-task coherence turns out to be adjudicable only against ground truth above the plan; this change makes that ground truth travel with the plan. Claude-Session: https://claude.ai/code/session_0185AJr98gHx5EmwqNeft4Sy --- skills/subagent-driven-development/SKILL.md | 5 ++++- skills/writing-plans/SKILL.md | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index 6c0b8349d..be2a44e44 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -140,7 +140,10 @@ a ledger file, not only in todos. that happens, recover from `git log`. Read the plan once, note its context and Global Constraints, and create a -todo per task. +todo per task. If the plan names a Spec, read that too: the spec is the +authority the plan argues from, and conflicts inside the plan resolve +against it. A plan with no reachable spec gets a ledger note saying so — +rulings made without one are provisional. Before dispatching Task 1, scan the plan once for conflicts: diff --git a/skills/writing-plans/SKILL.md b/skills/writing-plans/SKILL.md index dd2702b8b..f74605bfa 100644 --- a/skills/writing-plans/SKILL.md +++ b/skills/writing-plans/SKILL.md @@ -66,6 +66,9 @@ independently testable deliverable. **Tech Stack:** [Key technologies/libraries] +**Spec:** [path to the spec/design doc this plan implements — the plan +argues from the spec, so the spec travels with it; executors read both] + ## Global Constraints [The spec's project-wide requirements — version floors, dependency limits, From 7a01a0e83a2e53d2e5e5b70646a938df688d1cc7 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 4 Aug 2026 14:13:42 -0700 Subject: [PATCH 083/198] fix(sdd): one Ruling: token everywhere, exhaustive finish roll-up The breaker's two ledger formats wrote lowercase 'ruling' (parked findings, load-bearing adjudications), so the Finish section's collect-every-`Ruling:`-line step missed exactly the rulings made under the most pressure. Field evidence from an independent eval rep: a breaker-cap run adjudicated correctly, wrote everything to the plan-scoped ledger, deleted the workspace at finish, and left no durable trace of the adjudication. Capitalize the two breaker formats to the canonical token, and make the finish roll-up explicitly exhaustive across preflight, parked, and breaker rulings. Co-Authored-By: Claude Fable 5 --- skills/subagent-driven-development/SKILL.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index 341693503..a40ffdb64 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -374,13 +374,13 @@ dispatching. Adjudicate each open finding yourself — you hold the plan and the cross-task context the reviewer lacks: - **The reviewer is wrong, or the point is contestable:** park it — - `Task : parked — — ruling: `. The final + `Task : parked — — Ruling: `. The final review sees both sides. - **Real, but nothing downstream builds on it:** park it the same way, with a ruling that says it's real and deferred. - **Real and load-bearing** — a later task builds on it, or it reveals a plan defect: rule on the smallest change that unblocks the dependent work, - ledger it as `Task : ruling — — `, + ledger it as `Task : Ruling: — `, and carry it into the next task's dispatch. Parking a structural failure silently lets every dependent task build on it. Stop only when the defect leaves every path forward a guess. @@ -431,9 +431,11 @@ finishing-a-development-branch presents the options. ## Finish -Before you delete anything, collect every `Ruling:` line from the ledger into +Before you delete anything, collect every ledger line containing `Ruling:` — +preflight rulings, parked findings, breaker adjudications, all of them — into your final message under "Rulings I made", in the order you made them, each -with what it costs if wrong. That list is the only place the decisions you +with what it costs if wrong. The list is exhaustive: if the ledger holds a +ruling, the list holds it. That list is the only place the decisions you took on your human partner's behalf reach them — they read it and rework whatever you got wrong. A ruling that dies with the workspace was a decision made in secret. From 78cc1892442ceb765b38bc7983553b718b6e95c6 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Tue, 4 Aug 2026 14:25:40 -0700 Subject: [PATCH 084/198] fix(sdd): batch reviews check the diff against the brief's file list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Batching moves N edits under one review, which changes the review's failure profile: an implementer that silently skips one file of twelve produces a diff full of correct, uniform edits — nothing conspicuous is missing, and no seat in the pipeline was assigned to notice. The single combined review is the only net for a dropped edit, but the reviewer template never told it to count. The batch brief already lists every file with its change, so the reviewer reconciles the diff against that list file by file; a listed file with no hunk is a Missing finding regardless of how clean the rest of the batch looks. Conditional on a multi-file brief, so single-task reviews are unchanged. Co-Authored-By: Claude Fable 5 --- skills/subagent-driven-development/task-reviewer-prompt.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/skills/subagent-driven-development/task-reviewer-prompt.md b/skills/subagent-driven-development/task-reviewer-prompt.md index fefaea8a7..7134274ca 100644 --- a/skills/subagent-driven-development/task-reviewer-prompt.md +++ b/skills/subagent-driven-development/task-reviewer-prompt.md @@ -86,6 +86,12 @@ Subagent (general-purpose): - **Misunderstood:** right feature built the wrong way, wrong problem solved + If the brief lists several files each with its own change (a batched + dispatch), check the diff against that list file by file: every listed + file must have its corresponding hunk. A listed file the diff never + touches is a Missing finding, no matter how clean the rest of the + batch looks. + If a requirement cannot be verified from this diff alone (it lives in unchanged code or spans tasks), report it as a ⚠️ item instead of broadening your search. From 80b82abd8d5a43f629b9b0ca55336d63f3da5680 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Tue, 4 Aug 2026 18:24:10 -0700 Subject: [PATCH 085/198] fix(sdd): task reviewers re-read illegible evidence instead of re-running to regenerate it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Interrogation of reviewers who bypassed test-evidence leases showed a convergent driver: when the report or receipt looked truncated or couldn't be located, re-running the suite felt cheaper than re-reading — evidence got regenerated instead of read. This paragraph names that moment: re-read at the stated path, report a genuine gap to the controller, and never re-run to regenerate what wasn't read. Battery: 0/31 reviewer re-runs across 4 treatment reps vs 7/~59 reviewers in 5/8 control reps on the same scenario and classifier. Claude-Session: https://claude.ai/code/session_0185AJr98gHx5EmwqNeft4Sy --- skills/subagent-driven-development/task-reviewer-prompt.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/skills/subagent-driven-development/task-reviewer-prompt.md b/skills/subagent-driven-development/task-reviewer-prompt.md index fa910c617..ce7969482 100644 --- a/skills/subagent-driven-development/task-reviewer-prompt.md +++ b/skills/subagent-driven-development/task-reviewer-prompt.md @@ -84,6 +84,13 @@ Subagent (general-purpose): Warnings or other noise in the implementer's reported test output are findings — test output should be pristine. + Evidence you cannot see is not evidence that doesn't exist. If the + report or its test evidence looks truncated, or you cannot locate the + results it claims, re-read the file at its stated path — and if it is + genuinely missing or garbled, report that as a gap for the controller. + Re-running the suite to regenerate what you failed to read is not + verification; illegibility of the evidence is not invalidation of it. + ## Part 1: Spec Compliance Compare the diff against What Was Requested: From fb518edf7b6d636b91709a10a89288e4e2742208 Mon Sep 17 00:00:00 2001 From: Kattni Date: Tue, 4 Aug 2026 21:07:15 -0400 Subject: [PATCH 086/198] Moves Community up, and adds ToC. --- README.md | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 2757b2efb..762bd91a9 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,31 @@ Superpowers is a complete software development methodology for your coding agents, built on top of a set of composable skills and some initial instructions that make sure your agent uses them. +## Table of Contents + +- [Quickstart](#quickstart) +- [How it works](#how-it-works) +- [Commercial Services](#commercial-services) +- [Installation](#installation) + - [Claude Code](#claude-code) + - [Antigravity](#antigravity) + - [Codex App](#codex-app) + - [Codex CLI](#codex-cli) + - [Cursor](#cursor) + - [Factory Droid](#factory-droid) + - [Gemini CLI](#gemini-cli) + - [GitHub Copilot CLI](#github-copilot-cli) + - [Kimi Code](#kimi-code) + - [OpenCode](#opencode) + - [Pi](#pi) +- [The Basic Workflow](#the-basic-workflow) +- [Community](#community) +- [What's Inside](#whats-inside) +- [Philosophy](#philosophy) +- [Contributing](#contributing) +- [Updating](#updating) +- [License](#license) +- [Visual companion telemetry](#visual-companion-telemetry) ## Quickstart @@ -211,6 +236,14 @@ The Pi package loads the Superpowers skills and a small extension that injects t **The agent checks for relevant skills before any task.** Mandatory workflows, not suggestions. +## Community + +Superpowers is built by [Jesse Vincent](https://blog.fsck.com) and the rest of the folks at [Prime Radiant](https://primeradiant.com). + +- **Discord**: [Join us](https://discord.gg/35wsABTejz) for community support, questions, and sharing what you're building with Superpowers +- **Issues**: https://github.com/obra/superpowers/issues +- **Release announcements**: [Sign up](https://primeradiant.com/superpowers/) to get notified about new versions + ## What's Inside ### Skills Library @@ -271,11 +304,3 @@ MIT License - see LICENSE file for details ## Visual companion telemetry Because skills and plugins don't provide any feedback to creators, we have no idea how many of you are using Superpowers. By default, the Prime Radiant logo on brainstorming's optional visual companion feature is loaded from our website. It includes the version of Superpowers in use. It does not include any details about your project, prompt, or coding agent. We don't see your clicks or anything about what you're building. This helps us have a rough idea of how many folks are using Superpowers and which version of Superpowers they're using. It's 100% optional. To disable this, set the environment variable `SUPERPOWERS_DISABLE_TELEMETRY` to any true value. Superpowers also honors Claude Code's `DISABLE_TELEMETRY` and `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` opt-outs. - -## Community - -Superpowers is built by [Jesse Vincent](https://blog.fsck.com) and the rest of the folks at [Prime Radiant](https://primeradiant.com). - -- **Discord**: [Join us](https://discord.gg/35wsABTejz) for community support, questions, and sharing what you're building with Superpowers -- **Issues**: https://github.com/obra/superpowers/issues -- **Release announcements**: [Sign up](https://primeradiant.com/superpowers/) to get notified about new versions From 695744056ed1338404539aba3fbd98928d78005c Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Wed, 5 Aug 2026 17:57:31 -0700 Subject: [PATCH 087/198] chore(hermes): align plugin version with dev Update the Hermes plugin manifest from 6.1.1 to 6.2.0 so PR #2025 matches the current release version at the tip of origin/dev.\n\nThis intentionally does not change the version bump tooling. The existing release script supports JSON manifests only; YAML support will be handled separately on its own branch. --- .hermes-plugin/plugin.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.hermes-plugin/plugin.yaml b/.hermes-plugin/plugin.yaml index c10f9f55c..78f76e8bb 100644 --- a/.hermes-plugin/plugin.yaml +++ b/.hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: superpowers -version: 6.1.1 +version: 6.2.0 description: Superpowers skills and workflow bootstrap for Hermes Agent author: obra provides_hooks: From dcd3661b7c0835dde6d7484dd77cace209083d5b Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 18 Jun 2026 15:15:54 -0700 Subject: [PATCH 088/198] fix(writing-skills): run graphviz without a shell in render-graphs.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `dot` availability check shelled out to `which dot`, which is not a command on Windows, so render-graphs.js reported graphviz as missing on Windows even when it was installed. Replace it with a direct `dot -V` probe via execFileSync. Also switch the SVG render call from execSync to execFileSync('dot', ['-Tsvg']). Behavior is identical on macOS/Linux — the diagram source was already passed via stdin, never interpolated into the command — but running the binary directly removes the shell entirely. --- skills/writing-skills/render-graphs.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/skills/writing-skills/render-graphs.js b/skills/writing-skills/render-graphs.js index 1d670fbb3..14988965b 100755 --- a/skills/writing-skills/render-graphs.js +++ b/skills/writing-skills/render-graphs.js @@ -15,7 +15,7 @@ const fs = require('fs'); const path = require('path'); -const { execSync } = require('child_process'); +const { execFileSync } = require('child_process'); function extractDotBlocks(markdown) { const blocks = []; @@ -69,7 +69,7 @@ ${bodies.join('\n\n')} function renderToSvg(dotContent) { try { - return execSync('dot -Tsvg', { + return execFileSync('dot', ['-Tsvg'], { input: dotContent, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 @@ -107,9 +107,10 @@ function main() { process.exit(1); } - // Check if dot is available + // Check if dot is available. Run the binary directly rather than probing + // with `which`, which is not a command on Windows. try { - execSync('which dot', { encoding: 'utf-8' }); + execFileSync('dot', ['-V'], { stdio: 'ignore' }); } catch { console.error('Error: graphviz (dot) not found. Install with:'); console.error(' brew install graphviz # macOS'); From 02654f93bf723eb1e3c8c4c6e74bd338f990b1c2 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Thu, 2 Jul 2026 14:09:14 -0700 Subject: [PATCH 089/198] test(writing-skills): cover render-graphs execution --- skills/writing-skills/render-graphs.js | 6 +- tests/writing-skills/test-render-graphs.sh | 113 +++++++++++++++++++++ 2 files changed, 116 insertions(+), 3 deletions(-) create mode 100755 tests/writing-skills/test-render-graphs.sh diff --git a/skills/writing-skills/render-graphs.js b/skills/writing-skills/render-graphs.js index 14988965b..59e74b54e 100755 --- a/skills/writing-skills/render-graphs.js +++ b/skills/writing-skills/render-graphs.js @@ -13,9 +13,9 @@ * Requires: graphviz (dot) installed on system */ -const fs = require('fs'); -const path = require('path'); -const { execFileSync } = require('child_process'); +import * as fs from 'fs'; +import * as path from 'path'; +import { execFileSync } from 'child_process'; function extractDotBlocks(markdown) { const blocks = []; diff --git a/tests/writing-skills/test-render-graphs.sh b/tests/writing-skills/test-render-graphs.sh new file mode 100755 index 000000000..349cd47e6 --- /dev/null +++ b/tests/writing-skills/test-render-graphs.sh @@ -0,0 +1,113 @@ +#!/usr/bin/env bash +set -u + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +SCRIPT_UNDER_TEST="$REPO_ROOT/skills/writing-skills/render-graphs.js" +NODE_BIN="$(command -v node)" + +PASSES=0 +FAILURES=0 +TEST_ROOT="$(mktemp -d)" + +cleanup() { + rm -rf "$TEST_ROOT" +} +trap cleanup EXIT + +pass() { + echo " [PASS] $1" + PASSES=$((PASSES + 1)) +} + +fail() { + echo " [FAIL] $1" + FAILURES=$((FAILURES + 1)) +} + +assert_contains() { + local haystack="$1" + local needle="$2" + local description="$3" + + if printf '%s' "$haystack" | grep -Fq -- "$needle"; then + pass "$description" + else + fail "$description" + echo " expected to find: $needle" + fi +} + +assert_not_contains() { + local haystack="$1" + local needle="$2" + local description="$3" + + if printf '%s' "$haystack" | grep -Fq -- "$needle"; then + fail "$description" + echo " did not expect to find: $needle" + else + pass "$description" + fi +} + +fixture="$TEST_ROOT/fixture-skill" +mkdir -p "$fixture" "$TEST_ROOT/empty-path" +cat >"$fixture/SKILL.md" <<'EOF' +--- +name: fixture-skill +--- + +# Fixture Skill + +```dot +digraph fixture_graph { + start -> end; +} +``` +EOF + +echo "Writing-skills render-graphs tests" + +missing_dot_output="$(PATH="$TEST_ROOT/empty-path" "$NODE_BIN" "$SCRIPT_UNDER_TEST" "$fixture" 2>&1)" +missing_dot_status=$? + +if [[ "$missing_dot_status" -ne 0 ]]; then + pass "missing Graphviz exits non-zero" +else + fail "missing Graphviz exits non-zero" +fi +assert_contains "$missing_dot_output" "Error: graphviz (dot) not found." "missing Graphviz reports install guidance" +assert_not_contains "$missing_dot_output" "ReferenceError: require is not defined" "script runs as an ES module" + +render_output="$("$NODE_BIN" "$SCRIPT_UNDER_TEST" "$fixture" 2>&1)" +render_status=$? + +if [[ "$render_status" -eq 0 ]]; then + pass "fixture diagram renders" +else + fail "fixture diagram renders" + printf '%s\n' "$render_output" +fi + +assert_contains "$render_output" "Found 1 diagram(s)" "reports discovered diagram" +assert_contains "$render_output" "Rendered: fixture_graph.svg" "reports rendered SVG" + +if [[ -f "$fixture/diagrams/fixture_graph.svg" ]]; then + pass "writes SVG output" +else + fail "writes SVG output" +fi + +if [[ -f "$fixture/diagrams/fixture_graph.svg" ]] && grep -Fq " Date: Thu, 6 Aug 2026 12:14:55 -0700 Subject: [PATCH 090/198] fix(finishing): name the actual files in the refusal prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `git status --porcelain` collapses a wholly-untracked directory to a single `?? docs/` line. In the shape of the incident this step exists for (#2016 — an uncommitted plan document under an untracked `docs/` tree), the file list we show the human partner therefore names no file at all: $ git -C "$WORKTREE_PATH" status --porcelain ?? docs/ $ git -C "$WORKTREE_PATH" status --porcelain -uall ?? docs/superpowers/plans/2026-08-04-csv-export-rollout.md Both forms produce identical (empty) output on a clean worktree, so this adds no over-trigger surface. Found while running this PR's behavioral micro-tests. Every treatment agent dug past `?? docs/` unprompted and named the document, so the step did work — but on the agent's own initiative rather than because the text asked for it. That initiative is not reliable one tier down: Claude Haiku 4.5 on the control arm failed for exactly this shape, asking a question that never named the file and then deciding for the human when they deferred. Nothing in the prior wording stopped a treatment agent from relaying `?? docs/` verbatim and satisfying the letter of the instruction. Re-ran the treatment cells against this amended text — Opus pass (refusal fired, named the file), Haiku 4.5 pass (named the file) — no regression. Co-Authored-By: Claude Opus 5 (1M context) --- skills/finishing-a-development-branch/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/finishing-a-development-branch/SKILL.md b/skills/finishing-a-development-branch/SKILL.md index 4ca486bef..fa8aecaf8 100644 --- a/skills/finishing-a-development-branch/SKILL.md +++ b/skills/finishing-a-development-branch/SKILL.md @@ -180,7 +180,7 @@ or scratch work. Never `--force` on your own initiative. Show your human partner what is at stake and ask: ```bash -git -C "$WORKTREE_PATH" status --porcelain +git -C "$WORKTREE_PATH" status --porcelain -uall ``` ``` From ffe22811bf6177089046645869780105cb9224e9 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Wed, 5 Aug 2026 18:52:47 -0700 Subject: [PATCH 091/198] docs: design Hermes version-bump wiring Document the agreed follow-up to PR #2025 on a branch based on its merged dev commit. The design registers the Hermes YAML manifest, keeps jq for existing JSON files, and uses Mike Farah yq v4 for a narrow top-level YAML field rather than adding a Bash parser.\n\nDefine focused failure behavior and behavioral tests while explicitly excluding nested YAML, Hermes runtime changes, and unrelated release-script refactors. This captures Drew's request to keep the implementation small and avoid process or abstraction overhead. --- ...08-05-hermes-version-bump-wiring-design.md | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md diff --git a/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md b/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md new file mode 100644 index 000000000..b3187e483 --- /dev/null +++ b/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md @@ -0,0 +1,47 @@ +# Hermes Version-Bump Wiring Design + +**Date:** 2026-08-05 +**Status:** Draft for Drew review + +## Goal + +Keep `.hermes-plugin/plugin.yaml` in lockstep with the repository version by +registering it in `.version-bump.json` and teaching `scripts/bump-version.sh` +to process YAML without implementing a YAML parser in Bash. + +## Design + +- Add `{ "path": ".hermes-plugin/plugin.yaml", "field": "version" }` to + `.version-bump.json`. +- Dispatch manifest reads and writes by extension. +- Keep the existing `jq` path for JSON manifests. +- Use Mike Farah `yq` v4 for `.yaml` and `.yml` manifests. +- Limit YAML entries to one top-level field such as `version`; dotted YAML + paths are out of scope. +- Route `--check`, `--audit`, and version updates through the same dispatcher. + +Non-help commands fail with an actionable message when a required tool is +missing, `yq` is not the Mike Farah v4 implementation, a YAML field is nested +or missing, or a configured extension is unsupported. Existing JSON behavior +and unrelated release-script semantics remain unchanged. + +## Tests + +Behavioral tests run the real script against an isolated temporary fixture and +prove: + +- aligned JSON and YAML manifests pass `--check`; +- YAML drift fails `--check`; +- a version bump updates both formats; +- nested YAML fields and an incompatible `yq` fail clearly; and +- the real Hermes manifest is registered in `.version-bump.json`. + +Verification also runs the existing Hermes tests, shell lint, and +`scripts/bump-version.sh --check` against the repository. + +## Non-Goals + +- No hand-written YAML parser. +- No general nested-YAML support. +- No Hermes runtime changes. +- No refactor of unrelated audit, missing-file, or version-validation behavior. From 3e1ecde38f4d2890379ee8b70ecb92a7d87bd7bb Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Thu, 6 Aug 2026 14:21:22 -0700 Subject: [PATCH 092/198] docs: reduce Hermes version-bump design Incorporate the adversarial design review without turning the Hermes wiring follow-up into a general release-script refactor. Keep the existing jq path, add Mike Farah yq v4 only for .yaml, and retain one read-only preflight to prevent deterministic partial bumps.\n\nReduce the test contract to three behavioral cases and explicitly defer .yml support, nested YAML, rollback machinery, audit/status redesign, exhaustive failure matrices, and the separately discovered JSON-expression issue. This follows Drew's direction to avoid ceremony and overengineering. --- ...08-05-hermes-version-bump-wiring-design.md | 44 +++++++++++-------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md b/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md index b3187e483..5a401925b 100644 --- a/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md +++ b/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md @@ -1,6 +1,7 @@ # Hermes Version-Bump Wiring Design **Date:** 2026-08-05 +**Revised:** 2026-08-06 **Status:** Draft for Drew review ## Goal @@ -13,28 +14,30 @@ to process YAML without implementing a YAML parser in Bash. - Add `{ "path": ".hermes-plugin/plugin.yaml", "field": "version" }` to `.version-bump.json`. -- Dispatch manifest reads and writes by extension. -- Keep the existing `jq` path for JSON manifests. -- Use Mike Farah `yq` v4 for `.yaml` and `.yml` manifests. -- Limit YAML entries to one top-level field such as `version`; dotted YAML - paths are out of scope. -- Route `--check`, `--audit`, and version updates through the same dispatcher. +- Route `.json` through the existing `jq` helpers and `.yaml` through Mike + Farah `yq` v4. The YAML key and value are passed as data, not interpolated + into the expression. +- Support only a present top-level YAML string field. Nested fields and `.yml` + are out of scope. +- Route `--check`, `--audit`, and version updates through the same small + read/write dispatcher. +- Before any non-help command, run one read-only preflight that validates the + required tools and configured extensions, then reads every present declared + manifest. This prevents a deterministic YAML failure from occurring after + earlier JSON files have already been updated. Missing-file behavior remains + unchanged, and `--help` still works without `jq` or `yq`. -Non-help commands fail with an actionable message when a required tool is -missing, `yq` is not the Mike Farah v4 implementation, a YAML field is nested -or missing, or a configured extension is unsupported. Existing JSON behavior -and unrelated release-script semantics remain unchanged. +The preflight is the only reliability addition. It does not make the script +transactional or redesign its existing audit and error-status behavior. ## Tests -Behavioral tests run the real script against an isolated temporary fixture and -prove: +Three focused behavioral tests run the real script against an isolated +temporary fixture and prove: -- aligned JSON and YAML manifests pass `--check`; -- YAML drift fails `--check`; -- a version bump updates both formats; -- nested YAML fields and an incompatible `yq` fail clearly; and -- the real Hermes manifest is registered in `.version-bump.json`. +- aligned JSON and YAML pass `--check`, and a bump updates both formats; +- a preflight failure leaves every manifest unchanged; and +- the real `.version-bump.json` registers the Hermes manifest. Verification also runs the existing Hermes tests, shell lint, and `scripts/bump-version.sh --check` against the repository. @@ -42,6 +45,9 @@ Verification also runs the existing Hermes tests, shell lint, and ## Non-Goals - No hand-written YAML parser. -- No general nested-YAML support. +- No `.yml` or nested-YAML support. - No Hermes runtime changes. -- No refactor of unrelated audit, missing-file, or version-validation behavior. +- No rollback framework, general config-schema layer, audit/status refactor, or + exhaustive failure matrix. +- No change to the separate version-validation and JSON-expression issue found + during review. From 707b155a384f835dd375edf848b1d3d04f21987e Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Thu, 6 Aug 2026 14:42:08 -0700 Subject: [PATCH 093/198] docs: plan Hermes version-bump wiring Record Drew's approved reduced design after the second staff review. Limit preflight to the mutating bump path, cover audit's independent read path, and require byte-for-byte proof that deterministic YAML failures cannot partially update earlier JSON manifests. Provide one TDD implementation task for the Hermes registry entry, jq/yq dispatch, focused preflight, and three behavioral checks. Explicitly defer rollback, audit-status changes, nested YAML, runtime changes, and broader release-tool refactoring. --- .../2026-08-06-hermes-version-bump-wiring.md | 304 ++++++++++++++++++ ...08-05-hermes-version-bump-wiring-design.md | 23 +- 2 files changed, 317 insertions(+), 10 deletions(-) create mode 100644 docs/superpowers/plans/2026-08-06-hermes-version-bump-wiring.md diff --git a/docs/superpowers/plans/2026-08-06-hermes-version-bump-wiring.md b/docs/superpowers/plans/2026-08-06-hermes-version-bump-wiring.md new file mode 100644 index 000000000..8fccfbf36 --- /dev/null +++ b/docs/superpowers/plans/2026-08-06-hermes-version-bump-wiring.md @@ -0,0 +1,304 @@ +# Hermes Version-Bump Wiring 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:** Keep the Hermes YAML manifest version synchronized with every other declared release manifest. + +**Spec:** `docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md` + +**Architecture:** Extend the existing release script with a small extension-based dispatcher: JSON continues through `jq`, while `.yaml` uses Mike Farah `yq` v4. Before the mutating bump loop, read every present manifest through that dispatcher so deterministic format or field failures occur before the first write. + +**Tech Stack:** Bash 3.2-compatible shell, `jq`, Mike Farah `yq` v4, existing shell-lint tooling. + +## Global Constraints + +- Support only `.json` and `.yaml`; `.yml` and other extensions remain unsupported. +- YAML fields are present top-level strings; nested YAML fields are out of scope. +- Pass the YAML field and new value through environment data, never interpolate either into a `yq` expression. +- Keep `yq` confined to maintainer release tooling; do not add a plugin runtime dependency. +- Preserve the existing missing-file behavior: `--check` reports missing files and a bump skips them. +- Preflight only the mutating bump path; do not add rollback or transactional writes. +- Do not change audit status behavior, version validation, or the existing JSON field-expression implementation. + +--- + +## File Map + +- Create: `tests/version-bump/test-bump-version.sh` + - Exercise the real script in temporary JSON/YAML fixtures and check the real registry. +- Modify: `scripts/bump-version.sh` + - Add YAML read/write helpers, format dispatch, and bump-only read preflight. +- Modify: `.version-bump.json` + - Register `.hermes-plugin/plugin.yaml` at top-level field `version`. + +### Task 1: Wire Hermes Into The Existing Version-Bump Script + +**Files:** +- Create: `tests/version-bump/test-bump-version.sh` +- Modify: `scripts/bump-version.sh` +- Modify: `.version-bump.json` + +**Interfaces:** +- Consumes: `.version-bump.json` records shaped as `{ "path": string, "field": string }`. +- Produces: `read_manifest_field FILE FIELD`, `write_manifest_field FILE FIELD VALUE`, and `preflight_manifests` Bash helpers. + +- [ ] **Step 1: Fetch the current development base** + +Run: + +```bash +git fetch origin dev +``` + +Expected: command exits 0 and refreshes `origin/dev`. + +- [ ] **Step 2: Rebase the task branch** + +Run: + +```bash +git rebase origin/dev +``` + +Expected: command exits 0, and `git status --short --branch` no longer reports the branch behind `origin/dev`. + +- [ ] **Step 3: Add the initial failing behavioral test** + +Create `tests/version-bump/test-bump-version.sh` with the happy-path fixture and real registry assertion: + +```bash +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +SCRIPT_SOURCE="$REPO_ROOT/scripts/bump-version.sh" +TEST_ROOT="$(mktemp -d)" + +cleanup() { + rm -rf "$TEST_ROOT" +} +trap cleanup EXIT + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +make_fixture() { + local repo="$1" + local yaml_body="$2" + + mkdir -p "$repo/scripts" "$repo/.hermes-plugin" + cp "$SCRIPT_SOURCE" "$repo/scripts/bump-version.sh" + cat >"$repo/.version-bump.json" <<'JSON' +{ + "files": [ + { "path": "package.json", "field": "version" }, + { "path": ".hermes-plugin/plugin.yaml", "field": "version" } + ], + "audit": { "exclude": [] } +} +JSON + cat >"$repo/package.json" <<'JSON' +{ + "name": "fixture", + "version": "1.2.3" +} +JSON + printf '%s\n' "$yaml_body" >"$repo/.hermes-plugin/plugin.yaml" +} + +happy_repo="$TEST_ROOT/happy" +make_fixture "$happy_repo" $'name: superpowers\nversion: 1.2.3' + +/bin/bash "$happy_repo/scripts/bump-version.sh" --check >"$TEST_ROOT/check.out" +/bin/bash "$happy_repo/scripts/bump-version.sh" --audit >"$TEST_ROOT/audit.out" +/bin/bash "$happy_repo/scripts/bump-version.sh" 2.3.4 >"$TEST_ROOT/bump.out" + +[[ "$(jq -r '.version' "$happy_repo/package.json")" == "2.3.4" ]] \ + || fail "JSON manifest was not bumped" +[[ "$(yq -r '.version' "$happy_repo/.hermes-plugin/plugin.yaml")" == "2.3.4" ]] \ + || fail "YAML manifest was not bumped" + +jq -e ' + any(.files[]; + .path == ".hermes-plugin/plugin.yaml" and .field == "version") +' "$REPO_ROOT/.version-bump.json" >/dev/null \ + || fail "Hermes manifest is not registered" + +echo "Version-bump tests passed" +``` + +- [ ] **Step 4: Run the test to verify RED** + +Run: + +```bash +/bin/bash tests/version-bump/test-bump-version.sh +``` + +Expected: FAIL before `Version-bump tests passed`; the current JSON-only reader cannot process the YAML fixture. + +- [ ] **Step 5: Add minimal YAML dispatch and register Hermes** + +In `scripts/bump-version.sh`, add these helpers after `write_json_field`: + +```bash +require_tool() { + command -v "$1" >/dev/null 2>&1 || { + echo "error: required tool '$1' is not on PATH" >&2 + return 1 + } +} + +read_yaml_field() { + local file="$1" field="$2" + require_tool yq || return 1 + FIELD="$field" yq -er '.[strenv(FIELD)] | select(tag == "!!str")' "$file" +} + +write_yaml_field() { + local file="$1" field="$2" value="$3" + FIELD="$field" VALUE="$value" \ + yq -i '.[strenv(FIELD)] = strenv(VALUE)' "$file" +} + +read_manifest_field() { + local file="$1" + + case "$file" in + *.json) read_json_field "$@" ;; + *.yaml) read_yaml_field "$@" ;; + *) + echo "error: unsupported manifest format: $file" >&2 + return 1 + ;; + esac +} + +write_manifest_field() { + local file="$1" + + case "$file" in + *.json) write_json_field "$@" ;; + *.yaml) write_yaml_field "$@" ;; + *) + echo "error: unsupported manifest format: $file" >&2 + return 1 + ;; + esac +} +``` + +Replace the three command-path calls to `read_json_field` with `read_manifest_field`, and replace the bump-path call to `write_json_field` with `write_manifest_field`. + +Add this exact entry to `.version-bump.json` immediately after `package.json`: + +```json +{ "path": ".hermes-plugin/plugin.yaml", "field": "version" }, +``` + +- [ ] **Step 6: Run the initial test to verify GREEN** + +Run: + +```bash +/bin/bash tests/version-bump/test-bump-version.sh +``` + +Expected: PASS with `Version-bump tests passed`. + +- [ ] **Step 7: Add the failing no-partial-write regression** + +Insert this block before the final success message in `tests/version-bump/test-bump-version.sh`: + +```bash +invalid_repo="$TEST_ROOT/invalid" +make_fixture "$invalid_repo" $'name: superpowers\nversion: 123' +cp "$invalid_repo/package.json" "$TEST_ROOT/package.before" +cp "$invalid_repo/.hermes-plugin/plugin.yaml" "$TEST_ROOT/plugin.before" + +if /bin/bash "$invalid_repo/scripts/bump-version.sh" 2.3.4 \ + >"$TEST_ROOT/invalid.out" 2>&1; then + fail "bump accepted a non-string YAML version" +fi + +cmp -s "$TEST_ROOT/package.before" "$invalid_repo/package.json" \ + || fail "JSON manifest changed before YAML validation failed" +cmp -s "$TEST_ROOT/plugin.before" "$invalid_repo/.hermes-plugin/plugin.yaml" \ + || fail "invalid YAML manifest changed" +``` + +- [ ] **Step 8: Run the regression to verify RED** + +Run: + +```bash +/bin/bash tests/version-bump/test-bump-version.sh +``` + +Expected: FAIL with `JSON manifest changed before YAML validation failed`; without preflight, the JSON manifest is written before the later YAML reader rejects its non-string version. + +- [ ] **Step 9: Add the bump-only preflight** + +Add this helper after `declared_files` in `scripts/bump-version.sh`: + +```bash +preflight_manifests() { + local path field fullpath + + require_tool jq || return 1 + while IFS=$'\t' read -r path field; do + fullpath="$REPO_ROOT/$path" + [[ -f "$fullpath" ]] || continue + + if ! read_manifest_field "$fullpath" "$field" >/dev/null; then + echo "error: cannot read declared manifest: $path ($field)" >&2 + return 1 + fi + done < <(declared_files) +} +``` + +Call it in `cmd_bump` after version-format validation and before the first bump output or write: + +```bash + preflight_manifests + + echo "Bumping all declared files to $new_version..." +``` + +- [ ] **Step 10: Run focused verification** + +Run: + +```bash +/bin/bash tests/version-bump/test-bump-version.sh +scripts/lint-shell.sh scripts/bump-version.sh tests/version-bump/test-bump-version.sh +scripts/bump-version.sh --check +git diff --check +``` + +Expected: + +- The behavioral test prints `Version-bump tests passed`. +- Shell lint reports both scripts with no errors. +- `--check` lists eight declared manifests, including `.hermes-plugin/plugin.yaml`, all at `6.2.0`. +- `git diff --check` prints nothing. + +- [ ] **Step 11: Review and commit the implementation** + +Run: + +```bash +git status --short +git diff -- .version-bump.json scripts/bump-version.sh tests/version-bump/test-bump-version.sh +git add .version-bump.json scripts/bump-version.sh tests/version-bump/test-bump-version.sh +git commit \ + -m "fix(release): wire Hermes into version bumps" \ + -m "Register the Hermes YAML manifest alongside the existing JSON manifests. Route manifest reads and writes by extension through jq or Mike Farah yq v4, with field names and values passed as data." \ + -m "Preflight every present manifest before the mutating bump loop so a deterministic YAML read failure cannot leave earlier JSON manifests partially updated. Cover check, audit, bump, registry wiring, and byte-for-byte no-partial-write behavior with one focused fixture test." +``` + +Expected: the commit succeeds with only the three implementation paths staged. diff --git a/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md b/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md index 5a401925b..4629b0cd3 100644 --- a/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md +++ b/docs/superpowers/specs/2026-08-05-hermes-version-bump-wiring-design.md @@ -2,7 +2,7 @@ **Date:** 2026-08-05 **Revised:** 2026-08-06 -**Status:** Draft for Drew review +**Status:** Approved ## Goal @@ -21,11 +21,11 @@ to process YAML without implementing a YAML parser in Bash. are out of scope. - Route `--check`, `--audit`, and version updates through the same small read/write dispatcher. -- Before any non-help command, run one read-only preflight that validates the - required tools and configured extensions, then reads every present declared - manifest. This prevents a deterministic YAML failure from occurring after - earlier JSON files have already been updated. Missing-file behavior remains - unchanged, and `--help` still works without `jq` or `yq`. +- Before a version bump writes any manifest, run one read-only preflight that + validates the required tools and reads every present declared manifest + through the dispatcher. This prevents a deterministic YAML failure from + occurring after earlier JSON files have already been updated. Missing-file + behavior remains unchanged, and `--help` still works without `jq` or `yq`. The preflight is the only reliability addition. It does not make the script transactional or redesign its existing audit and error-status behavior. @@ -35,12 +35,15 @@ transactional or redesign its existing audit and error-status behavior. Three focused behavioral tests run the real script against an isolated temporary fixture and prove: -- aligned JSON and YAML pass `--check`, and a bump updates both formats; -- a preflight failure leaves every manifest unchanged; and +- aligned JSON and YAML pass `--check` and `--audit`, and a bump updates both + formats; +- an actual bump with JSON declared first and a later YAML manifest whose + top-level `version` is not a string exits nonzero and leaves every manifest + byte-for-byte unchanged; and - the real `.version-bump.json` registers the Hermes manifest. -Verification also runs the existing Hermes tests, shell lint, and -`scripts/bump-version.sh --check` against the repository. +Verification also runs shell lint and `scripts/bump-version.sh --check` against +the repository. ## Non-Goals From 5f8f500b1d8655607890b8439cb5c31b4301917c Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Thu, 6 Aug 2026 14:47:14 -0700 Subject: [PATCH 094/198] fix(release): wire Hermes into version bumps Register the Hermes YAML manifest alongside the existing JSON manifests. Route manifest reads and writes by extension through jq or Mike Farah yq v4, with field names and values passed as data. Preflight every present manifest before the mutating bump loop so a deterministic YAML read failure cannot leave earlier JSON manifests partially updated. Cover check, audit, bump, registry wiring, and byte-for-byte no-partial-write behavior with one focused fixture test. --- .version-bump.json | 1 + scripts/bump-version.sh | 70 +++++++++++++++++++++-- tests/version-bump/test-bump-version.sh | 76 +++++++++++++++++++++++++ 3 files changed, 143 insertions(+), 4 deletions(-) create mode 100644 tests/version-bump/test-bump-version.sh diff --git a/.version-bump.json b/.version-bump.json index 7fc6cc9fe..8b9c6d99b 100644 --- a/.version-bump.json +++ b/.version-bump.json @@ -1,6 +1,7 @@ { "files": [ { "path": "package.json", "field": "version" }, + { "path": ".hermes-plugin/plugin.yaml", "field": "version" }, { "path": ".claude-plugin/plugin.json", "field": "version" }, { "path": ".cursor-plugin/plugin.json", "field": "version" }, { "path": ".codex-plugin/plugin.json", "field": "version" }, diff --git a/scripts/bump-version.sh b/scripts/bump-version.sh index 01adec992..14ead0029 100755 --- a/scripts/bump-version.sh +++ b/scripts/bump-version.sh @@ -40,12 +40,72 @@ write_json_field() { jq "$jq_path = \"$value\"" "$file" > "$tmp" && mv "$tmp" "$file" } +require_tool() { + command -v "$1" >/dev/null 2>&1 || { + echo "error: required tool '$1' is not on PATH" >&2 + return 1 + } +} + +read_yaml_field() { + local file="$1" field="$2" + require_tool yq || return 1 + FIELD="$field" yq -er '.[strenv(FIELD)] | select(tag == "!!str")' "$file" +} + +write_yaml_field() { + local file="$1" field="$2" value="$3" + FIELD="$field" VALUE="$value" \ + yq -i '.[strenv(FIELD)] = strenv(VALUE)' "$file" +} + +read_manifest_field() { + local file="$1" + + case "$file" in + *.json) read_json_field "$@" ;; + *.yaml) read_yaml_field "$@" ;; + *) + echo "error: unsupported manifest format: $file" >&2 + return 1 + ;; + esac +} + +write_manifest_field() { + local file="$1" + + case "$file" in + *.json) write_json_field "$@" ;; + *.yaml) write_yaml_field "$@" ;; + *) + echo "error: unsupported manifest format: $file" >&2 + return 1 + ;; + esac +} + # Read the list of declared files from config. # Outputs lines of "pathfield" declared_files() { jq -r '.files[] | "\(.path)\t\(.field)"' "$CONFIG" } +preflight_manifests() { + local path field fullpath + + require_tool jq || return 1 + while IFS=$'\t' read -r path field; do + fullpath="$REPO_ROOT/$path" + [[ -f "$fullpath" ]] || continue + + if ! read_manifest_field "$fullpath" "$field" >/dev/null; then + echo "error: cannot read declared manifest: $path ($field)" >&2 + return 1 + fi + done < <(declared_files) +} + # Read the audit exclude patterns from config. audit_excludes() { jq -r '.audit.exclude[]' "$CONFIG" 2>/dev/null @@ -68,7 +128,7 @@ cmd_check() { continue fi local ver - ver=$(read_json_field "$fullpath" "$field") + ver=$(read_manifest_field "$fullpath" "$field") printf " %-45s %s\n" "$path ($field)" "$ver" versions+=("$ver") done < <(declared_files) @@ -101,7 +161,7 @@ cmd_audit() { current_version=$( while IFS=$'\t' read -r path field; do local fullpath="$REPO_ROOT/$path" - [[ -f "$fullpath" ]] && read_json_field "$fullpath" "$field" + [[ -f "$fullpath" ]] && read_manifest_field "$fullpath" "$field" done < <(declared_files) | sort | uniq -c | sort -rn | head -1 | awk '{print $2}' ) @@ -172,6 +232,8 @@ cmd_bump() { exit 1 fi + preflight_manifests + echo "Bumping all declared files to $new_version..." echo "" @@ -182,8 +244,8 @@ cmd_bump() { continue fi local old_ver - old_ver=$(read_json_field "$fullpath" "$field") - write_json_field "$fullpath" "$field" "$new_version" + old_ver=$(read_manifest_field "$fullpath" "$field") + write_manifest_field "$fullpath" "$field" "$new_version" printf " %-45s %s -> %s\n" "$path ($field)" "$old_ver" "$new_version" done < <(declared_files) diff --git a/tests/version-bump/test-bump-version.sh b/tests/version-bump/test-bump-version.sh new file mode 100644 index 000000000..195d88a11 --- /dev/null +++ b/tests/version-bump/test-bump-version.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +SCRIPT_SOURCE="$REPO_ROOT/scripts/bump-version.sh" +TEST_ROOT="$(mktemp -d)" + +cleanup() { + rm -rf "$TEST_ROOT" +} +trap cleanup EXIT + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +make_fixture() { + local repo="$1" + local yaml_body="$2" + + mkdir -p "$repo/scripts" "$repo/.hermes-plugin" + cp "$SCRIPT_SOURCE" "$repo/scripts/bump-version.sh" + cat >"$repo/.version-bump.json" <<'JSON' +{ + "files": [ + { "path": "package.json", "field": "version" }, + { "path": ".hermes-plugin/plugin.yaml", "field": "version" } + ], + "audit": { "exclude": [] } +} +JSON + cat >"$repo/package.json" <<'JSON' +{ + "name": "fixture", + "version": "1.2.3" +} +JSON + printf '%s\n' "$yaml_body" >"$repo/.hermes-plugin/plugin.yaml" +} + +happy_repo="$TEST_ROOT/happy" +make_fixture "$happy_repo" $'name: superpowers\nversion: 1.2.3' + +/bin/bash "$happy_repo/scripts/bump-version.sh" --check >"$TEST_ROOT/check.out" +/bin/bash "$happy_repo/scripts/bump-version.sh" --audit >"$TEST_ROOT/audit.out" +/bin/bash "$happy_repo/scripts/bump-version.sh" 2.3.4 >"$TEST_ROOT/bump.out" + +[[ "$(jq -r '.version' "$happy_repo/package.json")" == "2.3.4" ]] \ + || fail "JSON manifest was not bumped" +[[ "$(yq -r '.version' "$happy_repo/.hermes-plugin/plugin.yaml")" == "2.3.4" ]] \ + || fail "YAML manifest was not bumped" + +jq -e ' + any(.files[]; + .path == ".hermes-plugin/plugin.yaml" and .field == "version") +' "$REPO_ROOT/.version-bump.json" >/dev/null \ + || fail "Hermes manifest is not registered" + +invalid_repo="$TEST_ROOT/invalid" +make_fixture "$invalid_repo" $'name: superpowers\nversion: 123' +cp "$invalid_repo/package.json" "$TEST_ROOT/package.before" +cp "$invalid_repo/.hermes-plugin/plugin.yaml" "$TEST_ROOT/plugin.before" + +if /bin/bash "$invalid_repo/scripts/bump-version.sh" 2.3.4 \ + >"$TEST_ROOT/invalid.out" 2>&1; then + fail "bump accepted a non-string YAML version" +fi + +cmp -s "$TEST_ROOT/package.before" "$invalid_repo/package.json" \ + || fail "JSON manifest changed before YAML validation failed" +cmp -s "$TEST_ROOT/plugin.before" "$invalid_repo/.hermes-plugin/plugin.yaml" \ + || fail "invalid YAML manifest changed" + +echo "Version-bump tests passed" From 2ee628174705a5db2dcd1bf2eeafe295a8fb48b7 Mon Sep 17 00:00:00 2001 From: GoldJohnKing Date: Fri, 7 Aug 2026 20:16:01 +0800 Subject: [PATCH 095/198] feat(opencode): add V2 (opencode2) plugin compatibility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add dual V1/V2 support to the OpenCode plugin. The same source file now works on both OpenCode V1 (opencode) and V2 (opencode2) without version detection at runtime. V2 changes: - Add default export { id, server, setup } for V2 PluginSupervisor - setup() registers skills via ctx.skill.transform() (V2 native API) - setup() injects bootstrap via ctx.session.hook('context') (V2 equivalent of V1's experimental.chat.messages.transform) - config hook guards against V2 array-format skills to avoid conflicts Both APIs confirmed active at runtime via diagnostics in the V2 beta. No external dependencies added — pure JavaScript throughout. Docs updated with V2 install instructions, OPENCODE_CONFIG_DIR side-by-side setup, and accurate How It Works section for both versions. --- .opencode/INSTALL.md | 77 ++++++++++++++++++- .opencode/plugins/superpowers.js | 128 +++++++++++++++++++++---------- docs/README.opencode.md | 106 ++++++++++++++++++++++--- 3 files changed, 257 insertions(+), 54 deletions(-) diff --git a/.opencode/INSTALL.md b/.opencode/INSTALL.md index 080f043f8..c761c6dc0 100644 --- a/.opencode/INSTALL.md +++ b/.opencode/INSTALL.md @@ -4,7 +4,7 @@ - [OpenCode.ai](https://opencode.ai) installed -## Installation +## OpenCode V1 (`opencode`) Installation Add superpowers to the `plugin` array in your `opencode.json` (global or project-level): @@ -22,6 +22,72 @@ Verify by asking: "Tell me about your superpowers" OpenCode uses its own plugin install. If you also use Claude Code, Codex, or another harness, install Superpowers separately for each one. +## OpenCode V2 (`opencode2`) Installation + +V2 does not support `git+https://` plugin installation. Use a local clone +with a path reference instead. + +### Steps + +1. Clone the repository: + +```bash +git clone https://github.com/obra/superpowers.git ~/superpowers +``` + +2. Add the plugin to your `opencode.json` (global or project-level). + Use the `plugin` field (singular) with an absolute path: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [ + "/home/your-username/superpowers/.opencode/plugins/superpowers.js" + ] +} +``` + +> **Note:** V2 does not expand `~` in local plugin paths. Use an absolute +> path or a relative path (`./` or `../`) resolved from the config file +> directory. + +3. Restart OpenCode: + +```bash +opencode2 service restart +``` + +4. Verify by asking: "Tell me about your superpowers" + +### Updating + +```bash +cd ~/superpowers && git pull +opencode2 service restart +``` + +## Running V1 and V2 Side by Side + +V1 (`opencode`) and V2 (`opencode2`) share the same default config directory +(`~/.config/opencode/`). Since V2 normalizes V1's `plugin` field into its own +loading pipeline, putting a `git+https://` spec (which V2 cannot install) in +the shared config causes V2 to silently fail loading it. + +To use different plugin sources for each version, point V2 at a separate +config directory via the `OPENCODE_CONFIG_DIR` environment variable: + +```bash +# In ~/.bashrc (or equivalent shell config) +export OPENCODE_CONFIG_DIR="$HOME/.config/opencode2" +``` + +Then maintain two config files: + +- `~/.config/opencode/opencode.json` — V1 config, using `git+https://` sources +- `~/.config/opencode2/opencode.json` — V2 config, using local path sources + +Both versions can now run independently without interfering with each other. + ## Migrating from the old symlink-based install If you previously installed superpowers using `git clone` and symlinks, remove the old setup: @@ -50,6 +116,8 @@ use skill tool to load brainstorming ## Updating +### V1 (`opencode`) + OpenCode installs Superpowers through a git-backed package spec. Some OpenCode and Bun versions pin that resolved git dependency in a lockfile or cache, so a restart may not pick up the newest Superpowers commit. If updates do not appear, @@ -63,6 +131,13 @@ To pin a specific version: } ``` +### V2 (`opencode2`) + +```bash +cd ~/superpowers && git pull +opencode2 service restart +``` + ## Troubleshooting ### Plugin not loading diff --git a/.opencode/plugins/superpowers.js b/.opencode/plugins/superpowers.js index 423e5ed51..557e3c20e 100644 --- a/.opencode/plugins/superpowers.js +++ b/.opencode/plugins/superpowers.js @@ -1,17 +1,29 @@ /** * Superpowers plugin for OpenCode.ai * - * Injects superpowers bootstrap context via message transform. - * Auto-registers skills directory via config hook (no symlinks needed). + * Dual-compatible with OpenCode V1 and V2. + * + * V1 (opencode): loaded via named export SuperpowersPlugin — provides config + * hook for skills registration and experimental.chat.messages.transform for + * bootstrap injection. + * + * V2 (opencode2): loaded via default export { id, setup } by PluginSupervisor. + * setup() registers skills natively via ctx.skill.transform(), and injects + * bootstrap context via ctx.session.hook("context"). + * + * No external dependencies — pure JavaScript works in both V1 and V2 without + * installing @opencode-ai/plugin or effect. */ import path from 'path'; import fs from 'fs'; -import os from 'os'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); +// Skills directory shared by V1 (config hook) and V2 (setup/ctx.skill.transform) +const superpowersSkillsDir = path.resolve(__dirname, '../../skills'); + // Simple frontmatter extraction (avoid dependency on skills-core for bootstrap) const extractAndStripFrontmatter = (content) => { const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/); @@ -33,47 +45,28 @@ const extractAndStripFrontmatter = (content) => { return { frontmatter, content: body }; }; -// Normalize a path: trim whitespace, expand ~, resolve to absolute -const normalizePath = (p, homeDir) => { - if (!p || typeof p !== 'string') return null; - let normalized = p.trim(); - if (!normalized) return null; - if (normalized.startsWith('~/')) { - normalized = path.join(homeDir, normalized.slice(2)); - } else if (normalized === '~') { - normalized = homeDir; - } - return path.resolve(normalized); -}; - // Module-level cache for bootstrap content. // The SKILL.md file does not change during a session, so reading + parsing it // once eliminates redundant fs.existsSync + fs.readFileSync + regex work on // every agent step. See #1202 for the full analysis. let _bootstrapCache = undefined; // undefined = not yet loaded, null = file missing -export const SuperpowersPlugin = async ({ client, directory }) => { - const homeDir = os.homedir(); - const superpowersSkillsDir = path.resolve(__dirname, '../../skills'); - const envConfigDir = normalizePath(process.env.OPENCODE_CONFIG_DIR, homeDir); - const configDir = envConfigDir || path.join(homeDir, '.config/opencode'); +// Helper to generate bootstrap content (cached after first call) +const getBootstrapContent = () => { + // Return cached result on subsequent calls + if (_bootstrapCache !== undefined) return _bootstrapCache; - // Helper to generate bootstrap content (cached after first call) - const getBootstrapContent = () => { - // Return cached result on subsequent calls - if (_bootstrapCache !== undefined) return _bootstrapCache; + // Try to load using-superpowers skill + const skillPath = path.join(superpowersSkillsDir, 'using-superpowers', 'SKILL.md'); + if (!fs.existsSync(skillPath)) { + _bootstrapCache = null; + return null; + } - // Try to load using-superpowers skill - const skillPath = path.join(superpowersSkillsDir, 'using-superpowers', 'SKILL.md'); - if (!fs.existsSync(skillPath)) { - _bootstrapCache = null; - return null; - } + const fullContent = fs.readFileSync(skillPath, 'utf8'); + const { content } = extractAndStripFrontmatter(fullContent); - const fullContent = fs.readFileSync(skillPath, 'utf8'); - const { content } = extractAndStripFrontmatter(fullContent); - - const toolMapping = `**Tool Mapping for OpenCode:** + const toolMapping = `**Tool Mapping for OpenCode:** When skills request actions, substitute OpenCode equivalents: - Create or update todos → \`todowrite\` - \`Subagent (general-purpose):\` → \`task\` with \`subagent_type: "general"\` @@ -86,7 +79,7 @@ When skills request actions, substitute OpenCode equivalents: Use OpenCode's native \`skill\` tool to list and load skills.`; - _bootstrapCache = ` + _bootstrapCache = ` You have superpowers. **IMPORTANT: The using-superpowers skill content is included below. It is ALREADY LOADED - you are currently following it. Do NOT use the skill tool to load "using-superpowers" again - that would be redundant.** @@ -96,15 +89,25 @@ ${content} ${toolMapping} `; - return _bootstrapCache; - }; + return _bootstrapCache; +}; +/** + * V1 Plugin Function (named export + default.server) + * + * Used by V1 (OpenCode 1.x): discovered via named export scanning. + * Provides: config hook (V1 skills registration) + bootstrap injection + * (experimental.chat.messages.transform). + */ +export const SuperpowersPlugin = async ({ client, directory }) => { return { // Inject skills path into live config so OpenCode discovers superpowers skills // without requiring manual symlinks or config file edits. - // This works because Config.get() returns a cached singleton — modifications - // here are visible when skills are lazily discovered later. config: async (config) => { + // V2: skills is a flat array — skip, setup() handles V2 skill registration + if (Array.isArray(config.skills)) return; + + // V1: skills is { paths: [...] } config.skills = config.skills || {}; config.skills.paths = config.skills.paths || []; if (!config.skills.paths.includes(superpowersSkillsDir)) { @@ -128,8 +131,6 @@ ${toolMapping} if (!firstUser || !firstUser.parts.length) return; // Guard: skip if first user message already contains bootstrap. - // This prevents double injection when OpenCode passes an already - // transformed in-memory message array through the hook again. if (firstUser.parts.some(p => p.type === 'text' && p.text.includes('EXTREMELY_IMPORTANT'))) return; const ref = firstUser.parts[0]; @@ -137,3 +138,46 @@ ${toolMapping} } }; }; + +/** + * V2 Setup Function (default.setup) + * + * Called by V2 PluginSupervisor (packages/core/src/plugin/). + * Performs two things: + * + * 1. Registers the skills directory natively via ctx.skill.transform(). + * 2. Injects bootstrap context via ctx.session.hook("context"), the V2 + * equivalent of V1's experimental.chat.messages.transform. + */ +async function setup(ctx) { + // 1. Register skills + await ctx.skill.transform((draft) => { + draft.source({ + type: 'directory', + path: superpowersSkillsDir, + }); + }); + + // 2. Inject bootstrap into first user message via V2 session context hook + await ctx.session.hook('context', (event) => { + const bootstrap = getBootstrapContent(); + if (!bootstrap || !event.messages || !event.messages.length) return; + const firstUser = event.messages.find(m => m.role === 'user'); + if (!firstUser || !firstUser.content || !firstUser.content.length) return; + if (firstUser.content.some(p => p.type === 'text' && p.text && p.text.includes('EXTREMELY_IMPORTANT'))) return; + firstUser.content.unshift({ type: 'text', text: bootstrap }); + }); +} + +/** + * Default Export: { id, server, setup } + * + * V2 PluginSupervisor reads { id, setup }. + * V1 reads named export SuperpowersPlugin. + * server() is exported for V1 compatibility. + */ +export default { + id: 'superpowers', + server: SuperpowersPlugin, + setup, +}; diff --git a/docs/README.opencode.md b/docs/README.opencode.md index 11da85425..ab5810fe2 100644 --- a/docs/README.opencode.md +++ b/docs/README.opencode.md @@ -4,6 +4,11 @@ Complete guide for using Superpowers with [OpenCode.ai](https://opencode.ai). ## Installation +Installation differs between OpenCode V1 (`opencode`) and V2 (`opencode2`). +Install Superpowers separately for each version if you use both. + +### OpenCode V1 (`opencode`) + Add superpowers to the `plugin` array in your `opencode.json` (global or project-level): ```json @@ -17,10 +22,62 @@ registers all skills. Verify by asking: "Tell me about your superpowers" -OpenCode uses its own plugin install. If you also use Claude Code, Codex, or -another harness, install Superpowers separately for each one. +### OpenCode V2 (`opencode2`) -### Migrating from the old symlink-based install +V2 does not support `git+https://` plugin installation. Use a local clone with +a path reference instead. + +1. Clone the repository: + +```bash +git clone https://github.com/obra/superpowers.git ~/superpowers +``` + +2. Add the plugin using the `plugin` field (singular) with an absolute path: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [ + "/home/your-username/superpowers/.opencode/plugins/superpowers.js" + ] +} +``` + +> **Note:** V2 does not expand `~` in local plugin paths. Use an absolute path +> or a relative path (`./` or `../`) resolved from the config file directory. + +3. Restart and verify: + +```bash +opencode2 service restart +``` + +Ask: "Tell me about your superpowers" + +### Running V1 and V2 Side by Side + +V1 (`opencode`) and V2 (`opencode2`) share the same default config directory +(`~/.config/opencode/`). Since V2 normalizes V1's `plugin` field into its own +loading pipeline, putting a `git+https://` spec (which V2 cannot install) in +the shared config causes V2 to silently fail loading it. + +To use different plugin sources for each version, point V2 at a separate +config directory via the `OPENCODE_CONFIG_DIR` environment variable: + +```bash +# In ~/.bashrc (or equivalent shell config) +export OPENCODE_CONFIG_DIR="$HOME/.config/opencode2" +``` + +Then maintain two config files: + +- `~/.config/opencode/opencode.json` — V1 config, using `git+https://` sources +- `~/.config/opencode2/opencode.json` — V2 config, using local path sources + +Both versions can now run independently without interfering with each other. + +### Migrating from the old symlink-based install (V1) If you previously installed superpowers using `git clone` and symlinks, remove the old setup: @@ -82,6 +139,8 @@ Create project-specific skills in `.opencode/skills/` within your project. ## Updating +### V1 (`opencode`) + OpenCode installs Superpowers through a git-backed package spec. Some OpenCode and Bun versions pin that resolved git dependency in a lockfile or cache, so a restart may not pick up the newest Superpowers commit. If updates do not appear, @@ -95,12 +154,23 @@ To pin a specific version, use a branch or tag: } ``` +### V2 (`opencode2`) + +```bash +cd ~/superpowers && git pull +opencode2 service restart +``` + ## How It Works The plugin does two things: -1. **Injects bootstrap context** via the `experimental.chat.messages.transform` hook, adding superpowers awareness to every conversation. -2. **Registers the skills directory** via the `config` hook, so OpenCode discovers all superpowers skills without symlinks or manual config. +1. **Registers the skills directory** so OpenCode discovers all superpowers skills without symlinks or manual config. + - **V1:** via the `config` hook, injecting into `config.skills.paths` + - **V2:** via the `setup()` function using `ctx.skill.transform()` (V2 native API, confirmed active at runtime) +2. **Injects bootstrap context** into the first user message of each conversation, adding superpowers awareness. + - **V1:** via `experimental.chat.messages.transform` hook + - **V2:** via `ctx.session.hook("context")` — the V2 equivalent (confirmed active at runtime) ### Tool Mapping @@ -121,9 +191,22 @@ Skills speak in actions rather than naming any one runtime's tools. On OpenCode ### Plugin not loading -1. Check OpenCode logs: `opencode run --print-logs "hello" 2>&1 | grep -i superpowers` -2. Verify the plugin line in your `opencode.json` is correct -3. Make sure you're running a recent version of OpenCode +**V1:** Check OpenCode logs: + +``` +opencode run --print-logs "hello" 2>&1 | grep -i superpowers +``` + +**V2:** Check the server log: + +``` +opencode2 service status +``` + +Then inspect `~/.local/share/opencode/log/opencode.log`, filtering for `role=server`. + +Also verify the plugin path in your `opencode.json` is correct and that you're +running a recent version of OpenCode. ### Windows install issues @@ -153,11 +236,12 @@ Then use the installed package path in `opencode.json`: ### Bootstrap not appearing -1. Check OpenCode version supports `experimental.chat.messages.transform` hook -2. Restart OpenCode after config changes +- **V1:** Check OpenCode version supports `experimental.chat.messages.transform` hook. Restart OpenCode after config changes. +- **V2:** The plugin uses `ctx.session.hook("context")` for bootstrap injection. Verify the plugin loaded via `opencode2 api get /api/plugin`. Restart with `opencode2 service restart` after config changes. ## Getting Help - Report issues: https://github.com/obra/superpowers/issues - Main documentation: https://github.com/obra/superpowers -- OpenCode docs: https://opencode.ai/docs/ +- OpenCode V2 docs: https://opencode.ai/v2/docs/ +- OpenCode V1 docs: https://opencode.ai/docs/ From 28125bf284235bb05277dddec3fff8dd35161c2c Mon Sep 17 00:00:00 2001 From: Georgii Perepechko Date: Sat, 4 Jul 2026 11:34:05 +0100 Subject: [PATCH 096/198] docs: add Grok Build CLI to README.md --- README.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 531502be6..cab41fffa 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Superpowers is a complete software development methodology for your coding agent - [Factory Droid](#factory-droid) - [Gemini CLI](#gemini-cli) - [GitHub Copilot CLI](#github-copilot-cli) + - [Grok Build CLI](#grok-build-cli) - [Kimi Code](#kimi-code) - [OpenCode](#opencode) - [Pi](#pi) @@ -30,7 +31,7 @@ Superpowers is a complete software development methodology for your coding agent ## Quickstart -Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Hermes Agent](#hermes-agent), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). +Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Grok Build CLI](#grok-build-cli), [Hermes Agent](#hermes-agent), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). ## How it works @@ -169,6 +170,22 @@ Superpowers is available via the [official Codex plugin marketplace](https://git copilot plugin install superpowers@superpowers-marketplace ``` +### Grok Build CLI + +Superpowers is available via the [official Grok plugin marketplace](https://github.com/xai-org/plugin-marketplace). + +- Install the plugin from xAI's official marketplace: + + ```bash + grok plugin install superpowers@xai-official --trust + ``` + +- Or open the marketplace in the TUI, search for Superpowers, and install it: + + ```text + /marketplace + ``` + ### Kimi Code Superpowers is available in Kimi Code's plugin marketplace. From 09a567b6f4e3ee47aa64c5e8db81a075217bbbfa Mon Sep 17 00:00:00 2001 From: Caio Lopes Date: Thu, 16 Jul 2026 10:46:34 -0300 Subject: [PATCH 097/198] feat: add Devin CLI support Devin CLI's `devin plugins install obra/superpowers` fails today because the repo has no `.devin-plugin/plugin.json` manifest. Add the manifest (skills are auto-discovered from the co-located skills/ directory), a Devin tool mapping linked from using-superpowers' Platform Adaptation section, a README install section, version tracking in .version-bump.json, a Codex-sync exclude for the new dotdir, and a CI-safe test mirroring the kimi/antigravity test style. Bootstrap rides Devin's native skill surfacing: every installed skill's name + description is injected into the system prompt at session start with a standing instruction to invoke matching skills via the native skill tool. Acceptance test ("Let's make a react todo list") passes in a clean session: using-superpowers and brainstorming auto-trigger before any code is written. --- .devin-plugin/plugin.json | 22 +++++ .version-bump.json | 1 + README.md | 17 +++- scripts/sync-to-codex-plugin.sh | 1 + skills/using-superpowers/SKILL.md | 1 + .../references/devin-tools.md | 18 ++++ tests/devin/test-devin-plugin.sh | 85 +++++++++++++++++++ 7 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 .devin-plugin/plugin.json create mode 100644 skills/using-superpowers/references/devin-tools.md create mode 100755 tests/devin/test-devin-plugin.sh diff --git a/.devin-plugin/plugin.json b/.devin-plugin/plugin.json new file mode 100644 index 000000000..5299cca82 --- /dev/null +++ b/.devin-plugin/plugin.json @@ -0,0 +1,22 @@ +{ + "name": "superpowers", + "version": "6.2.0", + "description": "An agentic skills framework & software development methodology that works: planning, TDD, debugging, and collaboration workflows.", + "author": { + "name": "Jesse Vincent", + "email": "jesse@fsck.com" + }, + "homepage": "https://github.com/obra/superpowers", + "repository": "https://github.com/obra/superpowers", + "license": "MIT", + "keywords": [ + "brainstorming", + "subagent-driven-development", + "skills", + "planning", + "tdd", + "debugging", + "code-review", + "workflow" + ] +} diff --git a/.version-bump.json b/.version-bump.json index 8b9c6d99b..8df0a9775 100644 --- a/.version-bump.json +++ b/.version-bump.json @@ -5,6 +5,7 @@ { "path": ".claude-plugin/plugin.json", "field": "version" }, { "path": ".cursor-plugin/plugin.json", "field": "version" }, { "path": ".codex-plugin/plugin.json", "field": "version" }, + { "path": ".devin-plugin/plugin.json", "field": "version" }, { "path": ".kimi-plugin/plugin.json", "field": "version" }, { "path": ".claude-plugin/marketplace.json", "field": "plugins.0.version" }, { "path": "gemini-extension.json", "field": "version" } diff --git a/README.md b/README.md index cab41fffa..652819a96 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Superpowers is a complete software development methodology for your coding agent - [Codex App](#codex-app) - [Codex CLI](#codex-cli) - [Cursor](#cursor) + - [Devin CLI](#devin-cli) - [Factory Droid](#factory-droid) - [Gemini CLI](#gemini-cli) - [GitHub Copilot CLI](#github-copilot-cli) @@ -31,7 +32,7 @@ Superpowers is a complete software development methodology for your coding agent ## Quickstart -Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Grok Build CLI](#grok-build-cli), [Hermes Agent](#hermes-agent), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). +Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Devin CLI](#devin-cli), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Grok Build CLI](#grok-build-cli), [Hermes Agent](#hermes-agent), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). ## How it works @@ -128,6 +129,20 @@ Superpowers is available via the [official Codex plugin marketplace](https://git - Or search for "superpowers" in the plugin marketplace. +### Devin CLI + +- Install the plugin from this repository: + + ```bash + devin plugins install obra/superpowers + ``` + +- Update to the latest version with: + + ```bash + devin plugins update superpowers + ``` + ### Factory Droid - Register the marketplace: diff --git a/scripts/sync-to-codex-plugin.sh b/scripts/sync-to-codex-plugin.sh index ef8e0839f..bdaa13a35 100755 --- a/scripts/sync-to-codex-plugin.sh +++ b/scripts/sync-to-codex-plugin.sh @@ -48,6 +48,7 @@ EXCLUDES=( "/.claude-plugin/" "/.codex/" "/.cursor-plugin/" + "/.devin-plugin/" "/.git/" "/.gitattributes" "/.github/" diff --git a/skills/using-superpowers/SKILL.md b/skills/using-superpowers/SKILL.md index 7ab2eb678..ec24a8764 100644 --- a/skills/using-superpowers/SKILL.md +++ b/skills/using-superpowers/SKILL.md @@ -57,6 +57,7 @@ If your harness appears here, read its reference file for special instructions: - Pi: `references/pi-tools.md` - Antigravity: `references/antigravity-tools.md` - Hermes Agent: `references/hermes-tools.md` +- Devin CLI: `references/devin-tools.md` ## User Instructions diff --git a/skills/using-superpowers/references/devin-tools.md b/skills/using-superpowers/references/devin-tools.md new file mode 100644 index 000000000..dc40d6331 --- /dev/null +++ b/skills/using-superpowers/references/devin-tools.md @@ -0,0 +1,18 @@ +# Devin CLI Tool Mapping + +Skills speak in actions ("dispatch a subagent", "create a todo", "read a file"). On Devin CLI these resolve to the tools below. + +| Action skills request | Devin CLI equivalent | +| --- | --- | +| Invoke a skill | The native `skill` tool (skills also appear as `/superpowers:` slash commands) | +| Dispatch a subagent (`Subagent (general-purpose):` template) | `run_subagent` with the `subagent_general` profile; use `subagent_explore` for read-only exploration | +| Task tracking ("create a todo", "mark complete") | `todo_write` | +| Ask the user / present options | `ask_user_question` (native multiple-choice prompts; fall back to plain text in non-interactive mode) | + +## Subagents + +`run_subagent` subagents are stateless and cannot ask clarifying questions — front-load the full context and exact instructions in the task prompt, as the subagent-driven-development templates already do. Run independent tasks in parallel with `is_background: true`; keep dependent tasks sequential. + +## File, shell, and search tools + +Devin CLI exposes native tools for reading, writing, and editing files, running shell commands, and searching (grep/glob). Exact tool names can vary by session mode — use whichever file/shell/search tools your session exposes rather than names remembered from another harness. diff --git a/tests/devin/test-devin-plugin.sh b/tests/devin/test-devin-plugin.sh new file mode 100755 index 000000000..312990d73 --- /dev/null +++ b/tests/devin/test-devin-plugin.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Validate the Devin CLI integration. `devin plugins install obra/superpowers` +# reads `.devin-plugin/plugin.json` and auto-discovers the co-located `skills/` +# directory; Devin CLI surfaces every installed skill's name + description in +# the system prompt at session start and invokes them via its native `skill` +# tool, so there is no hook or injector scaffold to test. What IS Devin-specific +# is the manifest and the tool mapping — subagent dispatch via run_subagent +# profiles and task tracking via todo_write — and SKILL.md pointing at it. +# +# Mirrors tests/kimi/test-plugin-manifest.sh (manifest) and +# tests/antigravity/test-antigravity-tools.sh (mapping). CI-safe: does not +# require `devin` installed. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" + +MANIFEST="$REPO_ROOT/.devin-plugin/plugin.json" +MAPPING="$REPO_ROOT/skills/using-superpowers/references/devin-tools.md" +SKILL="$REPO_ROOT/skills/using-superpowers/SKILL.md" + +fail() { echo "FAIL: $*" >&2; exit 1; } + +echo "test-devin-plugin: checking Devin CLI manifest and tool mapping" + +# --- Manifest is valid and matches the repo version ------------------------- +[ -f "$MANIFEST" ] || fail "manifest missing at $MANIFEST" + +python3 - "$MANIFEST" <<'PY' +import json +import sys +from pathlib import Path + +manifest_path = Path(sys.argv[1]) +manifest = json.loads(manifest_path.read_text(encoding="utf-8")) +repo_root = manifest_path.parents[1] + +if manifest.get("name") != "superpowers": + raise AssertionError(f"plugin name: expected 'superpowers', got {manifest.get('name')!r}") + +package = json.loads((repo_root / "package.json").read_text(encoding="utf-8")) +if manifest.get("version") != package.get("version"): + raise AssertionError( + f"manifest version {manifest.get('version')!r} != package.json version {package.get('version')!r}" + ) + +# Devin CLI plugins carry skills only (auto-discovered from ./skills/); the +# manifest supports metadata + dependency lists, nothing executable. +unsupported = ["skills", "hooks", "commands", "sessionStart", "contextFileName", "inject"] +present = sorted(field for field in unsupported if field in manifest) +if present: + raise AssertionError("unsupported Devin manifest fields present: " + ", ".join(present)) + +version_config = json.loads((repo_root / ".version-bump.json").read_text(encoding="utf-8")) +entries = version_config.get("files") +if not isinstance(entries, list) or not any( + entry.get("path") == ".devin-plugin/plugin.json" and entry.get("field") == "version" + for entry in entries + if isinstance(entry, dict) +): + raise AssertionError(".version-bump.json must update .devin-plugin/plugin.json version") + +print("Devin plugin manifest looks good") +PY + +# --- Mapping exists ---------------------------------------------------------- +[ -f "$MAPPING" ] || fail "tool mapping missing at $MAPPING" + +# --- Core action→tool mappings are documented -------------------------------- +for tool in skill run_subagent todo_write ask_user_question; do + grep -q "$tool" "$MAPPING" \ + || fail "mapping does not document the '$tool' tool" +done + +# --- Subagents use the built-in profiles -------------------------------------- +grep -q 'subagent_general' "$MAPPING" \ + || fail "mapping does not document the 'subagent_general' profile" +grep -q 'subagent_explore' "$MAPPING" \ + || fail "mapping does not document the 'subagent_explore' profile" + +# --- SKILL.md Platform Adaptation links the mapping --------------------------- +grep -q "devin-tools.md" "$SKILL" \ + || fail "SKILL.md Platform Adaptation does not reference devin-tools.md" + +echo "PASS: Devin CLI plugin valid (manifest, tool mapping, SKILL.md link)" From d21e171f5738700e05d4bd4cf056eea671c56b0f Mon Sep 17 00:00:00 2001 From: Caio Lopes Date: Mon, 20 Jul 2026 11:37:26 -0300 Subject: [PATCH 098/198] =?UTF-8?q?Drop=20devin-tools.md=20=E2=80=94=20not?= =?UTF-8?q?=20needed=20for=20correct=20operation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Re-ran the clean-session acceptance test with the mapping file and the SKILL.md Platform Adaptation pointer removed: using-superpowers and brainstorming still auto-trigger first, and the full workflow chain (writing-plans, executing-plans, TDD, verification) resolves every action to Devin's native tools. Devin CLI's own system prompt already documents its tools (skill invocation, subagent profiles, todo tracking, question prompts), so the mapping was redundant. Test now validates the manifest only. --- skills/using-superpowers/SKILL.md | 1 - .../references/devin-tools.md | 18 ---------- tests/devin/test-devin-plugin.sh | 36 ++++--------------- 3 files changed, 7 insertions(+), 48 deletions(-) delete mode 100644 skills/using-superpowers/references/devin-tools.md diff --git a/skills/using-superpowers/SKILL.md b/skills/using-superpowers/SKILL.md index ec24a8764..7ab2eb678 100644 --- a/skills/using-superpowers/SKILL.md +++ b/skills/using-superpowers/SKILL.md @@ -57,7 +57,6 @@ If your harness appears here, read its reference file for special instructions: - Pi: `references/pi-tools.md` - Antigravity: `references/antigravity-tools.md` - Hermes Agent: `references/hermes-tools.md` -- Devin CLI: `references/devin-tools.md` ## User Instructions diff --git a/skills/using-superpowers/references/devin-tools.md b/skills/using-superpowers/references/devin-tools.md deleted file mode 100644 index dc40d6331..000000000 --- a/skills/using-superpowers/references/devin-tools.md +++ /dev/null @@ -1,18 +0,0 @@ -# Devin CLI Tool Mapping - -Skills speak in actions ("dispatch a subagent", "create a todo", "read a file"). On Devin CLI these resolve to the tools below. - -| Action skills request | Devin CLI equivalent | -| --- | --- | -| Invoke a skill | The native `skill` tool (skills also appear as `/superpowers:` slash commands) | -| Dispatch a subagent (`Subagent (general-purpose):` template) | `run_subagent` with the `subagent_general` profile; use `subagent_explore` for read-only exploration | -| Task tracking ("create a todo", "mark complete") | `todo_write` | -| Ask the user / present options | `ask_user_question` (native multiple-choice prompts; fall back to plain text in non-interactive mode) | - -## Subagents - -`run_subagent` subagents are stateless and cannot ask clarifying questions — front-load the full context and exact instructions in the task prompt, as the subagent-driven-development templates already do. Run independent tasks in parallel with `is_background: true`; keep dependent tasks sequential. - -## File, shell, and search tools - -Devin CLI exposes native tools for reading, writing, and editing files, running shell commands, and searching (grep/glob). Exact tool names can vary by session mode — use whichever file/shell/search tools your session exposes rather than names remembered from another harness. diff --git a/tests/devin/test-devin-plugin.sh b/tests/devin/test-devin-plugin.sh index 312990d73..16ea31f4d 100755 --- a/tests/devin/test-devin-plugin.sh +++ b/tests/devin/test-devin-plugin.sh @@ -3,25 +3,22 @@ # reads `.devin-plugin/plugin.json` and auto-discovers the co-located `skills/` # directory; Devin CLI surfaces every installed skill's name + description in # the system prompt at session start and invokes them via its native `skill` -# tool, so there is no hook or injector scaffold to test. What IS Devin-specific -# is the manifest and the tool mapping — subagent dispatch via run_subagent -# profiles and task tracking via todo_write — and SKILL.md pointing at it. +# tool, and its system prompt already documents its own tools (subagent +# profiles, todo tracking, question prompts), so there is no hook, injector, +# or tool-mapping scaffold to test. What IS Devin-specific is the manifest. # -# Mirrors tests/kimi/test-plugin-manifest.sh (manifest) and -# tests/antigravity/test-antigravity-tools.sh (mapping). CI-safe: does not -# require `devin` installed. +# Mirrors tests/kimi/test-plugin-manifest.sh. CI-safe: does not require +# `devin` installed. set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" MANIFEST="$REPO_ROOT/.devin-plugin/plugin.json" -MAPPING="$REPO_ROOT/skills/using-superpowers/references/devin-tools.md" -SKILL="$REPO_ROOT/skills/using-superpowers/SKILL.md" fail() { echo "FAIL: $*" >&2; exit 1; } -echo "test-devin-plugin: checking Devin CLI manifest and tool mapping" +echo "test-devin-plugin: checking Devin CLI manifest" # --- Manifest is valid and matches the repo version ------------------------- [ -f "$MANIFEST" ] || fail "manifest missing at $MANIFEST" @@ -63,23 +60,4 @@ if not isinstance(entries, list) or not any( print("Devin plugin manifest looks good") PY -# --- Mapping exists ---------------------------------------------------------- -[ -f "$MAPPING" ] || fail "tool mapping missing at $MAPPING" - -# --- Core action→tool mappings are documented -------------------------------- -for tool in skill run_subagent todo_write ask_user_question; do - grep -q "$tool" "$MAPPING" \ - || fail "mapping does not document the '$tool' tool" -done - -# --- Subagents use the built-in profiles -------------------------------------- -grep -q 'subagent_general' "$MAPPING" \ - || fail "mapping does not document the 'subagent_general' profile" -grep -q 'subagent_explore' "$MAPPING" \ - || fail "mapping does not document the 'subagent_explore' profile" - -# --- SKILL.md Platform Adaptation links the mapping --------------------------- -grep -q "devin-tools.md" "$SKILL" \ - || fail "SKILL.md Platform Adaptation does not reference devin-tools.md" - -echo "PASS: Devin CLI plugin valid (manifest, tool mapping, SKILL.md link)" +echo "PASS: Devin CLI plugin valid (manifest)" From 824aabcb2172c2063aa3550cfc446027ee81570d Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Fri, 7 Aug 2026 16:57:42 -0700 Subject: [PATCH 099/198] docs: streamline README getting started navigation Remove the redundant Quickstart entry and section now that the README has a table of contents. Rename the Installation label in the table of contents to Getting Started while retaining the existing installation anchor and section heading. --- README.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/README.md b/README.md index 652819a96..0e44a9ea5 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,9 @@ Superpowers is a complete software development methodology for your coding agent ## Table of Contents -- [Quickstart](#quickstart) - [How it works](#how-it-works) - [Commercial Services](#commercial-services) -- [Installation](#installation) +- [Getting Started](#installation) - [Claude Code](#claude-code) - [Antigravity](#antigravity) - [Codex App](#codex-app) @@ -30,10 +29,6 @@ Superpowers is a complete software development methodology for your coding agent - [License](#license) - [Visual companion telemetry](#visual-companion-telemetry) -## Quickstart - -Give your agent Superpowers: [Claude Code](#claude-code), [Antigravity](#antigravity), [Codex App](#codex-app), [Codex CLI](#codex-cli), [Cursor](#cursor), [Devin CLI](#devin-cli), [Factory Droid](#factory-droid), [Gemini CLI](#gemini-cli), [GitHub Copilot CLI](#github-copilot-cli), [Grok Build CLI](#grok-build-cli), [Hermes Agent](#hermes-agent), [Kimi Code](#kimi-code), [OpenCode](#opencode), [Pi](#pi). - ## How it works It starts from the moment you fire up your coding agent. As soon as it sees that you're building something, it *doesn't* just jump into trying to write code. Instead, it steps back and asks you what you're really trying to do. From 034958f842a174077e1900345c958063f4595f95 Mon Sep 17 00:00:00 2001 From: Drew Ritter Date: Fri, 7 Aug 2026 16:59:38 -0700 Subject: [PATCH 100/198] docs: keep Hermes in installation navigation Add Hermes Agent to the installation entries in the table of contents. The removed Quickstart section was the README's only direct link to that existing installation section, so preserving the link avoids a navigation regression. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0e44a9ea5..09a91c6d0 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Superpowers is a complete software development methodology for your coding agent - [Kimi Code](#kimi-code) - [OpenCode](#opencode) - [Pi](#pi) + - [Hermes Agent](#hermes-agent) - [The Basic Workflow](#the-basic-workflow) - [Community](#community) - [What's Inside](#whats-inside) From a45ede8ddc0e0545a788868c83814b9d01fbf312 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Fri, 7 Aug 2026 18:44:56 -0700 Subject: [PATCH 101/198] feat(tdd): the project's suite defines green, not just your test file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit At the Verify GREEN moment, redefine "other tests still pass": run the project's test command even when the task named only one test file — a scope statement bounds the deliverable, not the verification — and any failure seen goes in the report by name. In a pre-registered 24-rep battery on an adjacent-breakage probe, controls ran the wider suite in 1/12 sessions; with this text, 8/12 (sonnet 4/4, kimi 3/4, glm 1/4), and every session that saw the failure reported it. Claude-Session: https://claude.ai/code/session_0185AJr98gHx5EmwqNeft4Sy --- skills/test-driven-development/SKILL.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/skills/test-driven-development/SKILL.md b/skills/test-driven-development/SKILL.md index 4320d8879..46838cc9e 100644 --- a/skills/test-driven-development/SKILL.md +++ b/skills/test-driven-development/SKILL.md @@ -182,6 +182,16 @@ Confirm: **Other tests fail?** Fix now. +**"Other tests" means the project's suite, not just your file.** A +green run of the test you wrote is not a green suite. Before you call +the change done, run the project's test command (bare `pytest`, +`npm test`, `cargo test` — whatever the repo uses) even when your task +named only one test file. A scope statement in your task bounds the +deliverable, not your verification. Any failure that run shows — +including one you didn't cause — goes in your report by name; a red +test you watched scroll past and didn't mention is a report falsified +by omission. + ### REFACTOR - Clean Up After green only: From 89d36fe961a75f6fbc950b963d64e1aac3dc1732 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 12 Aug 2026 04:50:23 +0000 Subject: [PATCH 102/198] docs: release notes for v6.3.0 --- RELEASE-NOTES.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index 46c51e38d..8b01918c9 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -1,5 +1,44 @@ # Superpowers Release Notes +## v6.3.0 (2026-08-12) + +### Harness Support + +- **Devin CLI**: `devin plugins install obra/superpowers` now works, and skills auto-trigger at session start. (#1995) +- **Hermes Agent**: install from a git clone; skills register with Hermes' native loader and the bootstrap loads on the first turn. (#1922, #2025) +- **Grok Build CLI** added to the install docs. (#1919) + +### Brainstorming + +- **Ceremony now scales to the task.** Requests are classified as spike, bounded, or architectural; small tasks skip the two-document ritual. Every path still stops for your approval before implementation. (#2063) + +### Subagent-Driven Development + +- **Controllers no longer stall on plan conflicts.** Non-catastrophic conflicts and ambiguities get a recorded ruling and work continues; only destructive or irreversible actions still stop for a human. One donated session had sat blocked for almost nine hours on a question the controller could have decided. (#2077) +- **The pre-dispatch conflict scan records its checks in the ledger** instead of just asserting the plan is clean. (#2080) +- **Small same-shape tasks batch into one dispatch**, cutting subagent cost sharply on micro-task plans; batch reviews verify every file in the brief made it into the diff. (#2078) +- **Implementers and reviewers may not spawn their own subagents**, which was producing duplicate reviews. (#2059) +- **Plans carry a `Spec:` pointer** and SDD reads the spec at setup, so plan conflicts get resolved against the design instead of guessed at. (#2086) +- Reviewers re-read evidence they find illegible instead of re-running the test suite (#2089), and circuit-breaker rulings now show up in the Finish report. + +### Codex + +- Subagent waits are event-driven instead of poll-heavy, spawns pin model and reasoning effort explicitly, and the multi-agent reference is corrected against Codex source. (#2060, #2061, #2062) + +### Finishing a Development Branch + +- **Worktree removal no longer destroys untracked files.** When `git worktree remove` refuses because the tree holds uncommitted work, the skill stops, names the files, and asks — instead of reaching for `--force`. (#2016, #1223, #2024) + +### Fixes + +- `render-graphs.js` in writing-skills works on Windows. +- Corrected Copilot CLI backgrounding guidance for Windows. (#1929, #2006) +- `bump-version.sh` covers the Hermes manifest. + +### Documentation + +- README: added a table of contents and reorganized Getting Started. + ## v6.2.0 (2026-07-23) ### Subagent-Driven Development From d4e3c1cb8c3344e567085594bfa2caee17779a37 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 12 Aug 2026 05:04:54 +0000 Subject: [PATCH 103/198] chore: bump version to 6.3.0 --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- .devin-plugin/plugin.json | 2 +- .hermes-plugin/plugin.yaml | 2 +- .kimi-plugin/plugin.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index e058f5e44..f85d3464b 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ { "name": "superpowers", "description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.2.0", + "version": "6.3.0", "source": "./", "author": { "name": "Jesse Vincent", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 5ec90b5e3..7e0c66154 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "superpowers", "description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.2.0", + "version": "6.3.0", "author": { "name": "Jesse Vincent", "email": "jesse@fsck.com" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index c777f316f..123793e54 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.2.0", + "version": "6.3.0", "description": "An agentic skills framework & software development methodology that works: planning, TDD, debugging, and collaboration workflows.", "author": { "name": "Jesse Vincent", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 0902be0e6..bb2bdbcd1 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -2,7 +2,7 @@ "name": "superpowers", "displayName": "Superpowers", "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.2.0", + "version": "6.3.0", "author": { "name": "Jesse Vincent", "email": "jesse@fsck.com" diff --git a/.devin-plugin/plugin.json b/.devin-plugin/plugin.json index 5299cca82..8b68f28e4 100644 --- a/.devin-plugin/plugin.json +++ b/.devin-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.2.0", + "version": "6.3.0", "description": "An agentic skills framework & software development methodology that works: planning, TDD, debugging, and collaboration workflows.", "author": { "name": "Jesse Vincent", diff --git a/.hermes-plugin/plugin.yaml b/.hermes-plugin/plugin.yaml index 78f76e8bb..3a0ecfb21 100644 --- a/.hermes-plugin/plugin.yaml +++ b/.hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: superpowers -version: 6.2.0 +version: 6.3.0 description: Superpowers skills and workflow bootstrap for Hermes Agent author: obra provides_hooks: diff --git a/.kimi-plugin/plugin.json b/.kimi-plugin/plugin.json index 55933e34a..dcb9a7a9b 100644 --- a/.kimi-plugin/plugin.json +++ b/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.2.0", + "version": "6.3.0", "description": "An agentic skills framework and software development methodology.", "author": { "name": "Jesse Vincent", diff --git a/gemini-extension.json b/gemini-extension.json index 01378c982..ccb77ae21 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "superpowers", "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.2.0", + "version": "6.3.0", "contextFileName": "GEMINI.md" } diff --git a/package.json b/package.json index c24b3721d..3a84ce88c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.2.0", + "version": "6.3.0", "description": "Superpowers skills and runtime bootstrap for coding agents", "type": "module", "main": ".opencode/plugins/superpowers.js", From fd02874aa5c55ba3c2bca431253b48e0e4c8be5a Mon Sep 17 00:00:00 2001 From: Kattni Date: Wed, 12 Aug 2026 18:31:42 -0400 Subject: [PATCH 104/198] Update to Prime Radiant Community Code of Conduct. (#2122) --- CODE_OF_CONDUCT.md | 216 +++++++++++++++++++++++---------------------- 1 file changed, 109 insertions(+), 107 deletions(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index f6422545a..b8af8cdf9 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,128 +1,130 @@ -# Contributor Covenant Code of Conduct +# Prime Radiant Community Code of Conduct ## Our Pledge -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. +We pledge to make our community welcoming, safe, and equitable for all. -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. +We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant. -## Our Standards +The guidelines within and enforcement of the Prime Radiant Community Code of Conduct apply equally to everyone participating in the Prime Radiant community, including members of the Prime Radiant team. -Examples of behavior that contributes to a positive environment for our -community include: +## Encouraged Behaviors -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community +While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language. -Examples of unacceptable behavior include: +With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including: -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting +1. Respecting the **purpose of our community**, our activities, and our ways of gathering. +2. Engaging **kindly and honestly** with others. +3. Respecting **different viewpoints** and experiences. +4. **Taking responsibility** for our actions and contributions. +5. Gracefully giving and accepting **constructive feedback**. +6. Committing to **repairing harm** when it occurs. +7. Behaving in other ways that promote and sustain the **well-being of our community**. -## Enforcement Responsibilities +## Restricted Behaviors -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. +We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct. -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. +1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop. +2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people. +3. **Inciting conflict.** Deliberately engaging in discussions meant to cause arguments or a hostile environment. +4. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits. +5. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community. +6. **Violating confidentiality.** Sharing or acting on someone's personal or private information without their permission. +7. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group. +8. Behaving in other ways that **threaten the well-being** of our community. + +### Other Restrictions + +1. **Divisive topics.** Discussing inflammatory topics that are unrelated to the community as a whole. +2. **Offensive content.** Any text or image that is offensive or violates any of the other restricted behaviors, including as part of a username, profile, status, avatar, or other publicly displayed identifier. +3. **Misleading identity.** Impersonating someone else for any reason, misrepresenting yourself as associated with Prime Radiant or any company, or pretending to be someone else to evade enforcement actions. +4. **Failing to credit sources.** Not properly crediting the sources of content you contribute, or representing work created by someone else as your own. +5. **Advertising and promotional materials.** Sharing marketing or other commercial content, invite links, or irrelevant self-promotion, as well as buying, trading, or asking for donations. +6. **Spam posts.** Spamming, including, but not limited to, posting a flood of messages in a short period of time, irrelevant content, or excessive links. +7. **Unsolicited mentions and direct messages.** Engaging in harassment by excessively mentioning someone by username or replying, or direct messaging someone without explicit invitation. +8. **Irresponsible communication.** Failing to responsibly present content which includes, links, or describes any other restricted behaviors. +9. Other conduct that could reasonably be considered **unprofessional** or **inappropriate**. + +## Reporting an Issue + +Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm. You are welcome to report concerns, even if they seem minor, as they can be helpful in identifying patterns of behavior that may not be concerning in isolation, but when viewed collectively may be more significant. + +When an incident does occur, it is important to report it promptly. To report a possible violation anywhere in the community, email [conduct@primeradiant.com](mailto:conduct@primeradiant.com). On the Prime Radiant Discord server, you can mention `@moderators` in a public channel, or report via a support ticket, created through the `#support-ticket` channel. In the event that you need to report a member of the Prime Radiant team, you can contact Kattni at [kattni@primeradiant.com](mailto:kattni@primeradiant.com) or Drew at [drew@primeradiant.com](mailto:drew@primeradiant.com). + +Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution. If moderators determine that a public statement needs to be made, the identities of all victims and reporters will remain confidential unless those individuals instruct otherwise. + +In your report, please include: + +- **Your contact info** so the team can get in touch with you if they need to follow up. +- **Names (real, nicknames, or pseudonyms) of any individuals involved.** If there were other witnesses besides you, please try to include them as well. +- **When and where the incident occurred.** Please be as specific as possible. +- **Your account of what occurred.** If there is a publicly available record (e.g. a Discord or GitHub message) please include a link. +- **Any extra context** you believe existed for the incident. +- **If you believe this incident is ongoing.** +- **If you believe any member of the team has a conflict of interest** in adjudicating the incident. +- **What, if any, corrective response** you believe would be appropriate. +- **Any other information** you believe the team should have. + +Moderators are obligated to maintain confidentiality with regard to the reporter and details of an incident. + +## Report Followup + +You will receive a response acknowledging receipt of your report within 24 business hours. + +If a member of the team is one of the named parties, they will not be included in any discussions, and will not be provided with any confidential details from the reporter. + +If anyone on the moderation team believes they have a conflict of interest in adjudicating on a reported issue, they will inform the other team members, and recuse themselves from any discussion about the issue. Following this declaration, they will not be provided with any confidential details from the reporter. + +The team will immediately review the incident and determine: + +- What happened. +- Whether this event constitutes a code of conduct violation. +- Who the reported person is. +- Whether this is an ongoing situation, or if there is a threat to anyone's physical safety. + +If this is determined to be an ongoing incident or a threat to physical safety, the team's immediate priority will be to protect everyone involved. This means they may delay an official response until they believe that the situation has concluded and that everyone is physically safe. + +The moderation team will respond within one week to the person who filed the report with either a resolution or an explanation of why the situation is not yet resolved. + +Once the team has determined their final action, they'll contact the reporter to let them know what action (if any) they'll be taking. They'll take into account feedback from the reporter on the appropriateness of the response, but do not guarantee they'll act on it. + +Finally, to maintain transparency in the reporting and enforcement process, whenever possible, a public transparency report of the incident will be made. A public report may not be made if the specifics of the incident do not allow the team to preserve anonymity, or if there is potential for ongoing harm. + +## Addressing and Repairing Harm + +If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped. + +1) Warning + 1) Event: A violation involving a single incident or series of incidents. + 2) Consequence: A private, written warning from the Community Moderators. + 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations. +2) Temporarily Limited Activities + 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation. + 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members. + 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over. +3) Temporary Suspension + 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation. + 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions. + 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted. +4) Permanent Ban + 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member. + 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior. + 3) Repair: There is no possible repair in cases of this severity. + +This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community. ## Scope -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. +This Code of Conduct applies within all community spaces, including GitHub and the Prime Radiant Discord server. It also applies when an individual is officially representing the community in public or other spaces. Examples of representing the community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -jesse@primeradiant.com. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. +Behavior outside of official Prime Radiant spaces may also be considered as supporting evidence for a report if that behavior establishes a pattern, or represents a potential risk to the Prime Radiant community. ## Attribution -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. +This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/). -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). +Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/) -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. +For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion). From bac79da8f13694ebcffe3c361139bea2a1c205fc Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Wed, 12 Aug 2026 23:35:41 +0000 Subject: [PATCH 105/198] docs: add Qwen Code install instructions to README Rebased from PR #2108 onto the reworked README. Differences from the PR: the Hermes TOC entry and Quickstart-line changes are obsolete (the v6.3.0 README rework already added the former and removed the latter), and the Hermes post-compaction caveat stays: .hermes-plugin injects the bootstrap only on is_first_turn, so the caveat is still accurate. Install/update commands and the acceptance transcript are from PR #2108 (@arittr, tested interactively on Qwen Code). Co-authored-by: Drew Ritter --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 09a91c6d0..482b9c36f 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Superpowers is a complete software development methodology for your coding agent - [Kimi Code](#kimi-code) - [OpenCode](#opencode) - [Pi](#pi) + - [Qwen Code](#qwen-code) - [Hermes Agent](#hermes-agent) - [The Basic Workflow](#the-basic-workflow) - [Community](#community) @@ -246,6 +247,22 @@ pi -e /path/to/superpowers The Pi package loads the Superpowers skills and a small extension that injects the `using-superpowers` bootstrap at session startup and again after compaction. Pi has native skills, so no compatibility `Skill` tool is required. Subagent and task-list tools remain optional Pi companion packages. +### Qwen Code + +Qwen Code installs plugins from Claude Code marketplaces directly. + +- Install the plugin from this repository, and pick `superpowers` when prompted: + + ```bash + qwen extensions install obra/superpowers + ``` + +- Update later: + + ```bash + qwen extensions update superpowers + ``` + ### Hermes Agent Install Superpowers as a Hermes plugin from this repository: From 2a500febcc10a07f24df8b72452156a16f277600 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 13 Aug 2026 00:26:43 +0000 Subject: [PATCH 106/198] fix(requesting-code-review): anchor the multi-commit BASE_SHA alternative to the merge base The '# or origin/main' alternative fed a moving ref into the reviewer's two-dot diff: once origin/main advances past the branch point, main's new files appear as phantom deletions the reviewer can't distinguish from real ones. Reproduced during triage (2026-08-12): a scratch repo with main advanced one commit shows 'main-new.txt | 1 -' in the branch's diff. git merge-base origin/main HEAD anchors the range to the branch point, matching how sdd's review-package already computes BASE. Reported in #2118 (wan-huiyan). Fixes #2118. --- skills/requesting-code-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/requesting-code-review/SKILL.md b/skills/requesting-code-review/SKILL.md index fa4f2f996..6d995da5c 100644 --- a/skills/requesting-code-review/SKILL.md +++ b/skills/requesting-code-review/SKILL.md @@ -25,7 +25,7 @@ Dispatch a code reviewer subagent to catch issues before they cascade. The revie **1. Get git SHAs:** ```bash -BASE_SHA=$(git rev-parse HEAD~1) # or origin/main +BASE_SHA=$(git rev-parse HEAD~1) # or: git merge-base origin/main HEAD HEAD_SHA=$(git rev-parse HEAD) ``` From 0be49879b1c51a479d2013a14fe42ed9bd10ce32 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 13 Aug 2026 00:27:52 +0000 Subject: [PATCH 107/198] fix(sdd): invoke sdd-workspace via bash so helpers survive stripped exec bits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex marketplace users hit 'Permission denied' running SDD helpers: some extractors (Python zipfile) discard Unix mode attributes when unpacking the package, so task-brief's and review-package's direct exec of their sibling sdd-workspace fails. Our packaging preserves 0755 (git archive | tar -xpf, asserted by the existing packaging test) — the bits are lost on the consumer side, which no packaging change can reach. Invoking the sibling via "${BASH:-bash}" makes the exec bit irrelevant. TDD: new regression case copies the helpers, chmod -x, runs task-brief via bash — RED with the reported rc=126 Permission denied, GREEN after. Reported in #2040 (michaelholcomb-creator). Fixes #2040. --- .../scripts/review-package | 4 +++- .../scripts/task-brief | 4 +++- tests/claude-code/test-sdd-workspace.sh | 15 +++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/skills/subagent-driven-development/scripts/review-package b/skills/subagent-driven-development/scripts/review-package index 31852e2ab..c7ce1ef47 100755 --- a/skills/subagent-driven-development/scripts/review-package +++ b/skills/subagent-driven-development/scripts/review-package @@ -25,7 +25,9 @@ git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >& if [ $# -eq 4 ]; then out=$4 else - dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan") + # Invoke via bash rather than direct exec: some extractors (Python zipfile) + # strip Unix exec bits when unpacking marketplace packages (#2040). + dir=$("${BASH:-bash}" "$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan") out="$dir/review-$(git rev-parse --short "$base")..$(git rev-parse --short "$head").diff" fi diff --git a/skills/subagent-driven-development/scripts/task-brief b/skills/subagent-driven-development/scripts/task-brief index 612e14a1e..b49fc546c 100755 --- a/skills/subagent-driven-development/scripts/task-brief +++ b/skills/subagent-driven-development/scripts/task-brief @@ -21,7 +21,9 @@ n=$2 if [ $# -eq 3 ]; then out=$3 else - dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan") + # Invoke via bash rather than direct exec: some extractors (Python zipfile) + # strip Unix exec bits when unpacking marketplace packages (#2040). + dir=$("${BASH:-bash}" "$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan") out="$dir/task-${n}-brief.md" fi diff --git a/tests/claude-code/test-sdd-workspace.sh b/tests/claude-code/test-sdd-workspace.sh index 841723016..86576df52 100755 --- a/tests/claude-code/test-sdd-workspace.sh +++ b/tests/claude-code/test-sdd-workspace.sh @@ -189,6 +189,21 @@ PLAN echo " status: $wt_status" fi + # --- helpers survive a mode-stripping extractor dropping exec bits (#2040) --- + local stripped="$TEST_ROOT/stripped-scripts" + mkdir -p "$stripped" + cp "$SDD_SCRIPTS/sdd-workspace" "$SDD_SCRIPTS/task-brief" "$SDD_SCRIPTS/review-package" "$stripped/" + chmod -x "$stripped"/* + local noexec_out noexec_rc=0 + noexec_out="$(cd "$repo" && bash "$stripped/task-brief" plan-b.md 1 2>&1)" || noexec_rc=$? + if [[ "$noexec_rc" -eq 0 && -f "$repo/.superpowers/sdd/plan-b/task-1-brief.md" ]]; then + pass "task-brief works with no exec bit on sdd-workspace" + else + fail "task-brief works with no exec bit on sdd-workspace" + echo " rc: $noexec_rc" + echo " output: $noexec_out" + fi + echo "" if [[ "$FAILURES" -ne 0 ]]; then echo "FAILED: $FAILURES assertion(s)." From 99f9f00869e3e774e9abe9a29ccfccb8957ec5da Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Thu, 13 Aug 2026 00:29:29 +0000 Subject: [PATCH 108/198] fix(sdd): reject empty or non-descendant BASE..HEAD ranges in review-package MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When an SDD implementer commits to the wrong branch (#2050), the BASE..HEAD range handed to review-package is either empty or not rooted at BASE. Both cases previously produced a review package silently — an empty one lets the reviewer approve "clean" work that isn't there. Add two mechanical guards after BASE/HEAD validation, exiting 3 (vs 2 for usage errors) so callers can distinguish range problems: - git merge-base --is-ancestor BASE HEAD, else "HEAD is not a descendant of BASE" - git rev-list --count BASE..HEAD > 0, else "empty commit range" Guard shape credits the analysis in closed PR #2082 by @stantheman0128. Fixes #2050 --- .../scripts/review-package | 5 ++++ tests/claude-code/test-sdd-workspace.sh | 24 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/skills/subagent-driven-development/scripts/review-package b/skills/subagent-driven-development/scripts/review-package index 31852e2ab..7af8dbe4d 100755 --- a/skills/subagent-driven-development/scripts/review-package +++ b/skills/subagent-driven-development/scripts/review-package @@ -22,6 +22,11 @@ head=$3 git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; } git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; } +# Range guards (exit 3): a wrong-branch HEAD yields a range that is empty or +# not rooted at BASE; either would silently produce a bogus review package. +git merge-base --is-ancestor "$base" "$head" || { echo "HEAD is not a descendant of BASE: ${base}..${head}" >&2; exit 3; } +[ "$(git rev-list --count "${base}..${head}")" -gt 0 ] || { echo "empty commit range: ${base}..${head}" >&2; exit 3; } + if [ $# -eq 4 ]; then out=$4 else diff --git a/tests/claude-code/test-sdd-workspace.sh b/tests/claude-code/test-sdd-workspace.sh index 841723016..681cba08a 100755 --- a/tests/claude-code/test-sdd-workspace.sh +++ b/tests/claude-code/test-sdd-workspace.sh @@ -165,6 +165,30 @@ PLAN echo " got: $rp_explicit" fi + # --- range guards: BASE must be an ancestor of HEAD, range must be non-empty --- + local divergent + divergent="$(cd "$repo" && git "${git_id[@]}" commit-tree 'HEAD~1^{tree}' -p 'HEAD~1' -m divergent)" + rc=0 + local guard_err + guard_err="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md "$divergent" HEAD 2>&1 >/dev/null)" || rc=$? + if [[ "$rc" -eq 3 && "$guard_err" == *"not a descendant"* ]]; then + pass "review-package rejects a BASE that is not an ancestor of HEAD with exit 3" + else + fail "review-package rejects a BASE that is not an ancestor of HEAD with exit 3" + echo " exit: $rc" + echo " stderr: $guard_err" + fi + + rc=0 + guard_err="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD HEAD 2>&1 >/dev/null)" || rc=$? + if [[ "$rc" -eq 3 && "$guard_err" == *"empty commit range"* ]]; then + pass "review-package rejects an empty BASE..HEAD range with exit 3" + else + fail "review-package rejects an empty BASE..HEAD range with exit 3" + echo " exit: $rc" + echo " stderr: $guard_err" + fi + # --- Worktree isolation: a linked worktree resolves its own workspace --- local wt="$TEST_ROOT/wt" ( cd "$repo" && git worktree add -q "$wt" -b wt-feature ) From 6e31f3f7dba400468354e31de8e74d6e9729f70c Mon Sep 17 00:00:00 2001 From: GoldJohnKing Date: Tue, 18 Aug 2026 20:58:47 +0800 Subject: [PATCH 109/198] fix(opencode): adapt to V2 skill draft API removal (#2106) OpenCode V2 removed SkillDraft.source() in 1113adfd5e (#41622): the skill service now stores values only, and filesystem scanning moved to the config side. The plugin's draft.source({type:'directory'}) call threw 'draft.source is not a function', which killed the entire V2 plugin activation generation. Because V2 gates model.list on PluginSupervisor.flush (23b0688a7f, #41783), that failure left flush pending forever and the TUI showed no providers or models ('Model catalog initialization timed out', /api/model 503). Register each skills//SKILL.md as a native Skill.Info object via draft.add({id, name, description, location, content}) instead, matching the {list, add, update, remove} draft API and the pattern used by V2's built-in skill plugin. Wrap skill registration, hook registration, and the context hook callback in try/catch so a future V2 API change degrades to a logged error instead of taking down the whole generation again. session.hook('context') payload shape is unchanged and keeps working. Verified end-to-end on opencode2 v0.0.0-beta-17595: 24 skills listed via /api/skill (all superpowers skills present), /api/model returns 83 models across 3 providers, no 'failed to reload plugins' in server logs. V1 path untouched. --- .opencode/plugins/superpowers.js | 65 ++++++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 16 deletions(-) diff --git a/.opencode/plugins/superpowers.js b/.opencode/plugins/superpowers.js index 557e3c20e..e547e8716 100644 --- a/.opencode/plugins/superpowers.js +++ b/.opencode/plugins/superpowers.js @@ -142,31 +142,64 @@ export const SuperpowersPlugin = async ({ client, directory }) => { /** * V2 Setup Function (default.setup) * - * Called by V2 PluginSupervisor (packages/core/src/plugin/). + * Called by V2 PluginSupervisor (packages/core/src/plugin/supervisor.ts). * Performs two things: * - * 1. Registers the skills directory natively via ctx.skill.transform(). + * 1. Registers every skills//SKILL.md as a native Skill.Info object + * via ctx.skill.transform((draft) => draft.add(info)). + * V2 removed the old draft.source() directory registration; the draft API + * is now { list, add, update, remove } where add() decodes plain objects: + * { id, name, description?, slash?, autoinvoke?, location, content }. + * See packages/core/src/plugin/skill.ts and packages/schema/src/skill.ts. * 2. Injects bootstrap context via ctx.session.hook("context"), the V2 * equivalent of V1's experimental.chat.messages.transform. */ async function setup(ctx) { - // 1. Register skills - await ctx.skill.transform((draft) => { - draft.source({ - type: 'directory', - path: superpowersSkillsDir, + // 1. Register skills (one transform; one draft.add per skill) + try { + const skills = []; + if (fs.existsSync(superpowersSkillsDir)) { + for (const entry of fs.readdirSync(superpowersSkillsDir, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name.startsWith('.')) continue; + const skillPath = path.join(superpowersSkillsDir, entry.name, 'SKILL.md'); + if (!fs.existsSync(skillPath)) continue; + const { frontmatter, content } = extractAndStripFrontmatter(fs.readFileSync(skillPath, 'utf8')); + skills.push({ + id: entry.name, + name: frontmatter.name || entry.name, + ...(frontmatter.description ? { description: frontmatter.description } : {}), + location: skillPath, + content, + }); + } + } + await ctx.skill.transform((draft) => { + for (const skill of skills) draft.add(skill); }); - }); + } catch (err) { + // Never break plugin activation: one failing plugin takes down the whole + // V2 generation (including provider/catalog plugins => no models in TUI). + console.error('[superpowers] skill registration failed:', err); + } // 2. Inject bootstrap into first user message via V2 session context hook - await ctx.session.hook('context', (event) => { - const bootstrap = getBootstrapContent(); - if (!bootstrap || !event.messages || !event.messages.length) return; - const firstUser = event.messages.find(m => m.role === 'user'); - if (!firstUser || !firstUser.content || !firstUser.content.length) return; - if (firstUser.content.some(p => p.type === 'text' && p.text && p.text.includes('EXTREMELY_IMPORTANT'))) return; - firstUser.content.unshift({ type: 'text', text: bootstrap }); - }); + try { + await ctx.session.hook('context', (event) => { + try { + const bootstrap = getBootstrapContent(); + if (!bootstrap || !event.messages || !event.messages.length) return; + const firstUser = event.messages.find(m => m.role === 'user'); + if (!firstUser || !firstUser.content || !firstUser.content.length) return; + if (firstUser.content.some(p => p.type === 'text' && p.text && p.text.includes('EXTREMELY_IMPORTANT'))) return; + firstUser.content.unshift({ type: 'text', text: bootstrap }); + } catch (err) { + // Never let hook callback errors break the request pipeline. + console.error('[superpowers] context hook failed:', err); + } + }); + } catch (err) { + console.error('[superpowers] session hook registration failed:', err); + } } /** From ca8cb53f46eb42e1c11c6fa221855165bebbdce8 Mon Sep 17 00:00:00 2001 From: GoldJohnKing Date: Tue, 18 Aug 2026 21:27:47 +0800 Subject: [PATCH 110/198] fix(opencode): skip V2 setup when V1 invokes it with a V1-shaped ctx opencode 1.18.18 also calls default.setup, but with a ctx that lacks the skill/session domains, so the defensive try/catch logged a TypeError into every V1 session transcript even though V1 is fully served by the SuperpowersPlugin named export. Detect the V1 shape and return quietly. --- .opencode/plugins/superpowers.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.opencode/plugins/superpowers.js b/.opencode/plugins/superpowers.js index e547e8716..223e727ec 100644 --- a/.opencode/plugins/superpowers.js +++ b/.opencode/plugins/superpowers.js @@ -155,6 +155,13 @@ export const SuperpowersPlugin = async ({ client, directory }) => { * equivalent of V1's experimental.chat.messages.transform. */ async function setup(ctx) { + // V1 (observed on opencode 1.18.18) also invokes default.setup, but with a + // V1-shaped ctx that lacks the skill/session domains. Detect it and return + // quietly — V1 is served entirely by the SuperpowersPlugin named export. + if (!ctx || !ctx.skill || typeof ctx.skill.transform !== 'function' || !ctx.session || typeof ctx.session.hook !== 'function') { + return; + } + // 1. Register skills (one transform; one draft.add per skill) try { const skills = []; From f6617db1517488d4a8b66925519d5ffbeef965b3 Mon Sep 17 00:00:00 2001 From: Ada Sen Date: Thu, 27 Aug 2026 16:46:48 +0000 Subject: [PATCH 111/198] feat(skills): import proving-it-works-with-a-movie from its standalone repo Brings the proving-it-works-with-a-movie skill (demo/screencast/proof-video recording, plus the check-movie timeline gate that catches frozen pictures, narration drift, and dropped words) into superpowers core, along with its supporting docs, scripts, and shell regression tests. Source: prime-radiant-inc/proving-it-works (MIT, same copyright holder), skills/proving-it-works-with-a-movie/ at time of import. The five scripts (narrate, make-subtitles, assemble, burn-subtitles, check-movie) are self-contained uv --script files with inline PEP 723 dependency declarations, so they port with no new project-level dependency wiring. Test paths were adjusted one directory level to match superpowers' tests// layout (the standalone repo kept tests/ as a top-level sibling of skills/). Adds a Verification entry to README's Skills Library list. Goal: fold this into 6.4 and retire the standalone repo. --- README.md | 3 + skills/proving-it-works-with-a-movie/SKILL.md | 90 ++++++ .../assembling.md | 104 +++++++ .../narrating.md | 90 ++++++ .../recording-a-terminal.md | 90 ++++++ .../recording-motion.md | 118 ++++++++ .../rendering-from-a-log.md | 90 ++++++ .../rendering-stills.md | 50 +++ .../scripts/assemble | 204 +++++++++++++ .../scripts/burn-subtitles | 99 ++++++ .../scripts/check-movie | 261 ++++++++++++++++ .../scripts/make-subtitles | 125 ++++++++ .../scripts/narrate | 284 ++++++++++++++++++ .../test-assemble.sh | 88 ++++++ .../test-check-movie.sh | 105 +++++++ .../test-narrate.sh | 54 ++++ 16 files changed, 1855 insertions(+) create mode 100644 skills/proving-it-works-with-a-movie/SKILL.md create mode 100644 skills/proving-it-works-with-a-movie/assembling.md create mode 100644 skills/proving-it-works-with-a-movie/narrating.md create mode 100644 skills/proving-it-works-with-a-movie/recording-a-terminal.md create mode 100644 skills/proving-it-works-with-a-movie/recording-motion.md create mode 100644 skills/proving-it-works-with-a-movie/rendering-from-a-log.md create mode 100644 skills/proving-it-works-with-a-movie/rendering-stills.md create mode 100755 skills/proving-it-works-with-a-movie/scripts/assemble create mode 100755 skills/proving-it-works-with-a-movie/scripts/burn-subtitles create mode 100755 skills/proving-it-works-with-a-movie/scripts/check-movie create mode 100755 skills/proving-it-works-with-a-movie/scripts/make-subtitles create mode 100755 skills/proving-it-works-with-a-movie/scripts/narrate create mode 100755 tests/proving-it-works-with-a-movie/test-assemble.sh create mode 100755 tests/proving-it-works-with-a-movie/test-check-movie.sh create mode 100755 tests/proving-it-works-with-a-movie/test-narrate.sh diff --git a/README.md b/README.md index 09a91c6d0..0a54eba46 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,9 @@ Superpowers is built by [Jesse Vincent](https://blog.fsck.com) and the rest of t - **systematic-debugging** - 4-phase root cause process (includes root-cause-tracing, defense-in-depth, condition-based-waiting techniques) - **verification-before-completion** - Ensure it's actually fixed +**Verification** +- **proving-it-works-with-a-movie** - Record a demo, screencast, or proof video of software actually running, and catch the silent defects (frozen picture, narration over a dead screen, dropped words) before handing it over + **Collaboration** - **brainstorming** - Socratic design refinement - **writing-plans** - Detailed implementation plans diff --git a/skills/proving-it-works-with-a-movie/SKILL.md b/skills/proving-it-works-with-a-movie/SKILL.md new file mode 100644 index 000000000..58353f29a --- /dev/null +++ b/skills/proving-it-works-with-a-movie/SKILL.md @@ -0,0 +1,90 @@ +--- +name: proving-it-works-with-a-movie +description: Use when asked for a demo, screencast, tutorial, walkthrough, or proof video of software actually running, when a reviewer needs to see a feature work rather than take your word for it, or when handing over any video artifact of app behavior +--- + +# Proving It Works With a Movie + +## Overview + +A movie is evidence. Every way it fails is silent: no crash, no red text, +just an artifact that looks fine to whoever made it and is obviously broken +to the first person who watches it. + +**Core principle: you have not made a movie until you have looked at the +movie.** Not the frames going in. The finished file coming out. + +## Pick the route + +| What you have to show | Route | +|---|---| +| Interaction happening: typing, clicking, a list updating live | Browser-driven motion → recording-motion.md | +| A CLI, a TUI, an install, a test run, an agent working | Terminal → recording-a-terminal.md | +| A sequence of real states, motion optional | Composited stills → rendering-stills.md | +| OS capture blocked (wallpaper-only frames), or the thing to prove is a *run*, not a UI | Reel rendered from the run's own log → rendering-from-a-log.md | + +Stills are a legitimate movie. Reach for motion only when the *motion* is +the claim; it costs several times more to build and is where sync defects +live. + +**Never** mock, stage, or reenact. If a beat can't be shown for real +(no credentials, no data, a 40-minute job), cut it and say why. A movie +that quietly fakes one beat is worthless as evidence for any beat. + +## The gate — every route, before you hand anything over + +```bash +# $SKILL_DIR is this skill's own directory - the "Base directory for this +# skill" path printed when it loads. Installed as a plugin that is +# $CLAUDE_PLUGIN_ROOT/skills/proving-it-works-with-a-movie +"$SKILL_DIR/scripts/narrate" scenes.yaml narration/ # voice, gated +"$SKILL_DIR/scripts/assemble" scenes.yaml silent-cut.mp4 +"$SKILL_DIR/scripts/make-subtitles" narration/manifest.json movie.srt \ + --offsets-json segments/offsets.json +"$SKILL_DIR/scripts/burn-subtitles" silent-cut.mp4 movie.srt movie.mp4 +"$SKILL_DIR/scripts/check-movie" movie.mp4 # nonzero exit: do not ship +``` + +It samples picture and sound on one timeline and fails the movie when the +action is crammed into the first seconds while narration keeps talking, when +the picture never changes, when the audio is silent, or when a narrated +movie has no subtitles (or subtitles that quit before the narration does). It samples the +picture at 1 Hz, so any beat that must register — a flash, a blank frame, a +transition — has to be held longer than a second. Then: + +1. **Open the contact sheet it wrote and actually look at it.** Identical + tiles mean a frozen movie. Unreadable text means your viewport is wrong. +2. **If narrated: transcribe the rendered audio and diff it against your + script.** Not the TTS engine's claim about what it said — the audio in + the finished file. See narrating.md. +3. Fix, regenerate, re-run. Never patch the report instead of the movie. + +## The silent failures + +| What you get | Why it happens | +|---|---| +| Narrator talks over a picture that stopped moving | Sleeps guessed against narration nobody measured | +| A word missing from the narration | Local TTS drops out-of-vocabulary terms with no error | +| "Sure, here it is:" spoken aloud | Chat-model TTS ad-libs; it is not a TTS endpoint | +| Clicks that appear to happen by themselves | Automation draws no cursor | +| Wallpaper, or a blank window | OS screen-recording permission denied; capture "succeeds" | +| A scene missing, error naming a truncated file | `ffmpeg` ate the loop's stdin (`-nostdin`) | +| Your real data mutated | You recorded against the live tree; the movie writes | +| Nothing visibly happens, because nothing visibly *should* | The claim is "state survived" — film the event, not the effect (recording-motion.md) | +| A muted viewer gets nothing | Narration without subtitles. `narrate` + `make-subtitles` produce them; burn them in | + +## Red flags — stop + +- "The frames looked right" → frames are not a timeline. Run the checker. +- "ffprobe says 27 seconds" → duration is not content. +- "The TTS returned 200" → generation is not delivery. Transcribe it. +- "I'll note the glitch in the handover" → regenerate it instead. +- "Close enough to demo" → you are about to hand a reviewer a frozen movie. +- "No API key, so no narration" → `narrate` falls back to a local voice. +- "I'll add subtitles later" → later is after someone watched it muted. + +## Keep the pipeline + +Scene list, narration text, and build scripts are **committed files**, not +scratch. Scratch directories get cleaned mid-production and a movie you +can't rebuild is a movie you can't fix. See assembling.md. diff --git a/skills/proving-it-works-with-a-movie/assembling.md b/skills/proving-it-works-with-a-movie/assembling.md new file mode 100644 index 000000000..a11d0dcbb --- /dev/null +++ b/skills/proving-it-works-with-a-movie/assembling.md @@ -0,0 +1,104 @@ +# Assembling + +Turning clips, stills, and narration into one file — and the ffmpeg traps +that cost the most time. + +## The segment rule + +Per scene, the segment lasts **max(narration, visuals)**. Whichever is +shorter gets padded: + +- video short → freeze the last frame (`tpad=stop_mode=clone`) +- audio short → pad with silence (`apad`) + +```bash +ffmpeg -nostdin -y -v error -i clip.mp4 -i narration.wav \ + -filter_complex "[0:v]tpad=stop_mode=clone:stop_duration=${PAD}[v];[1:a]apad[a]" \ + -map "[v]" -map "[a]" -t "$DUR" -r 30 -pix_fmt yuv420p \ + -c:v libx264 -preset medium -c:a aac -ar 44100 -ac 2 segment.mp4 +``` + +Then concat the segments (`-f concat -safe 0 -c copy`). Uniform codec +parameters across segments are what make the stream-copy concat valid. + +**A long freeze-frame tail is a smell, not a fix.** If a scene's narration +runs 20 seconds past its visuals, the scene is wrong: give the camera +something to do, or cut the words. + +## `-nostdin` on every ffmpeg call inside a loop + +ffmpeg reads stdin by default and will eat the loop's input. + +```bash +while IFS= read -r scene; do + ffmpeg -nostdin ... # without this, ffmpeg swallows the rest of the list +done < scenes.txt +``` + +Symptom when you forget: scenes silently skipped, and an error naming a +*truncated* identifier (`val-landing` for `eval-landing`) because ffmpeg +consumed part of the next line. It reads like a corrupt input file. + +## Title and caption cards: render HTML, screenshot it + +Do not fight `drawtext`. It is the fragile part of ffmpeg — under macOS +sandbox `textfile=` fails outright ("Either text, a valid file, a timecode +or text source must be provided") even with absolute paths. Write the card +as HTML, screenshot it in the browser you already have open, and treat it as +an image. You get real fonts, CSS layout, and markup accents for free. + +Name cards so a lexical glob orders them: `card-00` (title), `card-01..NN` +(scenes), `card-99` (end). + +```bash +ffmpeg -nostdin -y -v error -framerate 1/3 -pattern_type glob -i 'card-*.png' \ + -r 30 -pix_fmt yuv420p out.mp4 # 1/3 = each card holds 3s +``` + +## Burn the subtitles in + +Subtitles are on by default; the checker fails a narrated movie without +them. Burn them into the picture so they survive being dropped into Slack, +a PR comment, or a phone — and keep the `.srt` beside the movie as the +sidecar the checker reads (and as the searchable transcript). + +```bash +scripts/make-subtitles narration/manifest.json movie.srt +scripts/burn-subtitles silent-cut.mp4 movie.srt movie.mp4 +``` + +Burn them at the *end*, over the assembled cut, so cue timings line up with +the final timeline rather than per-segment offsets. + +Two traps the script exists to absorb: + +- **Burning needs libass, and many ffmpeg builds lack it.** Homebrew's + default macOS ffmpeg has no `subtitles` filter at all; Debian's has it. + `burn-subtitles` checks, and falls back to an embedded soft track with a + loud note rather than pretending it burned anything. +- **ffmpeg 8 removed positional filter options.** `subtitles=movie.srt` + parses on 5.x and fails on 8.x with "No option name near". Write + `subtitles=filename=movie.srt`, which works on both. + +`Fontsize` is in points against the video height — check it on the contact +sheet, because a size that reads fine at 2560px wide is unreadable when the +movie is watched in a 400px-wide PR preview. + +## Verify the encode, then verify the content + +```bash +ffprobe -v error -show_entries format=duration,size \ + -show_entries stream=codec_name,width,height -of default=noprint_wrappers=1 out.mp4 +``` + +`ffprobe` proves the container is real. It says nothing about whether the +movie is watchable — that is `check-movie` plus your own eyes on the contact +sheet. + +## Keep the pipeline out of scratch + +Scene list, narration text, recorder, narrate and assemble scripts belong in +the repo. Scratch directories are cleaned by the OS between sessions; losing +the assembler mid-production means reconstructing it from prose before you +can re-cut a single scene. Ask before committing large media; the *pipeline* +is small and always worth committing. diff --git a/skills/proving-it-works-with-a-movie/narrating.md b/skills/proving-it-works-with-a-movie/narrating.md new file mode 100644 index 000000000..accfa2109 --- /dev/null +++ b/skills/proving-it-works-with-a-movie/narrating.md @@ -0,0 +1,90 @@ +# Narrating + +Narration is where the most embarrassing silent failures live: the movie +looks perfect and says the wrong words. + +## Choosing a voice + +Listen to a sample of your actual sentences — including product names and +jargon — before you render anything with it. A voice that mangles the one +word your movie is about is worse than no narration. + +| Engine | Watch for | +|---|---| +| OS built-ins (`say`) | Free and instant; reliably sounds robotic. Fine for a scratch timing pass, not for delivery. | +| Cloud TTS endpoints (e.g. `/v1/audio/speech`) | Deterministic: reads exactly what you send. The safe default. | +| Chat models with audio output | Best prosody, but they are *chat models*: they ad-lib preambles ("Sure, here it is:"). Usable only with a verbatim gate. | +| Local neural TTS, Piper | The default when no key is present: free, offline after a one-time voice download, runs on macOS and Linux. It **mispronounces** unusual names rather than dropping them (our jargon came back as "Smevel's", all 14 words intact) — the opposite of the failure below, and the safer one. | +| Local neural TTS, Kokoro | Free and offline, but drops out-of-vocabulary words **silently**, with a zero exit code. "Every eval on the shelf" became "every on the shelf" with no error at all. | + +## Use the script + +`scripts/narrate scenes.yaml narration/` renders one clip per scene and +picks its engine automatically: a cloud voice when a key is there, Piper +when there isn't. It writes `manifest.json` with the exact text and the +*measured* duration of every clip — which is what make-subtitles and the +assembly step both consume, so nothing downstream has to guess timings. + +Force the choice with `--engine openai|openai-chat|piper`. `openai-chat` +buys the best prosody and pays for it with ad-libs, so it is gated below. + +## The gate runs even without a key + +`narrate` listens back to every clip it renders and compares what it hears +against the script. With a key it can use a cloud transcriber; without one +it uses a local ASR (faster-whisper) in its own environment. The gate is not +something you only get when you're online. + +What it measures is **missing or invented content**, not exact words, and +that distinction is load-bearing. A small ASR mangles unusual names — ours +came back as "Mevil studio" and "Yvel" — so exact matching cries wolf on +good clips. Worse, a genuinely *dropped* word scores as more similar than +two mispronounced ones, so a strict ratio would pass the real defect and +fail the harmless one. The gate therefore flags a large length change or a +run of consecutive words that went missing: a skipped sentence, an ad-libbed +preamble, a clip that came out empty. + +It will not catch a single dropped word in a jargon-heavy line. For those, +listen to one clip yourself when you pick the voice. + +Editing a line re-renders it: `narrate` records the text each clip was made +from, and a clip whose script has changed is regenerated rather than reused. + +## The verbatim gate — required + +Never trust the generator's own account of what it produced. Verify the +audio that is actually in the file: + +```bash +# transcribe the RENDERED audio, then diff against the source script +ffmpeg -nostdin -v error -i movie.mp4 -map 0:a -ac 1 -ar 16000 narration.wav +# send narration.wav to a transcription API, then compare word sequences +``` + +A word-sequence diff (lowercase, strip punctuation) catches dropped jargon, +ad-libbed preambles, and whole missing sentences. If the engine returns its +own transcript, diff that too — it is a cheap early signal — but the +rendered audio is the artifact that ships, so it is the one that counts. + +When drift is found: regenerate that block and re-verify. Retrying once +clears chat-model preambles almost every time. + +## Measure durations; never guess them + +The single most common defect in a narrated movie is motion paced against +narration that nobody timed. Write the script, render the audio, `ffprobe` +each clip, *then* build video to those measured lengths. + +```bash +ffprobe -v error -show_entries format=duration -of csv=p=0 narration/scene-03.wav +``` + +Word-count estimates (~2.5 words/sec) are for planning the script only. +Real delivery runs long and varies per block. + +## Pronunciation of product names + +Check the sample for your own jargon before committing to a voice. If a good +voice mangles one term, spell it phonetically **in the TTS input only** +("S M evals"), never in the script file a human reads. Keep that +substitution in the narrate step so the source text stays clean. diff --git a/skills/proving-it-works-with-a-movie/recording-a-terminal.md b/skills/proving-it-works-with-a-movie/recording-a-terminal.md new file mode 100644 index 000000000..7f521bc58 --- /dev/null +++ b/skills/proving-it-works-with-a-movie/recording-a-terminal.md @@ -0,0 +1,90 @@ +# Recording a terminal + +CLIs, TUIs, installs, test runs, agents at work — a large share of what is +worth proving happens in a terminal, and none of it is visible to a browser +recorder or an OS screen capture you probably can't get permission for. + +The technique: serve the terminal over HTTP with **ttyd**, attach it to a +**tmux** session, screenshot the page from a browser, and drive the session +with `tmux send-keys` from outside. Real characters from a real shell, in a +window you fully control. `examples/film-terminal.py` is a working +implementation of everything below. + +```bash +# inside the machine/container being filmed +tmux new-session -d -s demo -x 125 -y 34 +ttyd -p 7681 -t fontSize=17 -t 'fontFamily=DejaVu Sans Mono,monospace' \ + -t 'theme={"background":"#101014","foreground":"#e8e6e1"}' \ + tmux attach -t demo + +# from outside: drive it +tmux send-keys -t demo 'claude plugin install proving-it-works' Enter +docker exec CONTAINER tmux send-keys -t demo 'ls -la' Enter # containerised +``` + +Size the tmux session to the browser viewport you will screenshot +(roughly `width/10` columns by `height/22` rows at 17px) or the capture +shows a window cropped to a different geometry than the shell believes it +has. + +## Headless Chrome renders the terminal blank without software GL + +ttyd draws the terminal into a ``. Headless Chrome with no GPU +paints that canvas empty — the screenshot is a black rectangle with a +status bar, and nothing warns you. It cost 73 blank frames to notice. + +``` +--use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader +``` + +A related trap: setting `Emulation.setDeviceMetricsOverride` mid-session +resizes the canvas without triggering a redraw, blanking it again. Set the +scale at launch (`--force-device-scale-factor=2`) instead. + +**Preflight before every take.** Print something known, screenshot once, and +count lit pixels; abort if the frame is empty. Filming a whole sequence and +discovering afterwards that all of it is black is the failure this prevents: + +```python +lit = sum(1 for v in frame.convert("L").getdata() if v > 90) / npixels +if lit < 0.002: + raise SystemExit("terminal renders blank - check software GL flags") +``` + +## Never type into a program that is still running + +`tmux send-keys` puts characters into whatever owns the pane. If a command +is still working, your keystrokes land in *its* stdin and appear as echoed +text — the movie shows commands that never ran. Wait for the shell: + +```python +def wait_for_shell(session): + while tmux(f"display-message -p -t {session} '#{{pane_current_command}}'") \ + .strip() not in ("bash", "sh", "zsh"): + time.sleep(2) +``` + +This matters most for the interesting shots: an agent working, a build, a +test suite. Those are exactly the commands that outlast your `sleep`. + +## Long work does not belong inside one take + +An agent run or a build takes minutes. Film the command being issued, stop +the take, wait for the shell to come back, then film the result as a new +take, and let the cut carry the gap with a card that says how long it took. +Same rule as recording-motion.md: the work is real, the tedium is not. + +## Playing a movie inside the terminal + +`mpv --vo=tct movie.mp4` renders video as coloured terminal cells. It genuinely +proves a file plays where it was made, and it looks like what it is: blocky. +For a demo where the viewer should actually *see* the movie, cut to the movie +itself as a segment (`kind: movie` in assemble) rather than filming a terminal +playing it. + +## Glyphs + +Terminal fonts routinely lack the check marks and box drawing that CLIs +emit; a missing glyph renders as a placeholder box and makes real output +look broken. `fonts-dejavu-core` plus `-t 'fontFamily=DejaVu Sans Mono'` +covers most of it. Check the preflight screenshot before a long session. diff --git a/skills/proving-it-works-with-a-movie/recording-motion.md b/skills/proving-it-works-with-a-movie/recording-motion.md new file mode 100644 index 000000000..e8ccbeb72 --- /dev/null +++ b/skills/proving-it-works-with-a-movie/recording-motion.md @@ -0,0 +1,118 @@ +# Recording motion from a live app + +For when the interaction itself is the claim. Drive a real browser against a +real running instance; every pixel is the product. + +## Record against a copy, always + +A demo movie *writes*: it creates records, saves edits, fires jobs. Copy the +data tree to a scratch suite and serve that. Never point the recorder at the +tree you care about, and never at a production instance. + +## Two capture styles + +**Native video capture** (Playwright `record_video_dir`, Chrome DevTools +screencast) gives you a continuous clip for free. Playwright needs its own +bundled encoder — `playwright install ffmpeg` — separate from system ffmpeg. +Good when you want one continuous take. + +**Deliberate frame capture** (screenshot per beat, encode at a chosen rate) +costs more code and buys per-beat control over pacing, which is what you +need when narration has to line up. This is the right default for a narrated +tutorial. + +## Draw a cursor or the app appears haunted + +Browser automation moves an invisible pointer: a click looks like the UI +changing by itself, which is exactly what a skeptical reviewer discounts. +Inject a cursor overlay on every page and animate it to each target before +clicking, with a press pulse on mousedown. + +```js +// injected via addInitScript / Page.addScriptToEvaluateOnNewDocument +const ring = document.createElement("div"); +ring.style.cssText = "position:fixed;width:20px;height:20px;border:3px solid " + + "rgba(255,64,129,.9);border-radius:50%;pointer-events:none;z-index:2147483647;" + + "transform:translate(-50%,-50%);transition:transform .08s"; +document.addEventListener("DOMContentLoaded", () => document.body.appendChild(ring)); +document.addEventListener("mousemove", e => { + ring.style.left = e.clientX + "px"; ring.style.top = e.clientY + "px"; +}, true); +document.addEventListener("mousedown", + () => ring.style.transform = "translate(-50%,-50%) scale(.6)", true); +``` + +Type at human pace too (~55ms/char, longer after punctuation). Instant text +insertion reads as a scripted fake even when it isn't. + +## Describe scenes as data, not code + +Put the movie in a scene list — id, narration, ordered actions — and keep the +recorder generic. You will re-record individual scenes many times; editing a +YAML entry beats editing a script every time. Verbs worth having: +`goto`, `wait_for`, `click`, `type`, `append` (caret to end, then type), +`select`, `pause`. + +Check your scene list against the recorder's actual verbs *before* a long +pass. A verb the recorder doesn't implement fails at record time, after +you've spent the wall clock. + +## Only type into empty fields + +Automation appends at whatever caret exists. To edit existing text you need +an explicit caret move (`ControlOrMeta+ArrowDown` to end, then type). +Anything else silently produces mangled input on camera. + +## When the correct behavior is invisible + +Some claims are proven by *nothing changing*: state survives a reload, +a retry is idempotent, a cache returns the same answer. Filmed naively, the +before and after frames are pixel-identical and the movie shows nothing at +all — a viewer cannot tell the reload happened, and the mechanical gate will +correctly report a picture that stopped moving. + +Stage a visible marker of **the event**, not the effect: navigate to +`about:blank` and back rather than reloading in place, so there is a real +teardown and a genuinely blank beat on camera, then the restored state. +Same for a restart — show the process dying. + +Hold that marker beat for **more than one second**. `check-movie` samples the +picture at 1 Hz; a 600ms blank falls between two samples and is invisible to +the gate even though it is real. Anything you want the checker (or a viewer) +to register needs ~1.3s or more. + +## Screenshot-based capture: navigation orphans an in-flight capture + +Driving CDP directly, a `Page.captureScreenshot` issued as a navigation +begins never gets a reply — not slowly, *never*. A capture loop that awaits +it hangs until whatever global timeout you have expires. + +Race every capture against a short timeout (~700ms) and skip the frame: + +```js +const shot = await Promise.race([ + send("Page.captureScreenshot", { format: "png" }), + new Promise(r => setTimeout(() => r(null), 700)), +]); +if (shot) writeFrame(shot.data); // dropped frames are fine; a hung loop is not +``` + +## Slow real work does not fit inside a scene + +A genuine multi-minute operation (a model generating, a build, a deploy) +cannot be waited out inside a recording pass — and if the recorder owns the +server, shutting it down at end-of-pass kills the job mid-flight and leaves +half-written artifacts. + +Split into passes: record up to the trigger, let the pass end, produce the +artifact off-camera with the normal CLI, then record the pass that opens the +finished result. The movie is honest — the work really happened — and no +scene depends on a job outliving the process that started it. + +## App-specific gotchas worth checking before a pass + +- **Auth in the URL**: apps that read a token from `?k=` on first load and + scrub it need the token on the *first* navigation of each fresh context + only; tagging every navigation forces reloads and breaks hash routing. +- **Typed fields with parsers**: a value like `Yes`/`No`/`On`/`Off` in a + YAML-backed form field saves as a boolean and can crash the app on camera. diff --git a/skills/proving-it-works-with-a-movie/rendering-from-a-log.md b/skills/proving-it-works-with-a-movie/rendering-from-a-log.md new file mode 100644 index 000000000..968a3bd5f --- /dev/null +++ b/skills/proving-it-works-with-a-movie/rendering-from-a-log.md @@ -0,0 +1,90 @@ +# Rendering a reel from the run's own log + +For when there are no pixels to capture — OS screen recording is blocked, or +the thing to prove is a *run* (a test suite, a deploy, a job) rather than a +UI. Render an auditable reel from the real run's log instead of fighting the +OS for a picture. + +Adapted from `recording-a-proof-movie.md` in obra/superpowers PR #1931. + +## First: try real capture, and refuse to fake it + +```bash +ffmpeg -f avfoundation -list_devices true -i "" # probe devices + +ffmpeg -y -hide_banner -f avfoundation -framerate 15 -capture_cursor 1 \ + -t 2 -i ':none' -vf scale=1280:-2 -pix_fmt yuv420p /tmp/cap-check.mp4 +ffmpeg -y -hide_banner -i /tmp/cap-check.mp4 -frames:v 1 /tmp/cap-check.png +``` + +Look at that PNG. If it is wallpaper with no app window, Screen Recording +permission is denied for this process and capture will "succeed" while +recording nothing. **Do not ship it.** Say plainly that the OS blocked +capture and switch to the reel below — that pivot is the honest outcome, not +a fallback to apologize for. (`screencapture -x` has the same limitation; +`screencapture -x -l ` can still grab one window if you can +resolve its CoreGraphics id.) + +## Make the real run the evidence source + +Wrap the actual command so its log carries machine-checkable markers. Use +`bash`, not `zsh` — zsh's read-only `$status` injects a spurious error after +a passing run and pollutes the evidence. + +```bash +bash -o pipefail -c ' + printf "RUN_KIND=\n"; + printf "STARTED_AT="; date -u +%Y-%m-%dT%H:%M:%SZ; + ; + rc=$?; + printf "FINISHED_AT="; date -u +%Y-%m-%dT%H:%M:%SZ; + printf "EXIT_STATUS=%s\n" "$rc"; exit "$rc" +' 2>&1 | tee evidence/run.log +``` + +Keep each producer plus its `tee` under one `pipefail` owner, or a failing +command's status is lost and a failed run renders as a successful movie. + +If the run touches a remote host or shared session, snapshot that state +identically before and after and diff them; equal snapshots prove the run +left no residue. + +## Draw frames from the log + +Render title / exact command / result / before-after diff / evidence-bundle +panels as images and stream them into one ffmpeg pipe. Keep it in a saved, +re-runnable `generate_reel.py`, not a one-shot heredoc. + +```python +cmd = ["ffmpeg", "-y", "-hide_banner", "-f", "rawvideo", "-pix_fmt", "rgb24", + "-s", f"{W}x{H}", "-r", str(FPS), "-i", "-", "-an", "-c:v", "libx264", + "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p", "out.mp4"] +proc = subprocess.Popen(cmd, stdin=subprocess.PIPE) +for nframes, render in scenes: # render(t) -> PIL RGB image + for i in range(nframes): + proc.stdin.write(render(i / max(1, nframes - 1)).tobytes()) +proc.stdin.close() +if proc.wait() != 0: + raise SystemExit("ffmpeg failed") +``` + +## Hash the bundle + +The reel is *derived from* the log and snapshots; they ship next to it, not +instead of it. + +```bash +shasum -a 256 out.mp4 contact-sheet.png run.log > SHA256SUMS +shasum -a 256 -c SHA256SUMS +``` + +Fix anything the movie renders — a timestamp, a log line, a stale selector — +and you regenerate the movie and re-hash. A hash that no longer matches the +log is a lie. + +## Gate it + +`"$SKILL_DIR/scripts/check-movie" reel.mp4 --no-expect-audio` if the reel is +silent (`$SKILL_DIR` = this skill's own directory; see SKILL.md). Then open +the contact sheet and confirm the panels are legible at full size: a reel +nobody can read proves nothing. diff --git a/skills/proving-it-works-with-a-movie/rendering-stills.md b/skills/proving-it-works-with-a-movie/rendering-stills.md new file mode 100644 index 000000000..ee23ec84e --- /dev/null +++ b/skills/proving-it-works-with-a-movie/rendering-stills.md @@ -0,0 +1,50 @@ +# Composited stills + +The cheap route, and the right one whenever the *sequence of states* is the +claim and motion is decoration. Real screenshots of the running product, +captioned, held long enough to read. + +Adapted from `rendering-a-demo-movie.md` in obra/superpowers PR #1931. + +## 1. Capture real scene frames + +Fix the viewport first so every frame composes identically. Per beat: +navigate or drive the app into the state, screenshot to `frame-NN.png`, and +**read the PNG back** to confirm you got the state you meant. One deliberate +screenshot per beat; no fps. + +The read-back is not optional. It is what catches a shot taken mid-scroll, +mid-animation, or before a fetch resolved — the defect that otherwise ships. + +## 2. Sequence the screenshots as they are + +Do not composite caption bars onto the stills. Subtitles carry the words +now (assembling.md), so a caption strip burned into each frame duplicates +them, competes with them, and has to be re-rendered every time you reword a +sentence. The screenshot is the evidence; leave it alone. + +Name the shots so a lexical glob orders them — `shot-01.png` … `shot-NN.png` +— and let the assembly step hold each one for its narration. + +A title and an end card are still worth having, and those genuinely are +compositing: render them as HTML and screenshot them rather than fighting +ffmpeg `drawtext` (see assembling.md). Name them `shot-00` and `shot-99` so +the same glob picks them up in the right place. + +## 3. Hold each shot for its narration + +If the movie is narrated, each shot's duration is its narration clip's +measured length (plus a short beat), not a fixed interval. This is what +keeps a stills movie in sync by construction — the picture advances exactly +when the sentence about it ends. + +Unnarrated, `-framerate 1/3` (3s per shot) is a reasonable default; anything +faster than ~2.5s is unreadable. + +## 4. Gate it + +Run `"$SKILL_DIR/scripts/check-movie"` (see SKILL.md for the path), open the +contact sheet, and look. A stills movie earns a +frozen-tail warning when its final card outlasts its last narration by a +lot — that usually means the closing card is doing too much work, or the +last scene should have been two. diff --git a/skills/proving-it-works-with-a-movie/scripts/assemble b/skills/proving-it-works-with-a-movie/scripts/assemble new file mode 100755 index 000000000..690c6f961 --- /dev/null +++ b/skills/proving-it-works-with-a-movie/scripts/assemble @@ -0,0 +1,204 @@ +#!/usr/bin/env -S uv run --quiet --script +# /// script +# requires-python = ">=3.10" +# dependencies = ["pyyaml"] +# /// +"""Assemble scenes into one movie, each segment held to max(narration, visuals). + +Reads the same scenes file narrate does, so the narration you rendered and +the picture you recorded stay in step by construction: a segment lasts as +long as whichever of its two halves is longer, and the short one is padded +(video freezes its last frame, audio pads with silence). + +It also writes segments/offsets.json — where each scene starts in the final +cut — which make-subtitles consumes. Hand-computing those offsets is the +step that silently breaks every time you insert or reorder a scene. + +Scene kinds: + card title/caption rendered as HTML and screenshotted (needs a browser) + image a still you already have (a contact sheet, a diagram) + frames a directory of PNGs, played at `rate` fps + movie an existing movie, played as itself with its own audio + +Usage: + assemble SCENES.yaml OUT.mp4 [--narration DIR] [--work DIR] [--browser PATH] +""" + +import argparse +import json +import os +import shutil +import subprocess +import sys +import urllib.parse +from pathlib import Path + +import yaml + +BROWSERS = [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + "chromium", "chromium-browser", "google-chrome", "google-chrome-stable", +] + +CARD_HTML = """ +

{TITLE}

{SUB}

+""" + + +def die(msg): + print(f"assemble: {msg}", file=sys.stderr) + sys.exit(1) + + +def run(cmd): + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + die(f"{' '.join(map(str, cmd))}\n{r.stderr.strip()[:500]}") + return r + + +def dur(path): + r = run(["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "csv=p=0", str(path)]) + return float(r.stdout.strip()) + + +def find_browser(explicit): + for cand in ([explicit] if explicit else []) + BROWSERS: + if not cand: + continue + if os.path.sep in cand and Path(cand).exists(): + return cand + found = shutil.which(cand) + if found: + return found + return None + + +def make_card(scene, png, w, h, browser): + if not browser: + die("a `card` scene needs a browser (Chrome/Chromium) to render text; " + "pass --browser, or use an `image` scene you rendered yourself") + html = CARD_HTML.format( + w=w, h=h, bg=scene.get("background", "#101014"), + gap=max(16, h // 44), title=scene.get("title_size", max(28, h // 14)), + sub=scene.get("subtitle_size", max(16, h // 32)), + TITLE=scene.get("title", ""), SUB=scene.get("subtitle", "")) + tmp = png.with_suffix(".html") + tmp.write_text(html) + run([browser, "--headless=new", "--disable-gpu", "--hide-scrollbars", + f"--screenshot={png}", f"--window-size={w},{h}", + "--force-device-scale-factor=1", "file://" + urllib.parse.quote(str(tmp))]) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("scenes", type=Path) + ap.add_argument("out", type=Path) + ap.add_argument("--narration", type=Path, default=None) + ap.add_argument("--work", type=Path, default=None) + ap.add_argument("--browser", default=None) + args = ap.parse_args() + + for tool in ("ffmpeg", "ffprobe"): + if not shutil.which(tool): + die(f"{tool} not on PATH") + + doc = yaml.safe_load(args.scenes.read_text()) + base = args.scenes.parent + res = doc.get("resolution", {}) or {} + W, H = int(res.get("width", 1920)), int(res.get("height", 1080)) + FPS = int(doc.get("fps", 30)) + narration = args.narration or (base / "narration") + work = args.work or (base / "segments") + work.mkdir(parents=True, exist_ok=True) + browser = find_browser(args.browser) + + fit = (f"scale={W}:{H}:force_original_aspect_ratio=decrease," + f"pad={W}:{H}:(ow-iw)/2:(oh-ih)/2:color=#101014,setsar=1") + + offsets, clock, concat_lines = {}, 0.0, [] + for sc in doc["scenes"]: + sid = sc["id"] + kind = sc.get("kind", "frames") + seg = work / f"{sid}.mp4" + nar = narration / f"{sid}.wav" + nard = dur(nar) if nar.exists() else 0.0 + + if kind == "movie": + src = base / sc["src"] + target = dur(src) + inner_h = int(sc.get("height", int(H * 0.82))) + run(["ffmpeg", "-nostdin", "-y", "-v", "error", "-i", str(src), + "-vf", f"scale=-2:{inner_h},pad={W}:{H}:(ow-iw)/2:(oh-ih)/2:" + f"color=#101014,setsar=1", + "-af", f"volume={sc.get('gain_db', 0)}dB,apad", + "-r", str(FPS), "-t", f"{target:.3f}", + "-c:v", "libx264", "-preset", "medium", "-pix_fmt", "yuv420p", + "-c:a", "aac", "-ar", "44100", "-ac", "2", str(seg)]) + else: + if kind == "frames": + src = base / sc["src"] + n = len(list(Path(src).glob("*.png"))) + if not n: + die(f"scene {sid}: no PNGs in {src}") + rate = float(sc.get("rate", FPS)) + vis = n / rate + target = max(nard, vis) + vin = ["-framerate", str(rate), "-pattern_type", "glob", + "-i", str(Path(src) / "*.png")] + # freeze the last frame when narration outlasts the action + vf = fit + f",tpad=stop_mode=clone:stop_duration={max(0.0, target - vis):.3f}" + else: + if kind == "card": + img = work / f"card-{sid}.png" + make_card(sc, img, W, H, browser) + elif kind == "image": + img = base / sc["src"] + if not img.exists(): + die(f"scene {sid}: no such image {img}") + else: + die(f"scene {sid}: unknown kind {kind!r}") + target = max(nard, float(sc.get("duration", 3))) + vin = ["-loop", "1", "-i", str(img)] + vf = fit + + ain = (["-i", str(nar)] if nar.exists() + else ["-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo"]) + run(["ffmpeg", "-nostdin", "-y", "-v", "error", *vin, *ain, + "-vf", vf, "-af", "apad", "-r", str(FPS), "-t", f"{target:.3f}", + "-map", "0:v:0", "-map", "1:a:0", + "-c:v", "libx264", "-preset", "medium", "-pix_fmt", "yuv420p", + "-c:a", "aac", "-ar", "44100", "-ac", "2", str(seg)]) + + actual = dur(seg) + # only scenes that speak get a subtitle offset; a movie played as + # itself carries its own subtitles already + if nar.exists() and kind != "movie": + offsets[sid] = round(clock, 3) + clock += actual + concat_lines.append(f"file '{seg.resolve()}'") + print(f"{sid}: {actual:.1f}s{' (own audio)' if kind == 'movie' else ''}") + + listing = work / "concat.txt" + listing.write_text("\n".join(concat_lines) + "\n") + run(["ffmpeg", "-nostdin", "-y", "-v", "error", "-f", "concat", "-safe", "0", + "-i", str(listing), "-c", "copy", str(args.out)]) + (work / "offsets.json").write_text(json.dumps(offsets, indent=2)) + print(f"\nassembled {args.out} ({dur(args.out):.1f}s)") + print(f"scene offsets -> {work / 'offsets.json'} " + f"(feed to make-subtitles --offsets-json)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/proving-it-works-with-a-movie/scripts/burn-subtitles b/skills/proving-it-works-with-a-movie/scripts/burn-subtitles new file mode 100755 index 000000000..edfcb0eb6 --- /dev/null +++ b/skills/proving-it-works-with-a-movie/scripts/burn-subtitles @@ -0,0 +1,99 @@ +#!/usr/bin/env -S uv run --quiet --script +# /// script +# requires-python = ">=3.10" +# /// +"""Put subtitles on a movie, by whichever route this ffmpeg supports. + +Burning them into the picture is what you want: subtitles survive Slack, +PR previews, phones, and anything that plays video without a subtitle UI. +That needs an ffmpeg built with libass, which many are not — Homebrew's +default macOS build has no `subtitles` filter at all, while Debian's does. +Rather than emit a command that works on half of machines, this checks and +falls back to an embedded soft-subtitle track, telling you which you got. + +Usage: + burn-subtitles IN.mp4 SUBS.srt OUT.mp4 [--font NAME] [--size N] + [--soft] [--margin PX] +""" + +import argparse +import shutil +import subprocess +import sys +from pathlib import Path + + +def has_libass(): + out = subprocess.run(["ffmpeg", "-hide_banner", "-filters"], + capture_output=True, text=True) + return any(line.split()[1:2] == ["subtitles"] + for line in out.stdout.splitlines() if line.strip()) + + +def run(cmd): + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + print(" ".join(map(str, cmd)), file=sys.stderr) + print(r.stderr.strip()[:600], file=sys.stderr) + return r.returncode == 0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("movie", type=Path) + ap.add_argument("subs", type=Path) + ap.add_argument("out", type=Path) + ap.add_argument("--font", default="DejaVu Sans") + ap.add_argument("--size", type=int, default=16) + ap.add_argument("--margin", type=int, default=30) + ap.add_argument("--soft", action="store_true", + help="embed a soft track even if burning is available") + args = ap.parse_args() + + if not shutil.which("ffmpeg"): + sys.exit("ffmpeg not on PATH") + for f in (args.movie, args.subs): + if not f.exists(): + sys.exit(f"no such file: {f}") + + if not args.soft and has_libass(): + # ffmpeg 8 dropped positional filter options, so name it explicitly: + # `subtitles=movie.srt` parses on 5.x and fails on 8.x, but + # `subtitles=filename=movie.srt` works on both + # BorderStyle=3 draws a filled box behind the text. Outline-only + # subtitles are legible over a dark terminal and marginal over a + # white app screenshot; a demo movie cuts between both. + style = (f"FontName={args.font},Fontsize={args.size}," + f"BorderStyle=3,Outline=1,Shadow=0,MarginV={args.margin}," + f"PrimaryColour=&H00FFFFFF&,OutlineColour=&HB0101014&," + f"BackColour=&HB0101014&") + # run from the subtitle's directory: the filter treats ':' and '\' in + # paths as its own syntax, and quoting around that is a losing game + ok = run(["ffmpeg", "-nostdin", "-y", "-v", "error", + "-i", str(args.movie.resolve()), + "-vf", f"subtitles=filename={args.subs.name}:" + f"force_style='{style}'", + "-c:a", "copy", "-c:v", "libx264", "-preset", "medium", + "-pix_fmt", "yuv420p", str(args.out.resolve())]) + if ok: + print(f"burned into the picture -> {args.out}") + return 0 + print("burn failed; falling back to a soft track", file=sys.stderr) + + ok = run(["ffmpeg", "-nostdin", "-y", "-v", "error", + "-i", str(args.movie), "-i", str(args.subs), + "-c", "copy", "-c:s", "mov_text", + "-metadata:s:s:0", "language=eng", str(args.out)]) + if not ok: + return 1 + print(f"embedded a soft subtitle track -> {args.out}") + if not args.soft: + print("NOTE: this ffmpeg has no libass, so the subtitles are a track a " + "player must choose to show, not pixels. Anything that autoplays " + "without subtitle UI (Slack, PR previews) will show none. Install " + "an ffmpeg with libass to burn them in.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/proving-it-works-with-a-movie/scripts/check-movie b/skills/proving-it-works-with-a-movie/scripts/check-movie new file mode 100755 index 000000000..ad4cf0561 --- /dev/null +++ b/skills/proving-it-works-with-a-movie/scripts/check-movie @@ -0,0 +1,261 @@ +#!/usr/bin/env -S uv run --quiet --script +# /// script +# requires-python = ">=3.10" +# dependencies = ["pillow"] +# /// +"""Mechanical gate for a proof/demo movie: catches the silent defects that +per-frame inspection structurally cannot see. + +A movie can pass every frame check and still be unwatchable, because the +defects live *between* frames: action crammed into the first seconds, a +narrator talking over a picture that died, a silent audio track. This +samples the picture and the sound on the same timeline and compares them. + +Thresholds are heuristics tuned against real good and bad movies. They +catch the egregious cases; they cannot tell you a movie is *right*. That is +what the contact sheet is for, and you have to actually look at it. + +Known blind spot: the picture is sampled at 1 Hz, so a visual beat shorter +than a second (a flash, a blank frame during a reload) falls between samples +and reads as "no change". Hold anything that matters for >1s. + +Usage: + check-movie MOVIE [--out DIR] [--no-expect-audio] + [--no-expect-subtitles] [--subs FILE] [--json] +""" + +import argparse +import array +import json +import math +import shutil +import subprocess +import sys +from pathlib import Path + +from PIL import Image + +THUMB_W = 320 # sampling width; the metric is a pixel fraction, so scale-free +PIXEL_DELTA = 8 # per-pixel grey delta that counts as "this pixel moved" +CHANGE_FRAC = 0.002 # >0.2% of pixels moved => the picture reached a new state +SPEECH_DB = -45.0 # windowed RMS above this counts as "someone is talking" +EARLY_ACTION = 0.40 # last change before this fraction of runtime => front-loaded +TAIL_TALK_S = 5.0 # ...and this many seconds of narration after it => broken +WARN_TAIL_S = 15.0 # frozen tail worth mentioning even when it passes +WARN_GAP_S = 30.0 # hold this long mid-movie and a viewer wonders if it froze + + +def die(msg): + print(f"FAIL {msg}") + sys.exit(2) + + +def grey(path): + with Image.open(path) as im: + return list(im.convert("L").tobytes()) + + +def sample_picture(movie, workdir): + """Per-second: fraction of pixels that moved since the previous second.""" + frames = workdir / "samples" + frames.mkdir(parents=True, exist_ok=True) + for old in frames.glob("*.png"): + old.unlink() + out = subprocess.run( + ["ffmpeg", "-nostdin", "-v", "error", "-i", str(movie), + "-vf", f"fps=1,scale={THUMB_W}:-1", "-f", "image2", str(frames / "s%05d.png")], + capture_output=True, text=True) + if out.returncode != 0: + die(f"frame sampling failed: {out.stderr.strip()[:200]}") + paths = sorted(frames.glob("s*.png")) + if not paths: + die("no video frames could be sampled") + fracs, prev = [], None + for p in paths: + px = grey(p) + if prev is not None: + n = min(len(px), len(prev)) + moved = sum(1 for i in range(n) if abs(px[i] - prev[i]) > PIXEL_DELTA) + fracs.append(moved / n) + prev = px + return paths, fracs + + +def sample_sound(movie, has_audio): + """Per-second RMS in dBFS.""" + if not has_audio: + return [] + out = subprocess.run( + ["ffmpeg", "-nostdin", "-v", "error", "-i", str(movie), + "-map", "0:a:0", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], + capture_output=True) + if out.returncode != 0 or not out.stdout: + die(f"audio decode failed: {out.stderr.decode()[:200]}") + pcm = array.array("h") + pcm.frombytes(out.stdout[: len(out.stdout) // 2 * 2]) + levels = [] + for start in range(0, len(pcm), 8000): + chunk = pcm[start:start + 8000] + if not chunk: + break + rms = math.sqrt(sum(float(s) * s for s in chunk) / len(chunk)) + levels.append(20 * math.log10(rms / 32768.0) if rms > 0 else -120.0) + return levels + + +def contact_sheet(paths, out_path, count=12): + picks = paths if len(paths) <= count else [ + paths[round(i * (len(paths) - 1) / (count - 1))] for i in range(count)] + thumbs = [Image.open(p).convert("RGB") for p in picks] + w, h = thumbs[0].size + # pick a column count that fills the grid exactly where possible: an + # empty cell reads as a black *frame*, which is a defect signal, and a + # sheet that lies about the movie defeats the point of the sheet + n = len(thumbs) + cols = next((c for c in (4, 3, 5, 2) if n % c == 0), min(4, n)) + rows = math.ceil(n / cols) + sheet = Image.new("RGB", (cols * w, rows * h), (48, 48, 52)) + for i, t in enumerate(thumbs): + sheet.paste(t, ((i % cols) * w, (i // cols) * h)) + sheet.save(out_path) + return [paths.index(p) for p in picks] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("movie", type=Path) + ap.add_argument("--out", type=Path, default=None) + ap.add_argument("--no-expect-audio", dest="expect_audio", + action="store_false", default=True) + ap.add_argument("--no-expect-subtitles", dest="expect_subs", + action="store_false", default=True) + ap.add_argument("--subs", type=Path, default=None, + help="sidecar .srt (default: MOVIE.srt beside the movie)") + ap.add_argument("--json", action="store_true") + args = ap.parse_args() + + if not args.movie.exists(): + die(f"no such movie: {args.movie}") + for tool in ("ffmpeg", "ffprobe"): + if not shutil.which(tool): + die(f"{tool} not on PATH") + + workdir = args.out or args.movie.parent / f"{args.movie.stem}-check" + workdir.mkdir(parents=True, exist_ok=True) + + meta = subprocess.run( + ["ffprobe", "-v", "error", "-print_format", "json", + "-show_format", "-show_streams", str(args.movie)], + capture_output=True, text=True) + if meta.returncode != 0: + die(f"ffprobe failed: {meta.stderr.strip()[:200]}") + info = json.loads(meta.stdout) + vs = [s for s in info["streams"] if s["codec_type"] == "video"] + as_ = [s for s in info["streams"] if s["codec_type"] == "audio"] + if not vs: + die("no video stream") + duration = float(info["format"].get("duration", 0)) + + paths, fracs = sample_picture(args.movie, workdir) + levels = sample_sound(args.movie, bool(as_)) + changes = [i for i, f in enumerate(fracs) if f > CHANGE_FRAC] + talking = [i for i, lv in enumerate(levels) if lv >= SPEECH_DB] + span = len(fracs) or 1 + last_change = changes[-1] if changes else None + last_talk = talking[-1] if talking else None + + print(f"container {vs[0]['codec_name']} {vs[0]['width']}x{vs[0]['height']}, " + f"{duration:.1f}s, audio={'yes' if as_ else 'no'}") + print(f"picture reaches a new state in {len(changes)} of {span} seconds" + + (f"; last at {last_change}s" if last_change is not None else "")) + if levels: + print(f"sound audible in {len(talking)} of {len(levels)} seconds" + + (f"; last at {last_talk}s" if last_talk is not None else "")) + + failures, warnings = [], [] + if duration < 1: + failures.append(f"duration is {duration:.2f}s - that is not a movie") + if args.expect_audio and not as_: + failures.append("expected narration but there is no audio stream") + if levels and not talking: + failures.append("the audio track is silent end to end") + + # a narrated movie with no subtitles fails for everyone watching it muted + if as_ and args.expect_subs: + srt = args.subs or args.movie.with_suffix(".srt") + embedded = any(s["codec_type"] == "subtitle" for s in info["streams"]) + if srt.exists(): + last = 0.0 + for line in srt.read_text(errors="replace").splitlines(): + if "-->" in line: + end = line.split("-->")[1].strip().split()[0] + hh, mm, rest = end.split(":") + ss, _, ms = rest.partition(",") + last = max(last, int(hh) * 3600 + int(mm) * 60 + int(ss) + + int(ms or 0) / 1000) + # compare against where the narration ends, not the runtime: a + # silent end card is normal and must not read as missing subtitles + speech_end = float(last_talk + 1) if last_talk is not None else duration + print(f"subtitles {srt.name}, last cue ends at {last:.1f}s " + f"(narration ends {speech_end:.0f}s)") + if last < speech_end - 3.0: + failures.append( + f"subtitles stop at {last:.0f}s but the narration runs to " + f"{speech_end:.0f}s - {speech_end - last:.0f}s of speech " + f"has no subtitles") + elif embedded: + print("subtitles embedded subtitle stream present") + else: + failures.append( + f"narrated, but no subtitles: expected {srt.name} beside the " + f"movie (or an embedded track). Run make-subtitles and burn " + f"them in; pass --no-expect-subtitles only for a movie nobody " + f"will ever watch muted.") + if not changes: + failures.append("the picture never reaches a new state - this is a still, " + "not a movie") + else: + tail_talk = (last_talk - last_change) if last_talk is not None else 0 + frozen_frac = (span - last_change) / span + if last_change < EARLY_ACTION * span and tail_talk > TAIL_TALK_S: + failures.append( + f"every visible change happens in the first {last_change}s " + f"({100*last_change/span:.0f}% of runtime), then the picture is " + f"frozen for {span - last_change}s while narration keeps talking " + f"for {tail_talk:.0f}s of it. The demo is over before the " + f"explanation starts: pace the action to the narration.") + elif tail_talk > WARN_TAIL_S: + warnings.append(f"{tail_talk:.0f}s of narration after the last visible " + f"change ({100*frozen_frac:.0f}% of runtime frozen)") + gaps = [changes[i + 1] - changes[i] for i in range(len(changes) - 1)] + if gaps and max(gaps) > WARN_GAP_S: + warnings.append(f"{max(gaps)}s with no visible change mid-movie - " + f"intentional hold, or did something hang?") + + sheet = workdir / "contact-sheet.png" + idxs = contact_sheet(paths, sheet) + print(f"sheet {sheet}") + print(f" sampled at {', '.join(str(i) + 's' for i in idxs)}") + + for w in warnings: + print(f"WARN {w}") + for f in failures: + print(f"FAIL {f}") + + if args.json: + (workdir / "check.json").write_text(json.dumps( + {"duration": duration, "change_seconds": changes, + "talk_seconds": talking, "failures": failures, + "warnings": warnings}, indent=2)) + + if failures: + print("\nNOT SHIPPABLE. Fix, regenerate, re-run.") + return 1 + print("\nMechanical checks pass. NOW OPEN THE CONTACT SHEET AND LOOK AT IT: " + "this script cannot see wrong content, unreadable text, a missing " + "cursor, or narration that says something the picture contradicts.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/proving-it-works-with-a-movie/scripts/make-subtitles b/skills/proving-it-works-with-a-movie/scripts/make-subtitles new file mode 100755 index 000000000..7c73473d7 --- /dev/null +++ b/skills/proving-it-works-with-a-movie/scripts/make-subtitles @@ -0,0 +1,125 @@ +#!/usr/bin/env -S uv run --quiet --script +# /// script +# requires-python = ">=3.10" +# /// +"""Build an SRT from narrate's manifest, timed to the measured clips. + +Subtitles are not decoration. A movie gets watched muted - in a PR, on a +phone, in an open-plan office, by someone who is deaf - and an unsubtitled +narrated movie simply doesn't communicate to those viewers. They also make +the movie searchable and let a reviewer check what was said without +listening. + +Cue timing is proportional to character count within each scene's measured +audio, which tracks speech closely enough for reading. If you need +word-exact timing, transcribe the rendered audio with a word-timestamp API +and use those offsets instead. + +Usage: + make-subtitles MANIFEST.json OUT.srt [--offsets SCENE=SECONDS ...] + [--max-chars N] [--max-secs S] +""" + +import argparse +import json +import sys +from pathlib import Path + +MAX_CHARS = 84 # two comfortable lines +MAX_SECS = 5.5 +MIN_SECS = 1.0 + + +def cue_chunks(text, max_chars): + """Split into cue-sized pieces on sentence, then clause, then word.""" + words, chunks, cur = text.split(), [], "" + for w in words: + candidate = f"{cur} {w}".strip() + if len(candidate) > max_chars and cur: + chunks.append(cur) + cur = w + else: + cur = candidate + if cur.endswith((".", "!", "?")) and len(cur) > max_chars * 0.45: + chunks.append(cur) + cur = "" + if cur: + chunks.append(cur) + return chunks or [text] + + +def wrap(line, width=42): + words, out, cur = line.split(), [], "" + for w in words: + if len(f"{cur} {w}".strip()) > width and cur: + out.append(cur) + cur = w + else: + cur = f"{cur} {w}".strip() + if cur: + out.append(cur) + return "\n".join(out[:2]) if len(out) <= 2 else "\n".join( + [" ".join(out[:len(out) // 2]), " ".join(out[len(out) // 2:])]) + + +def ts(seconds): + ms = int(round(seconds * 1000)) + h, ms = divmod(ms, 3600000) + m, ms = divmod(ms, 60000) + s, ms = divmod(ms, 1000) + return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("manifest", type=Path) + ap.add_argument("out", type=Path) + ap.add_argument("--offsets", nargs="*", default=[], + help="SCENE=SECONDS start overrides; without these, scenes " + "are assumed to run back to back in manifest order") + ap.add_argument("--offsets-json", type=Path, default=None, + help="segments/offsets.json from assemble - the reliable " + "way to time cues against the finished cut") + ap.add_argument("--max-chars", type=int, default=MAX_CHARS) + ap.add_argument("--max-secs", type=float, default=MAX_SECS) + args = ap.parse_args() + + manifest = json.loads(args.manifest.read_text()) + overrides = {} + if args.offsets_json: + overrides.update({k: float(v) for k, v in + json.loads(args.offsets_json.read_text()).items()}) + for spec in args.offsets: + k, _, v = spec.partition("=") + overrides[k] = float(v) + + # a scene with no offset and no place in the cut would silently land at + # the wrong time; skip it rather than mistime it + if overrides: + manifest = [e for e in manifest if e["id"] in overrides] + cues, clock = [], 0.0 + for entry in manifest: + start = overrides.get(entry["id"], clock) + dur = float(entry["duration"]) + chunks = cue_chunks(entry["text"], args.max_chars) + total_chars = sum(len(c) for c in chunks) or 1 + t = start + for chunk in chunks: + share = dur * (len(chunk) / total_chars) + share = max(MIN_SECS, min(share, args.max_secs)) + cues.append((t, min(t + share, start + dur), wrap(chunk))) + t += share + clock = start + dur + + lines = [] + for i, (a, b, text) in enumerate(cues, 1): + if b <= a: + b = a + MIN_SECS + lines += [str(i), f"{ts(a)} --> {ts(b)}", text, ""] + args.out.write_text("\n".join(lines)) + print(f"{len(cues)} cues, ends at {ts(cues[-1][1])} -> {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/proving-it-works-with-a-movie/scripts/narrate b/skills/proving-it-works-with-a-movie/scripts/narrate new file mode 100755 index 000000000..5f99e2131 --- /dev/null +++ b/skills/proving-it-works-with-a-movie/scripts/narrate @@ -0,0 +1,284 @@ +#!/usr/bin/env -S uv run --quiet --script +# /// script +# requires-python = ">=3.10" +# dependencies = ["pyyaml", "piper-tts"] +# /// +"""Render one narration clip per scene, and prove it says what you wrote. + +Engine selection is automatic: a cloud voice when a key is available, a +local neural voice (Piper) when there isn't one. The local path needs no +key, no network after the first voice download, and runs on macOS and +Linux alike - so a container with no secrets in it can still narrate. + +Input is a scenes file: a YAML list of scenes, each with `id` and +`narration`. Output is OUTDIR/.wav plus OUTDIR/manifest.json carrying +the exact text and measured duration of each clip, which is what +make-subtitles and the assembly step both read. + +Usage: + narrate SCENES.yaml OUTDIR [--engine auto|openai|openai-chat|piper] + [--voice NAME] [--force] +""" + +import argparse +import base64 +import difflib +import json +import os +import re +import subprocess +import sys +import urllib.request +import wave +from pathlib import Path + +import yaml + +OPENAI_TTS_MODEL = "gpt-4o-mini-tts" # deterministic: reads what you send +OPENAI_CHAT_MODEL = "gpt-audio-1.5" # better prosody, will ad-lib; gated +PIPER_VOICE = "en_US-lessac-medium" + + +def die(msg): + print(f"narrate: {msg}", file=sys.stderr) + sys.exit(1) + + +def openai_key(): + key = os.environ.get("OPENAI_API_KEY") + if key: + return key.strip() + try: + out = subprocess.run(["llm", "keys", "get", "openai"], + capture_output=True, text=True, timeout=15) + if out.returncode == 0 and out.stdout.strip(): + return out.stdout.strip() + except Exception: # noqa: BLE001 - llm not installed is a normal outcome + pass + return None + + +def norm(s): + return re.sub(r"[^a-z0-9 ]+", "", s.lower()).split() + + +ASR_SNIPPET = """ +import sys +from faster_whisper import WhisperModel +m = WhisperModel(sys.argv[2], device="cpu", compute_type="int8") +segs, _ = m.transcribe(sys.argv[1]) +print(" ".join(s.text.strip() for s in segs)) +""" + + +def transcribe_local(wav, model="base.en"): + """Transcribe with a local ASR, in its own uv env so narrate stays light. + Returns None when faster-whisper isn't available.""" + try: + out = subprocess.run( + ["uv", "run", "--quiet", "--with", "faster-whisper", "python3", + "-c", ASR_SNIPPET, str(wav), model], + capture_output=True, text=True, timeout=900) + except Exception: # noqa: BLE001 - no uv, no network: gate simply unavailable + return None + return out.stdout.strip() if out.returncode == 0 and out.stdout.strip() else None + + +def structural_drift(text, heard): + """How far a transcript diverges from the script, ignoring the noise an + ASR always makes. + + Exact word-matching is the wrong tool here: a small model mangles + unusual names ("smevals" -> "Mevil"), and - worse - a *dropped* word + scores as more similar than two mispronounced ones. What is detectable, + and what actually matters, is missing or invented CONTENT: a sentence + the voice skipped, or a preamble it invented. Returns + (length_delta_fraction, longest_run_of_missing_or_changed_words). + """ + want, got = norm(text), norm(heard) + delta = abs(len(got) - len(want)) / max(1, len(want)) + ops = difflib.SequenceMatcher(a=want, b=got).get_opcodes() + worst = max((i2 - i1 for tag, i1, i2, _, _ in ops if tag in ("delete", "replace")), + default=0) + return delta, worst + + +def post(url, key, body, want_json=True): + req = urllib.request.Request( + url, data=json.dumps(body).encode(), + headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=180) as r: + return json.load(r) if want_json else r.read() + + +def say_openai(key, text, out_wav, voice): + data = post("https://api.openai.com/v1/audio/speech", key, + {"model": OPENAI_TTS_MODEL, "voice": voice or "nova", + "input": text, "response_format": "wav"}, want_json=False) + out_wav.write_bytes(data) + return None # deterministic engine: nothing to gate + + +def say_openai_chat(key, text, out_wav, voice): + doc = post("https://api.openai.com/v1/chat/completions", key, { + "model": OPENAI_CHAT_MODEL, + "modalities": ["text", "audio"], + "audio": {"voice": voice or "nova", "format": "wav"}, + "messages": [{"role": "user", "content": + "Read this narration aloud, warm and clear, verbatim, " + "and say nothing else:\n\n" + text}], + }) + audio = doc["choices"][0]["message"]["audio"] + out_wav.write_bytes(base64.b64decode(audio["data"])) + return audio.get("transcript", "") + + +def say_piper(text, out_wav, voice): + from piper import PiperVoice + from piper.download_voices import download_voice + home = Path(os.environ.get("PIPER_VOICE_DIR", + Path.home() / ".cache" / "piper-voices")) + home.mkdir(parents=True, exist_ok=True) + name = voice or PIPER_VOICE + onnx = home / f"{name}.onnx" + if not onnx.exists(): + print(f" downloading local voice {name} (one time)…") + download_voice(name, home) + v = PiperVoice.load(str(onnx)) + with wave.open(str(out_wav), "wb") as w: + v.synthesize_wav(text, w) + return None + + +def duration(path): + out = subprocess.run( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "csv=p=0", str(path)], capture_output=True, text=True) + return round(float(out.stdout.strip()), 3) + + +def main(): + if len(sys.argv) == 4 and sys.argv[1] == "--drift-check": + script = Path(sys.argv[2]).read_text() + heard = Path(sys.argv[3]).read_text() + delta, worst = structural_drift(script, heard) + bad = delta > 0.15 or worst >= 4 + print(f"length change {delta:.0%}, worst run {worst} -> " + f"{'MISMATCH' if bad else 'ok'}") + return 1 if bad else 0 + + ap = argparse.ArgumentParser() + ap.add_argument("scenes", type=Path) + ap.add_argument("outdir", type=Path) + ap.add_argument("--engine", default="auto", + choices=["auto", "openai", "openai-chat", "piper"]) + ap.add_argument("--voice", default=None) + ap.add_argument("--force", action="store_true") + ap.add_argument("--verify", default="auto", choices=["auto", "on", "off"], + help="listen back to each clip with a local ASR and flag " + "missing or invented content (default: on when the " + "engine can't tell you what it said)") + ap.add_argument("--asr-model", default="base.en") + args = ap.parse_args() + + doc = yaml.safe_load(args.scenes.read_text()) + scenes = [s for s in doc.get("scenes", []) if (s.get("narration") or "").strip()] + if not scenes: + die("no scenes with narration") + + key = openai_key() + engine = args.engine + if engine == "auto": + engine = "openai" if key else "piper" + if engine.startswith("openai") and not key: + die("no OPENAI_API_KEY (and `llm keys get openai` found nothing). " + "Use --engine piper for a local voice.") + print(f"engine: {engine}" + ("" if key or engine == "piper" else "")) + + # a deterministic cloud endpoint reads exactly what you send it, so the + # ear-check is optional there; anything else gets listened to by default + verify = args.verify == "on" or (args.verify == "auto" and engine != "openai") + + args.outdir.mkdir(parents=True, exist_ok=True) + # what the cached clips were rendered FROM: editing a line and keeping + # its old audio is a silent lie, and the movie will contradict itself + prior = {} + prior_path = args.outdir / "manifest.json" + if prior_path.exists(): + try: + prior = {e["id"]: e.get("text", "") for e in + json.loads(prior_path.read_text())} + except Exception: # noqa: BLE001 - a corrupt manifest just means no cache + prior = {} + manifest, failures = [], [] + + for sc in scenes: + sid = sc["id"] + text = " ".join((sc["narration"] or "").split()) + wav = args.outdir / f"{sid}.wav" + if wav.exists() and not args.force and prior.get(sid) == text: + print(f"{sid}: cached") + elif wav.exists() and not args.force and sid in prior: + print(f"{sid}: text changed since this clip was rendered - redoing") + args.force = True + else: + for attempt in (1, 2): + if engine == "openai": + claimed = say_openai(key, text, wav, args.voice) + elif engine == "openai-chat": + claimed = say_openai_chat(key, text, wav, args.voice) + else: + claimed = say_piper(text, wav, args.voice) + + # a chat model reports what it said: hold it to that exactly, + # because "Sure, here it is:" is the failure it introduces + if claimed is not None: + want, got = norm(text), norm(claimed) + drift = abs(len(want) - len(got)) + sum( + 1 for a, b in zip(want, got) if a != b) + if drift > max(2, len(want) // 25): + print(f"{sid}: engine ad-libbed (attempt {attempt}, " + f"drift {drift})") + continue + + # every engine: listen back. An ASR mangles unusual names, so + # only missing or invented CONTENT counts as a failure here. + if verify: + heard = transcribe_local(wav, args.asr_model) + if heard is None: + print(f"{sid}: ok (no local ASR available - gate skipped)") + break + delta, worst = structural_drift(text, heard) + if delta > 0.15 or worst >= 4: + print(f"{sid}: what came out does not match the script " + f"(attempt {attempt}: {delta:.0%} length change, " + f"{worst} words in a row wrong)") + print(f" heard: {heard[:120]}") + continue + print(f"{sid}: ok (verified by ear: {delta:.0%} length " + f"change, worst run {worst})") + break + print(f"{sid}: ok") + break + else: + failures.append(sid) + manifest.append({"id": sid, "text": text, "wav": wav.name, + "duration": duration(wav)}) + + (args.outdir / "manifest.json").write_text(json.dumps(manifest, indent=2)) + total = sum(m["duration"] for m in manifest) + print(f"\n{len(manifest)} clips, {total:.1f}s total -> {args.outdir}/manifest.json") + if engine == "piper": + print("local voice: it mispronounces unusual names rather than dropping " + "them - listen to one clip before you commit to a voice.") + if verify: + print("the ear-check catches missing or invented sentences, not " + "pronunciation: an ASR mangles jargon too.") + if failures: + print(f"FAILED verbatim delivery: {failures}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/proving-it-works-with-a-movie/test-assemble.sh b/tests/proving-it-works-with-a-movie/test-assemble.sh new file mode 100755 index 000000000..c5eca6698 --- /dev/null +++ b/tests/proving-it-works-with-a-movie/test-assemble.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Regression tests for scripts/assemble and scripts/make-subtitles. +# +# The property that matters: a segment lasts max(narration, visuals), and +# the scene offsets written for the subtitler match where scenes actually +# start in the finished cut. Hand-computed offsets silently mistime every +# cue after an inserted scene, which is why assemble emits them. +# +# Usage: tests/proving-it-works-with-a-movie/test-assemble.sh +set -uo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +SCRIPTS="$HERE/../../skills/proving-it-works-with-a-movie/scripts" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT +pass=0; fail=0 + +for tool in ffmpeg ffprobe uv; do + command -v "$tool" >/dev/null || { echo "SKIP: $tool not on PATH"; exit 0; } +done + +ok() { echo "ok $1"; pass=$((pass + 1)); } +no() { echo "FAIL $1"; fail=$((fail + 1)); } +dur() { ffprobe -v error -show_entries format=duration -of csv=p=0 "$1"; } +about() { # about + awk -v a="$1" -v b="$2" -v t="$3" 'BEGIN{exit !(a-b "$WORK/scenes.yaml" <<'YAML' +resolution: { width: 640, height: 360 } +fps: 30 +scenes: + - id: opener + kind: image + src: shots/s01.png + duration: 2 + - id: body + kind: frames + src: shots + rate: 1.0 +YAML + +out="$WORK/out.mp4" +if "$SCRIPTS/assemble" "$WORK/scenes.yaml" "$out" >"$WORK/log" 2>&1; then + ok "assemble runs" +else + no "assemble runs"; sed 's/^/ /' "$WORK/log" +fi + +# opener 2s + body max(4s pictures, 6s narration) = 8s +total="$(dur "$out")" +if about "$total" 8 0.4; then ok "segment = max(narration, visuals)" +else no "segment = max(narration, visuals): got ${total}s, wanted ~8"; fi + +offset="$(python3 -c "import json;print(json.load(open('$WORK/segments/offsets.json'))['body'])" 2>/dev/null)" +if about "${offset:-0}" 2 0.3; then ok "offsets.json places the narrated scene" +else no "offsets.json places the narrated scene: got ${offset:-none}, wanted ~2"; fi + +if "$SCRIPTS/make-subtitles" "$WORK/narration/manifest.json" "$WORK/out.srt" \ + --offsets-json "$WORK/segments/offsets.json" >/dev/null 2>&1 \ + && grep -q "00:00:0[2-9]" "$WORK/out.srt"; then + ok "cues start at the scene's real offset, not zero" +else + no "cues start at the scene's real offset, not zero" +fi + +echo +echo "$pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/tests/proving-it-works-with-a-movie/test-check-movie.sh b/tests/proving-it-works-with-a-movie/test-check-movie.sh new file mode 100755 index 000000000..05242dad9 --- /dev/null +++ b/tests/proving-it-works-with-a-movie/test-check-movie.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# Regression tests for scripts/check-movie. +# +# Synthesizes movies with known defects using ffmpeg's lavfi sources - no +# fixtures committed, nothing downloaded - and asserts the checker's verdict +# on each. The front-loaded case reproduces the real failure this skill +# exists to prevent: a movie whose action finishes in the first seconds +# while narration keeps talking over a frozen picture. +# +# Usage: tests/proving-it-works-with-a-movie/test-check-movie.sh +set -uo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +CHECKER="$HERE/../../skills/proving-it-works-with-a-movie/scripts/check-movie" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +pass=0 +fail=0 + +for tool in ffmpeg ffprobe uv; do + command -v "$tool" >/dev/null || { echo "SKIP: $tool not on PATH"; exit 0; } +done +[ -x "$CHECKER" ] || { echo "FAIL: $CHECKER is not executable"; exit 1; } + +# --- fixtures ------------------------------------------------------------- +# action for 2s, then a frozen picture for 20s, narration (tone) throughout +ffmpeg -nostdin -y -v error \ + -f lavfi -i "testsrc2=size=320x240:rate=10:d=2" \ + -f lavfi -i "color=c=navy:size=320x240:rate=10:d=20" \ + -f lavfi -i "sine=frequency=300:duration=22" \ + -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" \ + -map "[v]" -map 2:a -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest \ + "$WORK/front-loaded.mp4" + +# picture changing throughout, narration throughout +ffmpeg -nostdin -y -v error \ + -f lavfi -i "testsrc2=size=320x240:rate=10:d=22" \ + -f lavfi -i "sine=frequency=300:duration=22" \ + -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest "$WORK/paced.mp4" + +# one static frame for the whole runtime, narration throughout +ffmpeg -nostdin -y -v error \ + -f lavfi -i "color=c=navy:size=320x240:rate=10:d=12" \ + -f lavfi -i "sine=frequency=300:duration=12" \ + -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest "$WORK/still.mp4" + +# motion, but no audio track at all +ffmpeg -nostdin -y -v error \ + -f lavfi -i "testsrc2=size=320x240:rate=10:d=12" \ + -c:v libx264 -pix_fmt yuv420p "$WORK/silent.mp4" + +# subtitles: one covering the whole runtime, one that gives up early +cat > "$WORK/paced.srt" <<'SRT' +1 +00:00:00,000 --> 00:00:07,000 +A narrated movie needs subtitles: +plenty of people watch muted. + +2 +00:00:07,000 --> 00:00:14,000 +The checker treats their absence +as a defect, not a nicety. + +3 +00:00:14,000 --> 00:00:21,500 +And it notices when they stop +before the narration does. +SRT +head -8 "$WORK/paced.srt" > "$WORK/short.srt" +cp "$WORK/paced.mp4" "$WORK/short.mp4" + +# --- assertions ----------------------------------------------------------- +check() { # check