diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index cb54387..8afdfca 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -8,7 +8,7 @@ { "name": "superpowers-custom", "description": "Fork of obra/superpowers (v6.0.3 base + fork revisions) with the no-commit subagent-driven-development model. Drop-in replacement for the official superpowers plugin.", - "version": "6.0.4-fork.10", + "version": "6.0.4-fork.11", "source": "./", "author": { "name": "stanlrt" diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index de54d6d..a7bbf55 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "superpowers-custom", "description": "Fork of obra/superpowers (v6.0.3 base + fork revisions) with a no-commit subagent-driven-development model, snapshot-based review, dependency-DAG parallel batching, issue->branch worktrees, and a template-driven PR finish flow. Drop-in replacement for the official superpowers plugin.", - "version": "6.0.4-fork.10", + "version": "6.0.4-fork.11", "author": { "name": "stanlrt" }, diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 1343ca0..aba82bf 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers-custom", - "version": "6.0.4-fork.10", + "version": "6.0.4-fork.11", "description": "An agentic skills framework & software development methodology that works: planning, TDD, debugging, and collaboration workflows.", "author": { "name": "stanlrt" diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 2a3854c..d9c11f1 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -2,7 +2,7 @@ "name": "superpowers-custom", "displayName": "Superpowers (custom fork)", "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.0.4-fork.10", + "version": "6.0.4-fork.11", "author": { "name": "stanlrt" }, diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index af525c8..cd46299 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -23,3 +23,8 @@ jobs: # A new branch push has an all-zero "before" SHA; skip the bump check then. if [[ "$BASE_REF" =~ ^0+$ ]]; then BASE_REF=""; fi bash scripts/check-release.sh "$BASE_REF" + + - name: SDD script tests + run: | + bash tests/claude-code/test-sdd-workspace.sh + bash tests/claude-code/test-sdd-review-context.sh diff --git a/.kimi-plugin/plugin.json b/.kimi-plugin/plugin.json index dd5c2db..ca96825 100644 --- a/.kimi-plugin/plugin.json +++ b/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "superpowers-custom", - "version": "6.0.4-fork.10", + "version": "6.0.4-fork.11", "description": "An agentic skills framework and software development methodology.", "author": { "name": "stanlrt" diff --git a/AGENTS.md b/AGENTS.md index d98f0c2..d6f2620 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,13 +33,22 @@ These skills carry custom behavior (everything else tracks upstream verbatim): `scripts/plan-batches` (python3, stdlib-only) computes the batch topology deterministically — rejecting phantom edges whose `consumes=` names a theme rather than a symbol, so controllers stop over-serializing "related" tasks. + Review packages and task briefs carry the AGENTS.md / CLAUDE.md files on + the path from the repo root to each changed (or brief-listed) file, + gathered by `scripts/instruction-files`; review packages also widen each + hunk to its enclosing function (`git diff --function-context`, capped per + file by `SDD_CONTEXT_CAP`). Reviewer and implementer templates treat those + files as binding and check new code against the unchanged code that + encloses it. `tests/claude-code/test-sdd-review-context.sh` covers the + scripts and runs in CI. - **finishing-a-development-branch** — live-browser check of heavy UI changes with `chrome-devtools-axi` (skipped when axi is not installed); PR body from the repo's PR template via `--body-file`; after opening, monitor CI + Copilot + Code-Quality comments. - **requesting-code-review** / **verification-before-completion** — Minor findings are fixed before the branch is done; heavy UI changes need live-browser evidence - when axi is installed. + when axi is installed. The code reviewer reads a review package built by the + SDD `review-package` script. - **using-git-worktrees** — GitHub issue → linked branch entry points. - **writing-plans** / **brainstorming** — no approval stop between spec approval and branch finish: after saving the plan, execution starts with diff --git a/docs/superpowers/plans/2026-11-02-review-enclosing-context.md b/docs/superpowers/plans/2026-11-02-review-enclosing-context.md new file mode 100644 index 0000000..72122ef --- /dev/null +++ b/docs/superpowers/plans/2026-11-02-review-enclosing-context.md @@ -0,0 +1,1120 @@ +# Review Enclosing Context Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers-custom:subagent-driven-development (recommended) or superpowers-custom:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Review packages and task briefs carry every governing AGENTS.md / CLAUDE.md (gathered by script) and each hunk's whole enclosing function, and the reviewer/implementer templates treat both as binding inputs. + +**Architecture:** A new shared helper `scripts/instruction-files` walks root → each path's directory and prints the governing instruction files with line numbers. `review-package` calls it against the HEAD tree-ish and widens hunks with `git diff --function-context`, falling back per file to `-U10` over a line cap. `task-brief` calls it on the paths in the brief's `**Files:**` block. Templates gain a binding-instructions rule and one generic checklist item. + +**Tech Stack:** bash (3.2-compatible: no `mapfile`, no associative arrays), git, POSIX awk (mawk-compatible), GitHub Actions. + +**Spec:** `docs/superpowers/specs/2026-11-02-review-enclosing-context-design.md` + +## Global Constraints + +- Stack-agnostic: no framework, language, product, or company names in any shipped file (scripts, templates, skill docs, tests). The test fixture uses neutral JavaScript-looking text with no framework identifiers. +- Section heading printed by `instruction-files`: `## Instruction files (binding)` — exact. +- Instruction-file content lines are formatted with awk `printf "%6d %s\n", NR, $0` (6-wide right-aligned number, two spaces, the line). +- Duplicate heading format: `### — identical to ` (em dash U+2014). +- Capped-file marker, directly above that file's `diff --git` line: `# context capped: (function context over lines; -U10 shown)`. +- Cap: env `SDD_CONTEXT_CAP`, default `400`, positive integer, else exit 2. +- Checklist sentence, verbatim in every reviewer template and (adapted to first person only where noted) the implementer self-review: "For each piece of new state, effect, resource or side effect, check the unchanged code that encloses or calls it: lifecycle and remount behaviour, reactivity/keying, transaction or request scope, loops and limits. A bug can come from new code placed inside old code." +- A broken instruction-file rule is Important by default; findings cite the rule as `path:line`. +- All scripts: `#!/usr/bin/env bash`, `set -euo pipefail`, LF line endings, executable bit. +- Version: `6.0.4-fork.11`. +- Agent-facing docs state current behaviour only (no "previously", no rename history). + +--- + +### Task 1: `instruction-files` helper + +**Files:** +- Create: `skills/subagent-driven-development/scripts/instruction-files` +- Create: `tests/claude-code/test-sdd-review-context.sh` + +**Interfaces:** +- Consumes: nothing. +- Produces: `instruction-files [--tree TREEISH] PATH...` — PATHs repo-root-relative; works from any cwd inside the repo; prints nothing (exit 0) when no file governs any PATH or no PATH is given; exit 2 on usage error or a bad TREEISH. Test file `tests/claude-code/test-sdd-review-context.sh` with helpers `pass`, `fail`, `assert_contains FILE NEEDLE DESC`, `assert_not_contains FILE NEEDLE DESC`, `assert_has_line FILE LINE DESC`, `filler N PREFIX`, `make_fixture`, globals `REPO`, `TEST_ROOT`, `SDD_SCRIPTS`, `GIT_ID`, and a `main` that later tasks extend. + +- [ ] **Step 1: Write the failing test** + +Create `tests/claude-code/test-sdd-review-context.sh` (then `chmod +x`): + +```bash +#!/usr/bin/env bash +# Tests for SDD review context: scripts/instruction-files collects the +# AGENTS.md / CLAUDE.md files that govern a set of paths, review-package +# inlines them and widens each hunk to its enclosing function, and +# task-brief appends them to a task brief. +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="" +REPO="" +GIT_ID=(-c user.email=t@example.com -c user.name=t -c commit.gpgsign=false) + +pass() { echo " [PASS] $1"; } +fail() { + echo " [FAIL] $1" + FAILURES=$((FAILURES + 1)) +} + +# assert_contains FILE NEEDLE DESCRIPTION — NEEDLE appears anywhere in FILE. +assert_contains() { + if grep -qF -- "$2" "$1"; then pass "$3"; else fail "$3"; echo " missing: $2"; fi +} + +# assert_not_contains FILE NEEDLE DESCRIPTION +assert_not_contains() { + if grep -qF -- "$2" "$1"; then fail "$3"; echo " unexpected: $2"; else pass "$3"; fi +} + +# assert_has_line FILE LINE DESCRIPTION — LINE is a whole line of FILE. +assert_has_line() { + if grep -qxF -- "$2" "$1"; then pass "$3"; else fail "$3"; echo " missing line: $2"; fi +} + +cleanup() { + if [[ -n "$TEST_ROOT" && -d "$TEST_ROOT" ]]; then + rm -rf "$TEST_ROOT" + fi +} + +# filler N PREFIX — print N indented, unique filler lines. +filler() { + local i + for ((i = 1; i <= $1; i++)); do + printf ' const %s%d = %d;\n' "$2" "$i" "$i" + done +} + +# make_fixture — a repo with instruction files at several depths and two +# source files. No .gitattributes: function context comes from git's +# default funcname rule. +make_fixture() { + git init -q -b main "$TEST_ROOT/repo" + REPO="$(cd "$TEST_ROOT/repo" && git rev-parse --show-toplevel)" + mkdir -p "$REPO/pkg/sub/deep" "$REPO/pkg/other" + printf '# Root rules\nROOT_RULE: keep functions small.\n' > "$REPO/AGENTS.md" + printf '# Sub rules\nNESTED_RULE: never read a whole collection in one call.\n' > "$REPO/pkg/sub/AGENTS.md" + cp "$REPO/pkg/sub/AGENTS.md" "$REPO/pkg/sub/CLAUDE.md" + printf 'DEEP_RULE: deep only.\n' > "$REPO/pkg/sub/deep/AGENTS.md" + printf 'SIBLING_RULE: other only.\n' > "$REPO/pkg/other/AGENTS.md" + printf 'readme\n' > "$REPO/README.md" + printf 'export const other = 1;\n' > "$REPO/pkg/other/thing.js" + { + echo 'function renderPanel(items) {' + filler 12 before + echo ' wrapWithKey(items, () => {' + echo ' let count = 0;' + echo ' });' + filler 12 after + echo '} // end renderPanel' + echo '' + echo 'function trailing() {' + echo ' return 1;' + echo '}' + } > "$REPO/pkg/sub/widget.js" + { + echo 'function longTail() {' + echo ' let seed = 0;' + filler 60 tail + echo ' const farMarker = 1;' + echo '} // end longTail' + } > "$REPO/pkg/sub/long.js" + ( cd "$REPO" && git add -A && git "${GIT_ID[@]}" commit -qm c1 ) +} + +test_instruction_files() { + echo "--- instruction-files ---" + local out="$TEST_ROOT/if-widget.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" pkg/sub/widget.js ) > "$out" + assert_has_line "$out" "## Instruction files (binding)" "section heading printed" + assert_has_line "$out" "- AGENTS.md" "root file listed" + assert_has_line "$out" "- pkg/sub/AGENTS.md" "nested file listed" + assert_has_line "$out" " 2 ROOT_RULE: keep functions small." "root content with line numbers" + assert_has_line "$out" " 2 NESTED_RULE: never read a whole collection in one call." "nested content with line numbers" + assert_has_line "$out" "### pkg/sub/CLAUDE.md — identical to pkg/sub/AGENTS.md" "identical CLAUDE.md deduped" + if [[ "$(grep -cF NESTED_RULE "$out")" -eq 1 ]]; then + pass "duplicate content printed once" + else + fail "duplicate content printed once" + fi + assert_not_contains "$out" "SIBLING_RULE" "sibling directory excluded" + assert_not_contains "$out" "DEEP_RULE" "child directory excluded" + local root_line nested_line + root_line="$(grep -nxF -- "- AGENTS.md" "$out" | cut -d: -f1)" + nested_line="$(grep -nxF -- "- pkg/sub/AGENTS.md" "$out" | cut -d: -f1)" + if [[ -n "$root_line" && -n "$nested_line" && "$root_line" -lt "$nested_line" ]]; then + pass "root listed before nested" + else + fail "root listed before nested" + fi + + out="$TEST_ROOT/if-new.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" pkg/sub/newdir/new.js ) > "$out" + assert_contains "$out" "NESTED_RULE" "path in a missing directory still gets ancestor files" + + out="$TEST_ROOT/if-subdir.txt" + ( cd "$REPO/pkg/sub" && "$SDD_SCRIPTS/instruction-files" pkg/sub/widget.js ) > "$out" + assert_contains "$out" "NESTED_RULE" "root-relative paths work from a subdirectory" + + out="$TEST_ROOT/if-none.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" ) > "$out" + if [[ ! -s "$out" ]]; then pass "no paths, no output"; else fail "no paths, no output"; fi + + printf 'UNCOMMITTED_RULE: working tree only.\n' >> "$REPO/pkg/sub/AGENTS.md" + out="$TEST_ROOT/if-tree.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" --tree HEAD pkg/sub/widget.js ) > "$out" + assert_not_contains "$out" "UNCOMMITTED_RULE" "--tree reads the tree, not the working tree" + out="$TEST_ROOT/if-wt.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" pkg/sub/widget.js ) > "$out" + assert_contains "$out" " 3 UNCOMMITTED_RULE: working tree only." "default mode reads the working tree" + ( cd "$REPO" && git checkout -q -- pkg/sub/AGENTS.md ) + + if ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" --tree nosuchref x.js ) >/dev/null 2>&1; then + fail "bad TREEISH exits non-zero" + else + pass "bad TREEISH exits non-zero" + fi +} + +main() { + echo "=== Test: sdd review context ===" + + TEST_ROOT="$(mktemp -d)" + trap cleanup EXIT + + make_fixture + test_instruction_files + + echo "" + if [[ "$FAILURES" -ne 0 ]]; then + echo "FAILED: $FAILURES assertion(s)." + exit 1 + fi + echo "PASS" +} + +main "$@" +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `bash tests/claude-code/test-sdd-review-context.sh` +Expected: FAIL lines (instruction-files does not exist: "No such file or directory"), final `FAILED: N assertion(s).` + +- [ ] **Step 3: Write the implementation** + +Create `skills/subagent-driven-development/scripts/instruction-files` (then `chmod +x`): + +```bash +#!/usr/bin/env bash +# Print the instruction files (AGENTS.md, CLAUDE.md) that govern a set of +# paths, as one markdown section a reviewer or implementer reads with the +# change. A file governs a path when it sits in the repo root or in any +# directory on the way down to that path's directory. +# +# A nested instruction file holds rules no brief repeats, and a harness loads +# it only when an agent happens to read a file in that directory. Gathering +# the files by script, not by memory, puts every governing rule in front of +# the subagent. +# +# Usage: instruction-files [--tree TREEISH] PATH... +# PATH repo-root-relative path. It need not exist: a file a task +# will create still gets the files of its existing ancestors. +# --tree TREEISH read the instruction files from this tree (a commit, or a +# `snapshot` tree SHA) instead of the working tree. +# +# Output: nothing when no instruction file governs any PATH. Otherwise a +# "## Instruction files (binding)" section: the file paths (root first, then +# by depth), then each file's content with line numbers, so a finding can +# cite path:line. A file byte-identical to one already printed gets a heading +# that names the first file instead of its content. `@file` imports are not +# resolved. +set -euo pipefail + +usage() { + echo "usage: instruction-files [--tree TREEISH] PATH..." >&2 + exit 2 +} + +tree="" +if [ "${1:-}" = "--tree" ]; then + [ $# -ge 2 ] || usage + tree=$2 + shift 2 + git rev-parse --verify --quiet "${tree}^{tree}" >/dev/null || { echo "bad TREEISH: $tree" >&2; exit 2; } +fi + +cd "$(git rev-parse --show-toplevel)" + +# is_file PATH — true when PATH is a regular file in the source. +is_file() { + if [ -n "$tree" ]; then + [ "$(git cat-file -t "${tree}:$1" 2>/dev/null)" = blob ] + else + [ -f "$1" ] + fi +} + +# show PATH — print PATH's content from the source. +show() { + if [ -n "$tree" ]; then + git cat-file blob "${tree}:$1" + else + cat -- "$1" + fi +} + +# blob_id PATH — git blob SHA of PATH's content; equal SHAs mean equal bytes. +blob_id() { + if [ -n "$tree" ]; then + git rev-parse "${tree}:$1" + else + git hash-object -- "$1" + fi +} + +# candidates PATH... — AGENTS.md and CLAUDE.md in the root and in every +# directory on the way down to each PATH's directory, one per line. +candidates() { + local p d acc part + local parts + for p in "$@"; do + p=${p#./} + printf '%s\n' AGENTS.md CLAUDE.md + d=$(dirname -- "$p") + [ "$d" = . ] && continue + acc="" + IFS=/ read -r -a parts <<< "$d" + for part in "${parts[@]}"; do + acc=${acc:+$acc/}$part + printf '%s\n' "$acc/AGENTS.md" "$acc/CLAUDE.md" + done + done +} + +tab=$(printf '\t') +found=() +while IFS= read -r f; do + if is_file "$f"; then + found+=("$f") + fi +done < <(candidates "$@" | awk -F/ '{ print NF "\t" $0 }' | LC_ALL=C sort -t "$tab" -k1,1n -k2 -u | cut -f2-) + +if [ ${#found[@]} -eq 0 ]; then + exit 0 +fi + +echo "## Instruction files (binding)" +echo +echo "These files govern the files in scope. Their rules are binding constraints." +echo "Cite a rule as path:line." +echo +for f in "${found[@]}"; do + echo "- $f" +done + +seen_ids=() +seen_paths=() +for f in "${found[@]}"; do + id=$(blob_id "$f") + dup="" + i=0 + while [ "$i" -lt "${#seen_ids[@]}" ]; do + if [ "${seen_ids[$i]}" = "$id" ]; then + dup=${seen_paths[$i]} + break + fi + i=$((i + 1)) + done + echo + if [ -n "$dup" ]; then + echo "### $f — identical to $dup" + else + echo "### $f" + show "$f" | awk '{ printf "%6d %s\n", NR, $0 }' + seen_ids+=("$id") + seen_paths+=("$f") + fi +done +``` + +Note: `[ "$d" = . ] && continue` inside the `for` is safe under `set -e` (a non-final `&&` operand). If shellcheck or a bash 3.2 run complains about `"${#seen_ids[@]}"` on an empty array under `set -u`, initialise with `seen_ids=()` (already done) — `${#arr[@]}` is valid on an empty declared array. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `bash tests/claude-code/test-sdd-review-context.sh` +Expected: every line `[PASS]`, final line `PASS`. +Also run: `bash tests/claude-code/test-sdd-workspace.sh` → `PASS` (unchanged scripts, sanity). + +- [ ] **Step 5: Hand back for review (no commit — the controller commits).** + +--- + +### Task 2: `review-package` — instruction files and enclosing context + +**Files:** +- Modify: `skills/subagent-driven-development/scripts/review-package` (whole file) +- Modify: `tests/claude-code/test-sdd-review-context.sh` (add `make_change`, `package_path`, `test_review_package`; call it from `main`) + +**Interfaces:** +- Consumes: `instruction-files [--tree TREEISH] PATH...` (Task 1); test helpers from Task 1. +- Produces: package layout — header lines, `## Files changed`, optional `## Instruction files (binding)` section, `## Diff`. Header always contains `# Context: each hunk shows its whole enclosing function (cap: lines per file)`; when any file is capped, also `# Context capped (-U10 shown): ...`. The `wrote : N file(s) changed, B bytes` stdout line is unchanged. + +- [ ] **Step 1: Write the failing test** + +In `tests/claude-code/test-sdd-review-context.sh`, add these functions after `test_instruction_files`: + +```bash +# make_change — commit c2: one-line edits deep inside widget.js and long.js, +# an edit in pkg/other, and a new 60-line file. +make_change() { + ( cd "$REPO" \ + && sed -i.bak 's/ let count = 0;/ let count = items.length;/' pkg/sub/widget.js \ + && sed -i.bak 's/ let seed = 0;/ let seed = 1;/' pkg/sub/long.js \ + && rm -f pkg/sub/*.bak \ + && printf 'export const other = 2;\n' > pkg/other/thing.js \ + && { echo 'function fresh() {'; filler 60 fresh; echo '}'; } > pkg/sub/fresh.js \ + && git add -A && git "${GIT_ID[@]}" commit -qm c2 ) +} + +# package_path OUTPUT — the package path from review-package's "wrote" line. +package_path() { + printf '%s\n' "$1" | sed -n 's/^wrote \(.*\): [0-9].*$/\1/p' +} + +test_review_package() { + echo "--- review-package ---" + make_change + local out pkg + + out="$(cd "$REPO" && "$SDD_SCRIPTS/review-package" HEAD~1 HEAD)" + pkg="$(package_path "$out")" + assert_has_line "$pkg" "## Instruction files (binding)" "package has the instruction section" + assert_has_line "$pkg" " 2 ROOT_RULE: keep functions small." "root rule inlined" + assert_has_line "$pkg" " 2 NESTED_RULE: never read a whole collection in one call." "nested rule inlined" + assert_contains "$pkg" "SIBLING_RULE" "rules of every changed file's directories (pkg/other changed)" + assert_not_contains "$pkg" "DEEP_RULE" "directory below a changed file excluded" + local files_line instr_line diff_line + files_line="$(grep -nxF '## Files changed' "$pkg" | cut -d: -f1)" + instr_line="$(grep -nxF '## Instruction files (binding)' "$pkg" | cut -d: -f1)" + diff_line="$(grep -nxF '## Diff' "$pkg" | cut -d: -f1)" + if [[ -n "$files_line" && -n "$instr_line" && -n "$diff_line" \ + && "$files_line" -lt "$instr_line" && "$instr_line" -lt "$diff_line" ]]; then + pass "section order: files changed, instruction files, diff" + else + fail "section order: files changed, instruction files, diff" + fi + assert_has_line "$pkg" " function renderPanel(items) {" "enclosing function opening line" + assert_has_line "$pkg" " } // end renderPanel" "enclosing function closing line" + assert_has_line "$pkg" " const farMarker = 1;" "default cap keeps the whole long function" + assert_contains "$pkg" "# Context: each hunk shows its whole enclosing function (cap: 400 lines per file)" "header names the context rule" + assert_not_contains "$pkg" "# context capped:" "nothing capped at the default cap" + + out="$(cd "$REPO" && SDD_CONTEXT_CAP=45 "$SDD_SCRIPTS/review-package" HEAD~1 HEAD)" + pkg="$(package_path "$out")" + assert_has_line "$pkg" "# context capped: pkg/sub/long.js (function context over 45 lines; -U10 shown)" "over-cap file marked" + assert_contains "$pkg" "# Context capped (-U10 shown): pkg/sub/long.js" "header lists capped files" + assert_not_contains "$pkg" "farMarker" "capped file falls back to -U10" + assert_not_contains "$pkg" "# context capped: pkg/sub/widget.js" "under-cap file not marked" + assert_has_line "$pkg" " } // end renderPanel" "under-cap file keeps function context" + assert_not_contains "$pkg" "# context capped: pkg/sub/fresh.js" "new file never marked capped" + + if ( cd "$REPO" && SDD_CONTEXT_CAP=abc "$SDD_SCRIPTS/review-package" HEAD~1 HEAD ) >/dev/null 2>&1; then + fail "non-numeric SDD_CONTEXT_CAP rejected" + else + pass "non-numeric SDD_CONTEXT_CAP rejected" + fi + + out="$(cd "$REPO" && "$SDD_SCRIPTS/review-package" HEAD~1 HEAD -- pkg/sub/widget.js)" + pkg="$(package_path "$out")" + assert_contains "$pkg" "NESTED_RULE" "pathspec run keeps the scoped file's rules" + assert_not_contains "$pkg" "SIBLING_RULE" "pathspec run drops out-of-scope rules" + assert_not_contains "$pkg" "pkg/sub/long.js" "pathspec run drops out-of-scope diffs" + + printf 'SNAPSHOT_RULE: from the working tree.\n' >> "$REPO/pkg/sub/AGENTS.md" + local before after + before="$(cd "$REPO" && git rev-parse 'HEAD^{tree}')" + after="$(cd "$REPO" && "$SDD_SCRIPTS/snapshot")" + out="$(cd "$REPO" && "$SDD_SCRIPTS/review-package" "$before" "$after")" + pkg="$(package_path "$out")" + assert_has_line "$pkg" " 3 SNAPSHOT_RULE: from the working tree." "instruction files read from the HEAD tree-ish (snapshot)" + ( cd "$REPO" && git checkout -q -- pkg/sub/AGENTS.md ) +} +``` + +In `main`, add `test_review_package` on the line after `test_instruction_files`. + +- [ ] **Step 2: Run test to verify it fails** + +Run: `bash tests/claude-code/test-sdd-review-context.sh` +Expected: `--- review-package ---` assertions FAIL (no instruction section, no `# Context:` header, `farMarker` absent at default `-U10`), final `FAILED: N assertion(s).` + +- [ ] **Step 3: Write the implementation** + +Replace `skills/subagent-driven-development/scripts/review-package` with: + +```bash +#!/usr/bin/env bash +# Generate a review package: a stat summary, the instruction files that +# govern the changed files, and the net diff with each hunk widened to its +# enclosing function, written to a file the reviewer reads in one call. +# +# This fork runs the no-commit model: implementer subagents leave their work +# in the working tree and the controller commits after review. BASE and HEAD +# are therefore tree-ish (tree SHAs from `scripts/snapshot` or `HEAD^{tree}`), +# not commits — though plain commits still work, since `git diff A B` accepts +# either. There is no commit list to show because the task is not yet +# committed. +# +# Instruction files: every AGENTS.md / CLAUDE.md from the repo root down to +# each changed file's directory, read from HEAD (the tree under review, not +# the working tree, which in a parallel batch holds other tasks' edits), via +# the sibling `instruction-files` helper. +# +# Context: each file's diff uses `git diff --function-context`, so a hunk +# shows its whole enclosing function as git's funcname rule (or the repo's +# .gitattributes diff driver) finds it. When a file's function-context diff +# is over the cap and its -U10 diff is smaller, the package shows the -U10 +# diff for that file, marked with a "# context capped:" line. +# Cap: SDD_CONTEXT_CAP lines per file (default 400). +# +# Usage: review-package BASE HEAD [-- PATHSPEC...] +# BASE tree-ish before the task (e.g. HEAD^{tree}, or a snapshot SHA) +# HEAD tree-ish after the task (e.g. `scripts/snapshot` output) +# -- PATHSPEC limit the diff to these paths — use for one task inside a +# parallel disjoint-file batch, so each reviewer sees only its +# task's files even though all batch work sits in one tree. +# +# OUTFILE is auto-named under the SDD workspace (/.superpowers/sdd/, +# resolved via the sibling `sdd-workspace` helper so every SDD script agrees on +# one location) — unique per range (and per pathspec), so concurrent sessions +# and parallel per-task reviews never collide and a re-review after fixes +# always gets a distinctly named file. +set -euo pipefail + +if [ $# -lt 2 ]; then + echo "usage: review-package BASE HEAD [-- PATHSPEC...]" >&2 + exit 2 +fi + +base=$1 +head=$2 +shift 2 + +paths=() +if [ $# -gt 0 ]; then + if [ "$1" = "--" ]; then + shift + paths=("$@") + else + echo "usage: review-package BASE HEAD [-- PATHSPEC...]" >&2 + exit 2 + fi +fi + +cap=${SDD_CONTEXT_CAP:-400} +case $cap in + ''|*[!0-9]*|0) echo "SDD_CONTEXT_CAP must be a positive integer: $cap" >&2; exit 2 ;; +esac + +git rev-parse --verify --quiet "$base^{tree}" >/dev/null 2>&1 || git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; } +git rev-parse --verify --quiet "$head^{tree}" >/dev/null 2>&1 || git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; } + +scripts=$(cd "$(dirname "$0")" && pwd) +dir=$("$scripts/sdd-workspace") +name="review-$(git rev-parse --short "$base")..$(git rev-parse --short "$head")" +if [ ${#paths[@]} -gt 0 ]; then + # Keep the file unique when several per-task reviews share one BASE..HEAD + # range but cover different files (a parallel batch). + suffix=$(printf '%s\n' "${paths[@]}" | cksum | cut -d' ' -f1) + name="${name}-${suffix}" +fi +out="$dir/${name}.diff" + +tmp=$(mktemp -d "$dir/review-package.XXXXXX") +trap 'rm -rf "$tmp"' EXIT + +changed=() +while IFS= read -r f; do + changed+=("$f") +done < <(git diff --name-only "$base" "$head" ${paths[@]:+-- "${paths[@]}"}) + +"$scripts/instruction-files" --tree "$head" ${changed[@]+"${changed[@]}"} > "$tmp/instr" + +git diff --function-context -U10 "$base" "$head" ${paths[@]:+-- "${paths[@]}"} > "$tmp/wide" +git diff -U10 "$base" "$head" ${paths[@]:+-- "${paths[@]}"} > "$tmp/plain" + +# Both diffs cover the same range and pathspec, so they list the same files +# in the same order. Pair them file by file and keep the function-context +# chunk unless it is over the cap and the -U10 chunk is smaller (a new or +# fully rewritten file has equal chunks and keeps its full text). +: > "$tmp/capped" +awk -v cap="$cap" -v capped="$tmp/capped" ' + FNR == 1 { src++ } + /^diff --git / { n[src]++ } + n[src] { text[src, n[src]] = text[src, n[src]] $0 "\n"; len[src, n[src]]++ } + END { + for (i = 1; i <= n[1]; i++) { + if (len[1, i] > cap && len[2, i] < len[1, i]) { + hdr = text[2, i] + sub(/\n.*/, "", hdr) + path = hdr + sub(/^diff --git a\/.* b\//, "", path) + printf "# context capped: %s (function context over %d lines; -U10 shown)\n", path, cap + printf "%s", text[2, i] + print path > capped + } else { + printf "%s", text[1, i] + } + } + } +' "$tmp/wide" "$tmp/plain" > "$tmp/diff" + +{ + echo "# Review package: ${base}..${head}" + if [ ${#paths[@]} -gt 0 ]; then + echo "# Scoped to: ${paths[*]}" + fi + echo "# (no-commit model: changes are uncommitted in the working tree)" + echo "# Context: each hunk shows its whole enclosing function (cap: ${cap} lines per file)" + if [ -s "$tmp/capped" ]; then + echo "# Context capped (-U10 shown): $(paste -sd' ' "$tmp/capped")" + fi + echo + echo "## Files changed" + git diff --stat "$base" "$head" ${paths[@]:+-- "${paths[@]}"} + echo + if [ -s "$tmp/instr" ]; then + cat "$tmp/instr" + echo + fi + echo "## Diff" + cat "$tmp/diff" +} > "$out" + +echo "wrote ${out}: ${#changed[@]} file(s) changed, $(wc -c < "$out" | tr -d ' ') bytes" +``` + +Note on the awk: when `$tmp/wide` is empty (no changes) the first line read is from `$tmp/plain`, but then `plain` is empty too, so `n[1]` is unset and nothing prints. If the implementer finds `paste -sd' '` unavailable on a target, `tr '\n' ' '` plus trailing-space trim is equivalent. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash tests/claude-code/test-sdd-review-context.sh` → final `PASS`. +Run: `bash tests/claude-code/test-sdd-workspace.sh` → final `PASS` (its `wrote ... : [0-9]` parse still matches). + +- [ ] **Step 5: Hand back for review (no commit — the controller commits).** + +--- + +### Task 3: `task-brief` — instruction files of the task's files + +**Files:** +- Modify: `skills/subagent-driven-development/scripts/task-brief` (whole file) +- Modify: `tests/claude-code/test-sdd-review-context.sh` (add `brief_path`, `test_task_brief`; call it from `main` after `test_review_package`) + +**Interfaces:** +- Consumes: `instruction-files PATH...` (Task 1); test helpers (Tasks 1–2). +- Produces: briefs end with the `## Instruction files (binding)` section when the task's `**Files:**` block names a governed path. The `wrote : N lines` stdout line is unchanged. + +- [ ] **Step 1: Write the failing test** + +Add after `test_review_package`: + +```bash +# brief_path OUTPUT — the brief path from task-brief's "wrote" line. +brief_path() { + printf '%s\n' "$1" | sed -n 's/^wrote \(.*\): [0-9][0-9]* lines$/\1/p' +} + +test_task_brief() { + echo "--- task-brief ---" + cat > "$REPO/plan.md" <<'PLAN' +# Plan + +### Task 1: Sub change + +**Files:** +- Modify: `pkg/sub/widget.js:10-20` +- Test: `pkg/sub/widget.test.js` + +Do the sub change. + +### Task 2: Root change + +**Files:** +- Modify: `README.md` + +Do the root change. + +### Task 3: No files + +Do something without a Files block. + +### Task 4: New directory + +**Files:** +- Create: `pkg/sub/newdir/new.js` + +Create it. +PLAN + local out brief + + out="$(cd "$REPO" && "$SDD_SCRIPTS/task-brief" plan.md 1)" + brief="$(brief_path "$out")" + assert_contains "$brief" "Do the sub change." "brief keeps the task text" + assert_has_line "$brief" " 2 NESTED_RULE: never read a whole collection in one call." "Modify path with a line range gets nested rules" + assert_has_line "$brief" " 2 ROOT_RULE: keep functions small." "brief gets root rules" + assert_not_contains "$brief" "SIBLING_RULE" "brief excludes unrelated directories" + assert_not_contains "$brief" "Do the root change." "brief stops at the next task" + + out="$(cd "$REPO" && "$SDD_SCRIPTS/task-brief" plan.md 2)" + brief="$(brief_path "$out")" + assert_contains "$brief" "ROOT_RULE" "root-level file gets root rules" + assert_not_contains "$brief" "NESTED_RULE" "root-level file excludes nested rules" + + out="$(cd "$REPO" && "$SDD_SCRIPTS/task-brief" plan.md 3)" + brief="$(brief_path "$out")" + assert_not_contains "$brief" "## Instruction files" "no Files block, no section" + + out="$(cd "$REPO" && "$SDD_SCRIPTS/task-brief" plan.md 4)" + brief="$(brief_path "$out")" + assert_contains "$brief" "NESTED_RULE" "Create path in a new directory gets ancestor rules" + + mkdir -p "$TEST_ROOT/nogit" + cp "$REPO/plan.md" "$TEST_ROOT/nogit/plan.md" + if ( cd "$TEST_ROOT/nogit" && GIT_CEILING_DIRECTORIES="$TEST_ROOT" \ + "$SDD_SCRIPTS/task-brief" plan.md 1 brief.md ) >/dev/null 2>&1 \ + && ! grep -qF "## Instruction files" "$TEST_ROOT/nogit/brief.md"; then + pass "outside a git repo: brief written, no section" + else + fail "outside a git repo: brief written, no section" + fi +} +``` + +In `main`, add `test_task_brief` on the line after `test_review_package`. + +- [ ] **Step 2: Run test to verify it fails** + +Run: `bash tests/claude-code/test-sdd-review-context.sh` +Expected: `--- task-brief ---` rule assertions FAIL, final `FAILED: N assertion(s).` + +- [ ] **Step 3: Write the implementation** + +Replace `skills/subagent-driven-development/scripts/task-brief` with: + +```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. +# +# The brief ends with the instruction files (AGENTS.md / CLAUDE.md) that +# govern the task's files: every backticked path on a list line of the +# task's **Files:** block (a trailing :N or :N-M line range is stripped), +# resolved by the sibling `instruction-files` helper against the working +# tree. No Files block, no governing file, or no git repo: no section. +# +# 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). +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; } + +scripts=$(cd "$(dirname "$0")" && pwd) + +if [ $# -eq 3 ]; then + out=$3 +else + dir=$("$scripts/sdd-workspace") + 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 + +files=() +while IFS= read -r f; do + files+=("$f") +done < <(awk ' + /^\*\*Files:\*\*/ { inblock = 1; next } + inblock && /^[ \t]*[-*][ \t]/ { + line = $0 + while (match(line, /`[^`]+`/)) { + tok = substr(line, RSTART + 1, RLENGTH - 2) + sub(/:[0-9]+(-[0-9]+)?$/, "", tok) + print tok + line = substr(line, RSTART + RLENGTH) + } + next + } + inblock && /^[ \t]*$/ { next } + { inblock = 0 } +' "$out") + +if [ ${#files[@]} -gt 0 ] && git rev-parse --show-toplevel >/dev/null 2>&1; then + section=$("$scripts/instruction-files" "${files[@]}") + if [ -n "$section" ]; then + printf '\n%s\n' "$section" >> "$out" + fi +fi + +echo "wrote ${out}: $(wc -l < "$out" | tr -d ' ') lines" +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash tests/claude-code/test-sdd-review-context.sh` → final `PASS`. +Run: `bash tests/claude-code/test-sdd-workspace.sh` → final `PASS`. + +- [ ] **Step 5: Hand back for review (no commit — the controller commits).** + +--- + +### Task 4: Templates and skill docs + +**Files:** +- Modify: `skills/subagent-driven-development/task-reviewer-prompt.md` +- Modify: `skills/subagent-driven-development/implementer-prompt.md` +- Modify: `skills/subagent-driven-development/refactor-reviewer-prompt.md` +- Modify: `skills/requesting-code-review/code-reviewer.md` +- Modify: `skills/requesting-code-review/SKILL.md` +- Modify: `skills/subagent-driven-development/SKILL.md` +- Modify: `AGENTS.md` + +**Interfaces:** +- Consumes: the package/brief formats from the Global Constraints (`## Instruction files (binding)`, `# context capped:`, `SDD_CONTEXT_CAP`). No code dependency on Tasks 1–3. +- Produces: nothing other tasks use. + +Verification for this task is textual: after the edits, run the greps in Step 8. + +- [ ] **Step 1: `task-reviewer-prompt.md`** + +(a) In `## Diff Under Review`, replace + +``` + commit list. The diff's context lines ARE the changed files: do not Read a + changed file separately unless a hunk you must judge is cut off + mid-function — and say so in your report. Do not re-run git commands. +``` + +with + +``` + commit list. Each hunk shows its whole enclosing function; a file marked + `# context capped` shows 10 lines of context instead. Do not Read a + changed file separately unless a hunk you must judge is cut off — and + say so in your report. Do not re-run git commands. +``` + +(b) Directly after the line ` checking the call sites is the right method.` insert: + +``` + New code inside unchanged code is a named risk by default: when new + state, an effect, a resource, or a side effect sits inside or is called + from code the diff does not show (a capped file, a caller), one focused + read of that code is expected. +``` + +(c) Insert a new section directly before ` ## Do Not Trust the Report`: + +``` + ## Binding Instructions + + The diff file's "Instruction files (binding)" section holds every + AGENTS.md / CLAUDE.md that governs the changed files, with line numbers. + Their rules bind this task like the spec does. A change that breaks one + is an Important finding by default: cite the rule as path:line next to + the code's file:line. + +``` + +(d) In `## Part 2: Code Quality`, under `**Code quality:**`, after ` - Edge cases handled?` add: + +``` + - For each piece of new state, effect, resource or side effect, check the + unchanged code that encloses or calls it: lifecycle and remount + behaviour, reactivity/keying, transaction or request scope, loops and + limits. A bug can come from new code placed inside old code. +``` + +(e) In the `**Placeholders:**` list, replace the `[DIFF_FILE]` bullet's text `wrote; the package never enters the controller's context)` with `wrote; the package never enters the controller's context). It carries the governing instruction files and each hunk's enclosing function.` + +- [ ] **Step 2: `implementer-prompt.md`** + +(a) Replace + +``` + Read your task brief first: [BRIEF_FILE] + It contains the full task text from the plan. +``` + +with + +``` + Read your task brief first: [BRIEF_FILE] + It contains the full task text from the plan. Its "Instruction files + (binding)" section, when present, holds the AGENTS.md / CLAUDE.md rules + that govern your files. Follow them like the task text. When a rule + shaped a decision or ruled out an approach, cite it (path:line) in your + report. +``` + +(b) In `## Before Reporting Back: Self-Review`, under `**Quality:**`, after ` - Is the code clean and maintainable?` add: + +``` + - For each piece of new state, effect, resource or side effect, did I + check the unchanged code that encloses or calls it: lifecycle and + remount behaviour, reactivity/keying, transaction or request scope, + loops and limits? A bug can come from new code placed inside old code. +``` + +- [ ] **Step 3: `refactor-reviewer-prompt.md`** + +(a) In `## The Branch Under Review`, after the paragraph ending ``and `git diff [BASE_SHA]..[HEAD_SHA]`.`` add a blank line and: + +``` + The diff file's "Instruction files (binding)" section holds every + AGENTS.md / CLAUDE.md that governs the changed files, with line numbers. + A branch change that breaks one of their rules is Refactor-Critical: the + cited rule (path:line) is the evidence. +``` + +(b) In `## Design lens (Advisory findings)`, after the bullet ` - Naming drift — the same concept named differently across tasks` add: + +``` + - For each piece of new state, effect, resource or side effect, check the + unchanged code that encloses or calls it: lifecycle and remount + behaviour, reactivity/keying, transaction or request scope, loops and + limits. A bug can come from new code placed inside old code. +``` + +- [ ] **Step 4: `requesting-code-review/code-reviewer.md`** + +(a) Replace the block + +``` + ## Git Range to Review + + **Base:** [BASE_SHA] + **Head:** [HEAD_SHA] + + ```bash + git diff --stat [BASE_SHA]..[HEAD_SHA] + git diff [BASE_SHA]..[HEAD_SHA] + ``` +``` + +with + +``` + ## Git Range to Review + + **Base:** [BASE_SHA] + **Head:** [HEAD_SHA] + **Diff file:** [DIFF_FILE] + + Read the diff file once: a stat summary, the instruction files that + govern the changed files, and the diff with each hunk's whole enclosing + function (a file marked `# context capped` shows 10 lines instead). If + no diff file was given, fetch the diff yourself: + + ```bash + git diff --stat [BASE_SHA]..[HEAD_SHA] + git diff --function-context [BASE_SHA]..[HEAD_SHA] + ``` + + and read every AGENTS.md / CLAUDE.md from the repo root down to each + changed file's directory. + + ## Binding Instructions + + The rules in those instruction files bind this change like the plan + does. A change that breaks one is an Important finding by default: cite + the rule as path:line next to the code's file:line. +``` + +(b) Under `**Code quality:**`, after ` - Edge cases handled?` add: + +``` + - For each piece of new state, effect, resource or side effect, check the + unchanged code that encloses or calls it: lifecycle and remount + behaviour, reactivity/keying, transaction or request scope, loops and + limits. A bug can come from new code placed inside old code. This is a + named risk by default: one focused read of enclosing code the diff + does not show is expected. +``` + +(c) In the `**Placeholders:**` list after the template, add: + +``` +- `[DIFF_FILE]` — the review package path (`../subagent-driven-development/scripts/review-package BASE_SHA HEAD_SHA` prints it). Omit only when the script cannot run; the template's fallback then applies. +``` + +- [ ] **Step 5: `requesting-code-review/SKILL.md`** + +(a) In `## How to Request`, after the step-1 code block (ends with `HEAD_SHA=$(git rev-parse HEAD)` and the closing fence) insert: + +```` +**2. Build the review package:** +```bash +../subagent-driven-development/scripts/review-package "$BASE_SHA" "$HEAD_SHA" +``` +(Path relative to this skill's directory.) It prints the package path: +the stat summary, the AGENTS.md / CLAUDE.md files that govern the changed +files, and the diff with each hunk's whole enclosing function. It writes +under the self-ignored `/.superpowers/sdd/`. +```` + +(b) Renumber the following steps: `**2. Dispatch code reviewer subagent:**` → `**3. ...**`, `**3. Act on feedback:**` → `**4. ...**`. + +(c) In that section's `**Placeholders:**` list, after the `{HEAD_SHA}` bullet add: + +``` +- `{DIFF_FILE}` - Review package path from step 2 +``` + +(d) In `## Example`, after the line `HEAD_SHA=$(git rev-parse HEAD)` insert a line `DIFF_FILE=$(../subagent-driven-development/scripts/review-package "$BASE_SHA" "$HEAD_SHA" | sed -n 's/^wrote \(.*\): .*/\1/p')`, and under `[Dispatch code reviewer subagent]` after ` HEAD_SHA: 3df7661` add ` DIFF_FILE: .superpowers/sdd/review-a7981ec..3df7661.diff`. + +- [ ] **Step 6: `subagent-driven-development/SKILL.md`** + +(a) Replace + +``` +3. `scripts/review-package "$BASE" "$AFTER"` (add `-- ` when the task is one of a parallel batch) — it prints the unique diff path. +``` + +with + +``` +3. `scripts/review-package "$BASE" "$AFTER"` (add `-- ` when the task is one of a parallel batch) — it prints the unique diff path. The package carries the AGENTS.md / CLAUDE.md files that govern the changed files (read from `$AFTER`) and widens each hunk to its enclosing function; a file whose function context exceeds `SDD_CONTEXT_CAP` lines (default 400) falls back to `-U10` and is marked `# context capped`. +``` + +(b) Replace + +``` + uncommitted) — that is expected. Without bash: `git diff --stat BASE AFTER` + and `git diff -U10 BASE AFTER` redirected to one uniquely named file. +``` + +with + +``` + uncommitted) — that is expected. Without bash: `git diff --stat BASE AFTER` + and `git diff --function-context BASE AFTER` redirected to one uniquely + named file, plus every AGENTS.md / CLAUDE.md from the repo root down to + each changed file's directory appended to it. +``` + +(c) Replace + +``` + `scripts/task-brief PLAN_FILE N` — it extracts the task's full text to a + uniquely named file and prints the path. Every dispatch is the implementer +``` + +with + +``` + `scripts/task-brief PLAN_FILE N` — it extracts the task's full text to a + uniquely named file and prints the path. The brief ends with the + AGENTS.md / CLAUDE.md files that govern the paths in the task's + **Files:** block; they bind the implementer. Every dispatch is the implementer +``` + +- [ ] **Step 7: `AGENTS.md` (fork notes)** + +In the `subagent-driven-development` bullet, after the sentence ending `so controllers stop over-serializing "related" tasks.` add (same indentation, two leading spaces): + +``` + Review packages and task briefs carry the AGENTS.md / CLAUDE.md files on + the path from the repo root to each changed (or brief-listed) file, + gathered by `scripts/instruction-files`; review packages also widen each + hunk to its enclosing function (`git diff --function-context`, capped per + file by `SDD_CONTEXT_CAP`). Reviewer and implementer templates treat those + files as binding and check new code against the unchanged code that + encloses it. `tests/claude-code/test-sdd-review-context.sh` covers the + scripts and runs in CI. +``` + +In the `requesting-code-review / verification-before-completion` bullet, append the sentence: `The code reviewer reads a review package built by the SDD `review-package` script.` + +- [ ] **Step 8: Verify** + +Run: +```bash +grep -c "A bug can come from new code placed inside old code" \ + skills/subagent-driven-development/task-reviewer-prompt.md \ + skills/subagent-driven-development/implementer-prompt.md \ + skills/subagent-driven-development/refactor-reviewer-prompt.md \ + skills/requesting-code-review/code-reviewer.md +grep -rn "Instruction files (binding)" skills | wc -l +grep -rniE "solid|convex|react|vue|svelte|angular" skills/subagent-driven-development/*.md skills/requesting-code-review/*.md || echo "no stack names" +grep -rIoE 'superpowers:[a-z-]+' skills hooks || echo "namespace clean" +``` +Expected: each of the 4 files prints `1`; the instruction-section count is ≥ 4; `no stack names`; `namespace clean`. (If the stack-name grep hits pre-existing upstream text, confirm the hit is not from this task's edits.) + +- [ ] **Step 9: Hand back for review (no commit — the controller commits).** + +--- + +### Task 5: CI step and version bump + +**Files:** +- Modify: `.github/workflows/release-checks.yml` +- Modify (via script): `package.json`, `.claude-plugin/plugin.json`, `.cursor-plugin/plugin.json`, `.codex-plugin/plugin.json`, `.kimi-plugin/plugin.json`, `.claude-plugin/marketplace.json`, `gemini-extension.json` + +**Interfaces:** +- Consumes: `tests/claude-code/test-sdd-review-context.sh` (Task 1 creates it). +- Produces: nothing. + +- [ ] **Step 1: Add the CI step** + +In `.github/workflows/release-checks.yml`, after the `Check versions, manifests, namespace, and line endings` step (end of file), append: + +```yaml + + - name: SDD script tests + run: | + bash tests/claude-code/test-sdd-workspace.sh + bash tests/claude-code/test-sdd-review-context.sh +``` + +(Same indentation as the existing `- name:` step: six spaces before `-`.) + +- [ ] **Step 2: Bump the version** + +Run: `bash scripts/bump-version.sh 6.0.4-fork.11` +Then: `bash scripts/bump-version.sh --check` → no drift reported. + +- [ ] **Step 3: Verify** + +Run: `python3 -c "import yaml,sys; yaml.safe_load(open('.github/workflows/release-checks.yml'))" && echo yaml-ok` (skip if PyYAML is missing; then eyeball the indentation). +Run: `jq -r .version .claude-plugin/plugin.json` → `6.0.4-fork.11`. + +- [ ] **Step 4: Hand back for review (no commit — the controller commits).** diff --git a/docs/superpowers/specs/2026-11-02-review-enclosing-context-design.md b/docs/superpowers/specs/2026-11-02-review-enclosing-context-design.md new file mode 100644 index 0000000..0d4f837 --- /dev/null +++ b/docs/superpowers/specs/2026-11-02-review-enclosing-context-design.md @@ -0,0 +1,175 @@ +# Review and implementer context: nested instructions and enclosing code + +## Problem + +Reviewer and implementer subagents look at hunks, not at the code the hunks +land in. Two real misses on a downstream project, both caught by an external +bot and missed by eight reviewer passes: + +1. A new scheduled mutation read a whole table into memory. The rule against + that lived only in a nested instruction file (`/AGENTS.md`). No + brief or reviewer read it. +2. A task moved component-local state into a child component. The child sat + inside an existing keyed wrapper (an unchanged line) that remounts on every + data refetch, so the state was lost. The diff-scoped reviewer saw the + wrapper only as context and praised it. + +Both bugs come from new code meeting unchanged code. The fix gives +subagents (a) every instruction file that governs the files they touch, +gathered by script, and (b) the enclosing function or component of every +hunk, not just ten lines around it. + +## Constraint: stack-agnostic + +The skills ship to every stack. Templates, scripts, and tests carry no +framework, language, or product names. The two misses above motivate the +change; they do not appear in shipped text. + +## Design + +### 1. `scripts/instruction-files` (new shared helper) + +Location: `skills/subagent-driven-development/scripts/instruction-files`, +sibling of `sdd-workspace`. Bash + git only, `set -euo pipefail`, LF. + +- **Usage:** `instruction-files [--tree TREEISH] PATH...` +- **Collection:** for each path, walk directories from the repo root down to + the path's directory. In each directory, collect `AGENTS.md` and + `CLAUDE.md` if present. A directory that does not exist (a file the task + will create in a new directory) is skipped; the walk continues so ancestor + files still apply. +- **Source:** with `--tree TREEISH`, existence and content come from that + tree (`git cat-file -e` / `git show TREEISH:path`). Without it, from the + working tree. +- **Order:** unique paths, root first, then by depth, then by name. +- **Output** (stdout; nothing at all when no file is found): + + ``` + ## Instruction files (binding) + + These files govern the changed files. Their rules are binding constraints. + Cite a rule as path:line. + + - AGENTS.md + - pkg/sub/AGENTS.md + - pkg/sub/CLAUDE.md + + ### AGENTS.md + 1 + 2 + + ### pkg/sub/AGENTS.md + 1 + + ### pkg/sub/CLAUDE.md — identical to pkg/sub/AGENTS.md + ``` + + Contents carry original line numbers, so a reviewer cites `file:line` + without a separate read. Byte-identical files (same blob SHA in tree mode, + same checksum in working-tree mode) print once; later duplicates print the + "identical to" heading only. +- **Out of scope:** resolving `@file` imports. A one-line `@AGENTS.md` + `CLAUDE.md` is inlined as-is. + +### 2. `scripts/review-package` + +- **Instruction files:** call `instruction-files --tree HEAD` with the + changed paths (honouring `-- PATHSPEC`). Read from the HEAD tree-ish, not + the working tree: in a parallel batch the working tree holds other tasks' + edits, and a task that edits an instruction file is reviewed against the + new text. +- **Section order:** header, `## Files changed`, `## Instruction files + (binding)`, `## Diff`. +- **Enclosing context:** run `git diff --function-context -U10` once and + `git diff -U10` once over the same range and pathspec. Split both on + `^diff --git ` into per-file chunks (rename pairing preserved). Per file, + use the function-context chunk, except when it exceeds the cap **and** the + plain chunk is smaller; then use the plain chunk. A new or fully rewritten + file has equal chunks and is never marked capped. +- **Cap:** default 400 lines per file chunk; env `SDD_CONTEXT_CAP` + overrides. +- **Capped marking:** a line `# context capped: (function context + over N lines; -U10 shown)` directly above that file's `diff --git` line, + and a header line listing every capped file. +- **No language assumptions:** function context comes from git's default + funcname rule (enclosing column-0 declaration) or the repo's own + `.gitattributes` diff drivers. Indented declarations (class methods) can + widen to a whole class; the cap bounds that. + +### 3. `scripts/task-brief` + +After extracting the task, parse its `**Files:**` block: every backticked +token on a list line, with a trailing `:N` or `:N-M` stripped. Append the +`instruction-files` output (working-tree mode) to the brief. No `Files:` +block or no instruction file found: no section, exit 0. + +### 4. Templates (generic wording only) + +`task-reviewer-prompt.md`, `requesting-code-review/code-reviewer.md`, +`refactor-reviewer-prompt.md`: + +- The package's Instruction files section is binding. A violation is + Important by default. Cite the rule as `path:line` next to the code + `file:line`. +- Checklist item, verbatim: "For each piece of new state, effect, resource + or side effect, check the unchanged code that encloses or calls it: + lifecycle and remount behaviour, reactivity/keying, transaction or request + scope, loops and limits. A bug can come from new code placed inside old + code." +- The enclosing-code check is a named risk by default (one sentence added to + the existing "one focused check per named risk" allowance). A file marked + `context capped` is the expected case for that one focused read. + +`implementer-prompt.md`: + +- The brief's instruction files are binding. When a rule shaped a decision + or ruled out an approach, cite it (`path:line`) in the report. +- Self-review adds the same new-code-inside-old-code check. + +`requesting-code-review/SKILL.md`: before dispatch, run +`../subagent-driven-development/scripts/review-package BASE HEAD` and pass +the printed path as `[DIFF_FILE]`. Running it outside SDD creates the +self-ignored `/.superpowers/sdd/`. `code-reviewer.md` keeps the +raw `git diff` commands as fallback when no package is given. + +### 5. Docs + +- `subagent-driven-development/SKILL.md`: describe the package contents + (instruction files, enclosing context, cap) and the brief's instruction + section where review packages and briefs are described. +- `AGENTS.md` (fork notes): add the divergence, present tense. + +### 6. Tests and CI + +New `tests/claude-code/test-sdd-review-context.sh`, modelled on +`test-sdd-workspace.sh` (mktemp, physical-path resolution, +`-c commit.gpgsign=false`). Fixture repo, no `.gitattributes`: + +- root `AGENTS.md`; nested `pkg/sub/AGENTS.md` with a distinctive rule; + sibling `pkg/other/AGENTS.md`; `pkg/sub/CLAUDE.md` byte-identical to + `pkg/sub/AGENTS.md`. +- `pkg/sub/widget.js`: a column-0 function whose changed line sits more than + 10 lines below its opening line and above its closing line, inside an + unchanged wrapping block; a second, long function. + +Assertions: + +- package contains root and nested rule text with line numbers; + sibling text absent; CLAUDE.md shown as identical, not repeated. +- package contains the first function's opening and closing lines. +- with a small `SDD_CONTEXT_CAP`, the long function's file is marked capped + and its far lines are absent. +- `-- pathspec` run collects only scoped files' instruction files. +- an uncommitted edit to `pkg/sub/AGENTS.md`, captured by `snapshot`, + appears in the package. +- `task-brief` with ``Modify: `pkg/sub/widget.js:10-20` `` and a `Create:` + path in a new directory under `pkg/sub/` includes the nested rule text. + +`.github/workflows/release-checks.yml`: a step runs +`test-sdd-workspace.sh` and `test-sdd-review-context.sh` directly (not +`run-skill-tests.sh`, which needs a live `claude`). + +### 7. Release + +Version `6.0.4-fork.11` via `bash scripts/bump-version.sh`; +`bash scripts/check-release.sh origin/main` passes; PR to `main`. diff --git a/gemini-extension.json b/gemini-extension.json index a2323b2..c4dd22c 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "superpowers-custom", "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques", - "version": "6.0.4-fork.10", + "version": "6.0.4-fork.11", "contextFileName": "GEMINI.md" } diff --git a/package.json b/package.json index 1f836b9..844440f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "superpowers", - "version": "6.0.4-fork.10", + "version": "6.0.4-fork.11", "description": "Superpowers skills and runtime bootstrap for coding agents", "type": "module", "main": ".opencode/plugins/superpowers.js", diff --git a/skills/requesting-code-review/SKILL.md b/skills/requesting-code-review/SKILL.md index b1d26ea..4ddf461 100644 --- a/skills/requesting-code-review/SKILL.md +++ b/skills/requesting-code-review/SKILL.md @@ -29,7 +29,17 @@ BASE_SHA=$(git rev-parse HEAD~1) # or origin/main HEAD_SHA=$(git rev-parse HEAD) ``` -**2. Dispatch code reviewer subagent:** +**2. Build the review package:** +```bash +/../subagent-driven-development/scripts/review-package --print-path "$BASE_SHA" "$HEAD_SHA" +``` +`--print-path` prints only the path of the package (without it, the script +prints a `wrote : ...` line); the package is +the stat summary, the AGENTS.md / CLAUDE.md files that govern the changed +files, and the diff with each hunk's whole enclosing function. It writes +under the self-ignored `/.superpowers/sdd/`. + +**3. Dispatch code reviewer subagent:** Dispatch a `general-purpose` subagent, filling the template at [code-reviewer.md](code-reviewer.md) @@ -38,8 +48,9 @@ Dispatch a `general-purpose` subagent, filling the template at [code-reviewer.md - `{PLAN_OR_REQUIREMENTS}` - What it should do - `{BASE_SHA}` - Starting commit - `{HEAD_SHA}` - Ending commit +- `{DIFF_FILE}` - Review package path from step 2 -**3. Act on feedback:** +**4. Act on feedback:** - Fix Critical issues immediately - Fix Important issues before proceeding - Fix Minor issues before the branch is done — they are small, concrete, and cited @@ -54,12 +65,14 @@ You: Let me request code review before proceeding. BASE_SHA=$(git log --oneline | grep "Task 1" | head -1 | awk '{print $1}') HEAD_SHA=$(git rev-parse HEAD) +DIFF_FILE=$(/../subagent-driven-development/scripts/review-package --print-path "$BASE_SHA" "$HEAD_SHA") [Dispatch code reviewer subagent] DESCRIPTION: Added verifyIndex() and repairIndex() with 4 issue types PLAN_OR_REQUIREMENTS: Task 2 from docs/superpowers/plans/deployment-plan.md BASE_SHA: a7981ec HEAD_SHA: 3df7661 + DIFF_FILE: .superpowers/sdd/review-a7981ec..3df7661.diff [Subagent returns]: Strengths: Clean architecture, real tests diff --git a/skills/requesting-code-review/code-reviewer.md b/skills/requesting-code-review/code-reviewer.md index db84ae2..e266ab3 100644 --- a/skills/requesting-code-review/code-reviewer.md +++ b/skills/requesting-code-review/code-reviewer.md @@ -24,12 +24,27 @@ Subagent (general-purpose): **Base:** [BASE_SHA] **Head:** [HEAD_SHA] + **Diff file:** [DIFF_FILE] + + Read the diff file once: a stat summary, the instruction files that + govern the changed files, and the diff with each hunk's whole enclosing + function (a file marked `# context capped` shows 10 lines instead). If + no diff file was given, fetch the diff yourself: ```bash - git diff --stat [BASE_SHA]..[HEAD_SHA] - git diff [BASE_SHA]..[HEAD_SHA] + git diff --no-color --no-ext-diff --stat [BASE_SHA]..[HEAD_SHA] + git diff --no-color --no-ext-diff --function-context [BASE_SHA]..[HEAD_SHA] ``` + and read every AGENTS.md / CLAUDE.md from the repo root down to each + changed file's directory. + + ## Binding Instructions + + The rules in those instruction files bind this change like the plan + does. A change that breaks one is an Important finding by default: cite + the rule as path:line next to the code's file:line. + ## Read-Only Review 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. @@ -47,6 +62,12 @@ Subagent (general-purpose): - Type safety where applicable? - DRY without premature abstraction? - Edge cases handled? + - For each piece of new state, effect, resource or side effect, check the + unchanged code that encloses or calls it: lifecycle and remount + behaviour, reactivity/keying, transaction or request scope, loops and + limits. A bug can come from new code placed inside old code. This is a + named risk by default: one focused read of enclosing code the diff + does not show is expected. **Architecture:** - Sound design decisions? @@ -130,6 +151,7 @@ Subagent (general-purpose): - `[PLAN_OR_REQUIREMENTS]` — what it should do (plan file path, task text, or requirements) - `[BASE_SHA]` — starting commit - `[HEAD_SHA]` — ending commit +- `[DIFF_FILE]` — the review package path (`../subagent-driven-development/scripts/review-package BASE_SHA HEAD_SHA` prints it). Omit only when the script cannot run; the template's fallback then applies. **Reviewer returns:** Strengths, Issues (Critical / Important / Minor), Recommendations, Assessment diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index ed5bcf3..7ff850b 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -275,7 +275,7 @@ Implementer subagents report one of four statuses. Handle each appropriately: **DONE:** The implementer left its work uncommitted in the working tree. Capture it and review it: 1. `AFTER=$(scripts/snapshot)` — tree SHA of the working tree now. 2. `BASE` is the tree before this task: `HEAD^{tree}` for a sequential task, or the snapshot you recorded before dispatching a parallel batch. -3. `scripts/review-package "$BASE" "$AFTER"` (add `-- ` when the task is one of a parallel batch) — it prints the unique diff path. +3. `scripts/review-package "$BASE" "$AFTER"` (add `-- ` when the task is one of a parallel batch) — it prints the unique diff path (`--print-path` makes the path the only output). The package carries the AGENTS.md / CLAUDE.md files that govern the changed files (read from `$AFTER`) and widens each hunk to its enclosing function; a file whose function context exceeds `SDD_CONTEXT_CAP` lines (default 400) falls back to `-U10` and is marked `# context capped`. 4. Dispatch the task reviewer with the printed path. Do NOT commit yet — you commit only after the review passes (see [Committing](#committing)). **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. @@ -324,8 +324,11 @@ final whole-branch review. When you fill a reviewer template: - Hand the reviewer its diff as a file — the `scripts/review-package` path from [Handling Implementer Status](#handling-implementer-status), never pasted into your own context. The package has no commit list (the work is - uncommitted) — that is expected. Without bash: `git diff --stat BASE AFTER` - and `git diff -U10 BASE AFTER` redirected to one uniquely named file. + uncommitted) — that is expected. Without bash: + `git diff --no-color --no-ext-diff --stat BASE AFTER` and + `git diff --no-color --no-ext-diff --function-context BASE AFTER` + redirected to one uniquely named file, plus every AGENTS.md / CLAUDE.md + from the repo root down to each changed file's directory appended to it. - 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% @@ -499,7 +502,10 @@ and is re-read on every later turn. Hand artifacts over as files: - **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. Every dispatch is the implementer + uniquely named file and prints the path (`--print-path` makes the path + the only output). The brief ends with the + AGENTS.md / CLAUDE.md files that govern the paths in the task's + **Files:** block; they bind the implementer. Every dispatch is the implementer contract (above — non-negotiable) plus task framing, with the brief as the single source of requirements. The framing, on top of the contract: (1) one line on where this task fits in the project; (2) the brief path, diff --git a/skills/subagent-driven-development/implementer-prompt.md b/skills/subagent-driven-development/implementer-prompt.md index 9248a0a..a01ad12 100644 --- a/skills/subagent-driven-development/implementer-prompt.md +++ b/skills/subagent-driven-development/implementer-prompt.md @@ -18,7 +18,11 @@ Subagent (general-purpose): ## Task Description Read your task brief first: [BRIEF_FILE] - It contains the full task text from the plan. + It contains the full task text from the plan. Its "Instruction files + (binding)" section, when present, holds the AGENTS.md / CLAUDE.md rules + that govern your files. Follow them like the task text. When a rule + shaped a decision or ruled out an approach, cite it (path:line) in your + report. ## Context @@ -120,6 +124,10 @@ Subagent (general-purpose): - Is this my best work? - Are names clear and accurate (match what things do, not how they work)? - Is the code clean and maintainable? + - For each piece of new state, effect, resource or side effect, did I + check the unchanged code that encloses or calls it: lifecycle and + remount behaviour, reactivity/keying, transaction or request scope, + loops and limits? A bug can come from new code placed inside old code. **Discipline:** - Did I avoid overbuilding (YAGNI)? diff --git a/skills/subagent-driven-development/refactor-reviewer-prompt.md b/skills/subagent-driven-development/refactor-reviewer-prompt.md index 39b11dc..44b13b7 100644 --- a/skills/subagent-driven-development/refactor-reviewer-prompt.md +++ b/skills/subagent-driven-development/refactor-reviewer-prompt.md @@ -91,7 +91,16 @@ Subagent (general-purpose): Read the diff file once — it is a stat summary plus the full branch diff with context, and it is the set of changes you are judging. If it is missing, regenerate it yourself: - `git diff --stat [BASE_SHA]..[HEAD_SHA]` and `git diff [BASE_SHA]..[HEAD_SHA]`. + `git diff --no-color --no-ext-diff --stat [BASE_SHA]..[HEAD_SHA]` and + `git diff --no-color --no-ext-diff --function-context [BASE_SHA]..[HEAD_SHA]`, + and read every AGENTS.md / CLAUDE.md from the repo root down to each + changed file's directory. + + The diff file's "Instruction files (binding)" section holds every + AGENTS.md / CLAUDE.md that governs the changed files, with line numbers. + Those rules are binding: do not propose a refactor that breaks one. A rule + the branch already breaks is the correctness reviewer's finding; do not + file it as Refactor-Critical. ## You MAY read the whole codebase — that is the point @@ -132,6 +141,10 @@ Subagent (general-purpose): - Primitive obsession — bare strings/ints/maps where a small type would remove a class of mistakes - Naming drift — the same concept named differently across tasks + - For each piece of new state, effect, resource or side effect, check the + unchanged code that encloses or calls it: lifecycle and remount + behaviour, reactivity/keying, transaction or request scope, loops and + limits. A bug can come from new code placed inside old code. - Structure that works now but will force a painful change on the next feature that touches it diff --git a/skills/subagent-driven-development/scripts/instruction-files b/skills/subagent-driven-development/scripts/instruction-files new file mode 100755 index 0000000..5fc831f --- /dev/null +++ b/skills/subagent-driven-development/scripts/instruction-files @@ -0,0 +1,213 @@ +#!/usr/bin/env bash +# Print the instruction files (AGENTS.md, CLAUDE.md) that govern a set of +# paths, as one markdown section a reviewer or implementer reads with the +# change. A file governs a path when it sits in the repo root or in any +# directory on the way down to that path's directory. +# +# A nested instruction file holds rules no brief repeats, and a harness loads +# it only when an agent happens to read a file in that directory. Gathering +# the files by script, not by memory, puts every governing rule in front of +# the subagent. +# +# Usage: instruction-files [--tree TREEISH] [--] PATH... +# PATH repo-root-relative path. It need not exist: a file a task +# will create still gets the files of its existing ancestors. +# -- end of options, so a PATH may start with "-". +# --tree TREEISH read the instruction files from this tree (a commit, or a +# `snapshot` tree SHA) instead of the working tree. +# +# Output: nothing when no instruction file governs any PATH. Otherwise a +# "## Instruction files (binding)" section: the file paths (root first, then +# by depth), then each file's content with line numbers, so a finding can +# cite path:line. A file byte-identical to one already printed gets a heading +# that names the first file instead of its content. `@file` imports are not +# resolved. +set -euo pipefail + +usage() { + echo "usage: instruction-files [--tree TREEISH] [--] PATH..." >&2 + exit 2 +} + +tree="" +case "${1:-}" in + --tree) + [ $# -ge 2 ] || usage + tree=$2 + shift 2 + ;; +esac +case "${1:-}" in + --) shift ;; + -*) usage ;; +esac + +root=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "not inside a git repository" >&2; exit 2; } +if [ -n "$tree" ]; then + git rev-parse --verify --quiet "${tree}^{tree}" >/dev/null || { echo "bad TREEISH: $tree" >&2; exit 2; } +fi +cd "$root" + +# Instruction file names, checked in every directory. +names="AGENTS.md CLAUDE.md" + +# Most symlink hops either resolver follows before giving up. +max_hops=10 + +# in_repo PATH — true when PATH, with symlinks resolved, stays inside the repo +# root (a working-tree read must not follow a link out of the repository). +in_repo() { + local p=$1 hops=0 t d + while [ -L "$p" ]; do + [ "$hops" -lt "$max_hops" ] || return 1 + hops=$((hops + 1)) + t=$(readlink -- "$p") + case $t in /*) p=$t ;; *) p=$(dirname -- "$p")/$t ;; esac + done + d=$(cd -P -- "$(dirname -- "$p")" 2>/dev/null && pwd -P) || return 1 + case $d/ in "$root"/*) return 0 ;; esac + return 1 +} + +# is_file PATH — true when PATH is a regular file in the source. +is_file() { + if [ -n "$tree" ]; then + [ "$(git cat-file -t "${tree}:$1" 2>/dev/null)" = blob ] + else + [ -f "$1" ] + fi +} + +# join_path DIR TARGET — DIR/TARGET with ./ and ../ folded away. Fails when +# TARGET is absolute or climbs above the repo root. +join_path() { + local parts part out + out=() + case $2 in /*) return 1 ;; esac + IFS=/ read -r -a parts <<< "$1/$2" + for part in "${parts[@]}"; do + case $part in + ''|.) ;; + ..) + [ ${#out[@]} -gt 0 ] || return 1 + unset "out[$((${#out[@]} - 1))]" + ;; + *) out+=("$part") ;; + esac + done + [ ${#out[@]} -gt 0 ] || return 1 + (IFS=/; printf '%s\n' "${out[*]}") +} + +# tree_blob PATH — blob SHA of PATH in the tree, following symlink entries +# (mode 120000) to the blob they name, as a working-tree read would. Fails +# when PATH is not in the tree or the link does not resolve to a blob. +tree_blob() { + local p=$1 hops=0 mode type sha target + while [ "$hops" -lt "$max_hops" ]; do + read -r mode type sha _ < <(git ls-tree "$tree" -- "$p") || return 1 + [ -n "${sha:-}" ] || return 1 + if [ "$mode" = 120000 ]; then + target=$(git cat-file blob "$sha") + p=$(join_path "$(dirname -- "$p")" "$target") || return 1 + hops=$((hops + 1)) + elif [ "$type" = blob ]; then + printf '%s\n' "$sha" + return 0 + else + return 1 + fi + done + return 1 +} + +# show PATH — print PATH's content from the source. +show() { + if [ -n "$tree" ]; then + git cat-file blob "$(tree_blob "$1")" + else + cat -- "$1" + fi +} + +# blob_id PATH — git blob SHA of PATH's content; equal SHAs mean equal bytes. +blob_id() { + if [ -n "$tree" ]; then + tree_blob "$1" + else + git hash-object -- "$1" + fi +} + +# candidates PATH... — AGENTS.md and CLAUDE.md in the root and in every +# directory on the way down to each PATH's directory, one per line. +candidates() { + local p d acc part name + local parts + for p in "$@"; do + p=${p#./} + for name in $names; do printf '%s\n' "$name"; done + d=$(dirname -- "$p") + [ "$d" = . ] && continue + acc="" + IFS=/ read -r -a parts <<< "$d" + for part in "${parts[@]}"; do + acc=${acc:+$acc/}$part + for name in $names; do printf '%s\n' "$acc/$name"; done + done + done +} + +tab=$(printf '\t') +found=() +while IFS= read -r f; do + if is_file "$f"; then + found+=("$f") + fi +done < <(candidates "$@" | awk -F/ '{ print NF "\t" $0 }' | LC_ALL=C sort -t "$tab" -k1,1n -k2 -u | cut -f2-) + +if [ ${#found[@]} -eq 0 ]; then + exit 0 +fi + +echo "## Instruction files (binding)" +echo +echo "These files govern the files in scope. Their rules are binding constraints." +echo "Cite a rule as path:line." +echo +for f in "${found[@]}"; do + echo "- $f" +done + +seen_ids=() +seen_paths=() +for f in "${found[@]}"; do + if [ -z "$tree" ] && ! in_repo "$f"; then + echo + echo "### $f — symlink outside the repository (not read)" + continue + fi + if ! id=$(blob_id "$f"); then + echo + echo "### $f — symlink to $(git cat-file blob "${tree}:$f")" + continue + fi + dup="" + i=0 + while [ "$i" -lt "${#seen_ids[@]}" ]; do + if [ "${seen_ids[$i]}" = "$id" ]; then + dup=${seen_paths[$i]} + break + fi + i=$((i + 1)) + done + echo + if [ -n "$dup" ]; then + echo "### $f — identical to $dup" + else + echo "### $f" + show "$f" | awk '{ printf "%6d %s\n", NR, $0 }' + seen_ids+=("$id") + seen_paths+=("$f") + fi +done diff --git a/skills/subagent-driven-development/scripts/review-package b/skills/subagent-driven-development/scripts/review-package index 8904d99..f21a6ef 100755 --- a/skills/subagent-driven-development/scripts/review-package +++ b/skills/subagent-driven-development/scripts/review-package @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# Generate a review package: a stat summary and the net diff with extended -# context, written to a file the reviewer reads in one call. +# Generate a review package: a stat summary, the instruction files that +# govern the changed files, and the net diff with each hunk widened to its +# enclosing function, written to a file the reviewer reads in one call. # # This fork runs the no-commit model: implementer subagents leave their work # in the working tree and the controller commits after review. BASE and HEAD @@ -9,7 +10,21 @@ # either. There is no commit list to show because the task is not yet # committed. # -# Usage: review-package BASE HEAD [-- PATHSPEC...] +# Instruction files: every AGENTS.md / CLAUDE.md from the repo root down to +# each changed file's directory, read from HEAD (the tree under review, not +# the working tree, which in a parallel batch holds other tasks' edits), via +# the sibling `instruction-files` helper. +# +# Context: each file's diff uses `git diff --function-context`, so a hunk +# shows its whole enclosing function as git's funcname rule (or the repo's +# .gitattributes diff driver) finds it. When a file's function-context diff +# is over the cap and its -U10 diff is smaller, the package shows the -U10 +# diff for that file, marked with a "# context capped:" line. +# Cap: SDD_CONTEXT_CAP lines per file (default 400). +# +# Usage: review-package [--print-path] BASE HEAD [-- PATHSPEC...] +# --print-path print only the package's absolute path (one line) instead of +# the human `wrote : ...` summary line. # BASE tree-ish before the task (e.g. HEAD^{tree}, or a snapshot SHA) # HEAD tree-ish after the task (e.g. `scripts/snapshot` output) # -- PATHSPEC limit the diff to these paths — use for one task inside a @@ -23,8 +38,14 @@ # always gets a distinctly named file. set -euo pipefail +print_path=0 +if [ "${1:-}" = "--print-path" ]; then + print_path=1 + shift +fi + if [ $# -lt 2 ]; then - echo "usage: review-package BASE HEAD [-- PATHSPEC...]" >&2 + echo "usage: review-package [--print-path] BASE HEAD [-- PATHSPEC...]" >&2 exit 2 fi @@ -38,15 +59,21 @@ if [ $# -gt 0 ]; then shift paths=("$@") else - echo "usage: review-package BASE HEAD [-- PATHSPEC...]" >&2 + echo "usage: review-package [--print-path] BASE HEAD [-- PATHSPEC...]" >&2 exit 2 fi fi +cap=${SDD_CONTEXT_CAP:-400} +case $cap in + ''|*[!0-9]*|0) echo "SDD_CONTEXT_CAP must be a positive integer: $cap" >&2; exit 2 ;; +esac + git rev-parse --verify --quiet "$base^{tree}" >/dev/null 2>&1 || git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; } git rev-parse --verify --quiet "$head^{tree}" >/dev/null 2>&1 || git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; } -dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace") +scripts=$(cd "$(dirname "$0")" && pwd) +dir=$("$scripts/sdd-workspace") name="review-$(git rev-parse --short "$base")..$(git rev-parse --short "$head")" if [ ${#paths[@]} -gt 0 ]; then # Keep the file unique when several per-task reviews share one BASE..HEAD @@ -56,19 +83,105 @@ if [ ${#paths[@]} -gt 0 ]; then fi out="$dir/${name}.diff" +tmp=$(mktemp -d "$dir/review-package.XXXXXX") +trap 'rm -rf "$tmp"' EXIT + +# Every diff call pins the output format: no colour, no external diff driver, +# and a/ b/ prefixes, so a user's git config cannot change what is parsed. +range=("$base" "$head") +if [ ${#paths[@]} -gt 0 ]; then + range+=(-- "${paths[@]}") +fi +gitdiff=(git -c diff.relative=false diff --no-color --no-ext-diff --submodule=short) +ctx=10 + +# Changed paths (NUL-safe, for the instruction-files argv) and the display +# names, one per diff chunk in the order git lists the chunks. A typechange +# (file <-> symlink) is two chunks under one path, so its name is listed +# twice; a rename or copy lists its new path. A path holding a newline is +# shown with it escaped as \n, because awk reads the names one per line (and +# mawk cannot split on NUL). +changed=() +nl=$'\n' +esc='\n' +: > "$tmp/names" +while IFS= read -r -d '' status; do + IFS= read -r -d '' f + case $status in R*|C*) IFS= read -r -d '' f ;; esac + changed+=("$f") + shown=${f//$nl/$esc} + printf '%s\n' "$shown" >> "$tmp/names" + case $status in T*) printf '%s\n' "$shown" >> "$tmp/names" ;; esac +done < <("${gitdiff[@]}" --name-status -z "${range[@]}") + +"$scripts/instruction-files" --tree "$head" -- ${changed[@]+"${changed[@]}"} > "$tmp/instr" + +diffargs=(--src-prefix=a/ --dst-prefix=b/) +"${gitdiff[@]}" "${diffargs[@]}" --function-context -U"$ctx" "${range[@]}" > "$tmp/wide" +"${gitdiff[@]}" "${diffargs[@]}" -U"$ctx" "${range[@]}" > "$tmp/plain" + +# Both diffs cover the same range and pathspec, so they list the same files +# in the same order, and so does the name list. Pair them file by file and +# keep the function-context chunk unless it is over the cap and the plain +# chunk is smaller (a new or fully rewritten file has equal chunks and keeps +# its full text). Each chunk streams to its own file so a large file costs +# time linear in its size; awk keeps only line counts. +: > "$tmp/capped" +awk -v cap="$cap" -v ctx="$ctx" -v capped="$tmp/capped" -v names="$tmp/names" \ + -v wide="$tmp/wide" -v dir="$tmp" ' + BEGIN { while ((getline line < names) > 0) name[++nn] = line } + FNR == 1 { if (cur != "") close(cur); cur = ""; src = (FILENAME == wide) ? 1 : 2 } + /^diff --git / { + if (cur != "") close(cur) + n[src]++ + cur = dir "/chunk." src "." n[src] + } + cur != "" { print > cur; len[src, n[src]]++ } + END { + if (cur != "") close(cur) + for (i = 1; i <= n[1]; i++) { + pick = 1 + if (len[1, i] > cap && len[2, i] < len[1, i]) { + pick = 2 + printf "# context capped: %s (function context over %d lines; -U%d shown)\n", name[i], cap, ctx + print name[i] > capped + } + f = dir "/chunk." pick "." i + while ((getline line < f) > 0) print line + close(f) + } + } +' "$tmp/wide" "$tmp/plain" > "$tmp/diff" + +if [ -s "$tmp/wide" ] && [ ! -s "$tmp/diff" ]; then + echo "review-package: the diff is non-empty but no file chunk could be read from it" >&2 + exit 1 +fi + { echo "# Review package: ${base}..${head}" if [ ${#paths[@]} -gt 0 ]; then echo "# Scoped to: ${paths[*]}" fi echo "# (no-commit model: changes are uncommitted in the working tree)" + echo "# Context: each hunk shows its whole enclosing function (cap: ${cap} lines per file)" + if [ -s "$tmp/capped" ]; then + echo "# Context capped (-U${ctx} shown): $(paste -sd' ' "$tmp/capped")" + fi echo echo "## Files changed" - git diff --stat "$base" "$head" ${paths[@]:+-- "${paths[@]}"} + "${gitdiff[@]}" --stat "${range[@]}" echo + if [ -s "$tmp/instr" ]; then + cat "$tmp/instr" + echo + fi echo "## Diff" - git diff -U10 "$base" "$head" ${paths[@]:+-- "${paths[@]}"} + cat "$tmp/diff" } > "$out" -files=$(git diff --name-only "$base" "$head" ${paths[@]:+-- "${paths[@]}"} | wc -l | tr -d ' ') -echo "wrote ${out}: ${files} file(s) changed, $(wc -c < "$out" | tr -d ' ') bytes" +if [ "$print_path" = 1 ]; then + printf '%s\n' "$out" +else + echo "wrote ${out}: ${#changed[@]} file(s) changed, $(wc -c < "$out" | tr -d ' ') bytes" +fi diff --git a/skills/subagent-driven-development/scripts/sdd-workspace b/skills/subagent-driven-development/scripts/sdd-workspace old mode 100644 new mode 100755 diff --git a/skills/subagent-driven-development/scripts/snapshot b/skills/subagent-driven-development/scripts/snapshot index 640baa8..91fcd85 100755 --- a/skills/subagent-driven-development/scripts/snapshot +++ b/skills/subagent-driven-development/scripts/snapshot @@ -28,8 +28,18 @@ dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace") tmpidx="$dir/snapshot.$$.index" trap 'rm -f "$tmpidx"' EXIT +# Seed the temp index from the real one so entry modes survive: under +# core.fileMode=false a fresh index would record every file as 100644. +# Seeding also carries assume-unchanged / skip-worktree flags, so edits to +# such files are not captured, the same as what the controller's `git add` +# would commit. +realidx=$(git rev-parse --git-path index) +if [ -f "$realidx" ]; then + cp -- "$realidx" "$tmpidx" +fi + # Stage the entire working tree (respecting .gitignore) into the temp index, # then hash it into a tree object. -A captures additions, modifications, and -# deletions relative to an empty index = a faithful image of the working tree. +# deletions relative to the seeded index = a faithful image of the working tree. GIT_INDEX_FILE="$tmpidx" git add -A GIT_INDEX_FILE="$tmpidx" git write-tree diff --git a/skills/subagent-driven-development/scripts/task-brief b/skills/subagent-driven-development/scripts/task-brief index 247a767..e2a7b63 100755 --- a/skills/subagent-driven-development/scripts/task-brief +++ b/skills/subagent-driven-development/scripts/task-brief @@ -3,13 +3,29 @@ # 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] +# The brief ends with the instruction files (AGENTS.md / CLAUDE.md) that +# govern the task's files: every backticked path on a list line of the +# task's **Files:** block (a trailing :N or :N-M line range is stripped), +# resolved by the sibling `instruction-files` helper against the working +# tree. An indented line after an item continues it. The block ends at the +# first blank line after a list item, and a **Files:** inside a code fence is +# ignored. No Files block, no governing file, or no git repo: no section. +# +# Usage: task-brief [--print-path] PLAN_FILE TASK_NUMBER [OUTFILE] +# --print-path print only the brief's absolute path (one line) instead of +# the human `wrote : N lines` summary line. # Default OUTFILE: /.superpowers/sdd/task--brief.md # (per worktree; concurrent runs in the same working tree share it). set -euo pipefail +print_path=0 +if [ "${1:-}" = "--print-path" ]; then + print_path=1 + shift +fi + if [ $# -lt 2 ] || [ $# -gt 3 ]; then - echo "usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE]" >&2 + echo "usage: task-brief [--print-path] PLAN_FILE TASK_NUMBER [OUTFILE]" >&2 exit 2 fi @@ -17,15 +33,20 @@ plan=$1 n=$2 [ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; } +scripts=$(cd "$(dirname "$0")" && pwd) + if [ $# -eq 3 ]; then out=$3 else - dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace") + dir=$("$scripts/sdd-workspace") out="$dir/task-${n}-brief.md" fi +if [ "$print_path" = 1 ]; then + case $out in /*) ;; *) out="$PWD/$out" ;; esac +fi awk -v n="$n" ' - /^```/ { infence = !infence } + /^[ \t]*```/ { infence = !infence } !infence && /^#+[ \t]+Task[ \t]+[0-9]+/ { intask = ($0 ~ ("^#+[ \t]+Task[ \t]+" n "([^0-9]|$)")) } @@ -37,4 +58,38 @@ if [ ! -s "$out" ]; then exit 3 fi -echo "wrote ${out}: $(wc -l < "$out" | tr -d ' ') lines" +files=() +while IFS= read -r f; do + files+=("$f") +done < <(awk ' + # Print each backticked token of LINE, minus a trailing :N or :N-M range. + function emit(line, tok) { + while (match(line, /`[^`]+`/)) { + tok = substr(line, RSTART + 1, RLENGTH - 2) + sub(/:[0-9]+(-[0-9]+)?$/, "", tok) + print tok + line = substr(line, RSTART + RLENGTH) + } + } + /^[ \t]*```/ { infence = !infence; inblock = 0; next } + infence { next } + /^\*\*Files:\*\*/ { inblock = 1; seen = 0; next } + inblock && /^[ \t]*[-*][ \t]/ { seen = 1; emit($0); next } + # An indented line after an item continues that (wrapped) item. + inblock && seen && /^[ \t]+[^ \t]/ { emit($0); next } + inblock && /^[ \t]*$/ { if (seen) inblock = 0; next } + { inblock = 0 } +' "$out") + +if [ ${#files[@]} -gt 0 ] && git rev-parse --show-toplevel >/dev/null 2>&1; then + section=$("$scripts/instruction-files" -- "${files[@]}") + if [ -n "$section" ]; then + printf '\n%s\n' "$section" >> "$out" + fi +fi + +if [ "$print_path" = 1 ]; then + printf '%s\n' "$out" +else + echo "wrote ${out}: $(wc -l < "$out" | tr -d ' ') lines" +fi diff --git a/skills/subagent-driven-development/task-reviewer-prompt.md b/skills/subagent-driven-development/task-reviewer-prompt.md index deb9127..0a41962 100644 --- a/skills/subagent-driven-development/task-reviewer-prompt.md +++ b/skills/subagent-driven-development/task-reviewer-prompt.md @@ -38,21 +38,37 @@ Subagent (general-purpose): Read the diff file once — it contains a stat summary and the full diff with surrounding context, and it is your view of the change. The work is uncommitted (the controller commits after this review), so there is no - commit list. The diff's context lines ARE the changed files: do not Read a - changed file separately unless a hunk you must judge is cut off - mid-function — and say so in your report. Do not re-run git commands. + commit list. Each hunk shows its whole enclosing function; a file marked + `# context capped` shows 10 lines of context instead. Do not Read a + changed file separately unless a hunk you must judge is cut off — and + say so in your report. Do not re-run git commands. If the diff file is missing, fetch the diff yourself: - `git diff --stat [BASE_SHA] [HEAD_SHA]` and `git diff [BASE_SHA] [HEAD_SHA]`. + `git diff --no-color --no-ext-diff --stat [BASE_SHA] [HEAD_SHA]` and + `git diff --no-color --no-ext-diff --function-context [BASE_SHA] [HEAD_SHA]`, + and read every AGENTS.md / CLAUDE.md from the repo root down to each + changed file's directory. Do not crawl the broader codebase. Inspect code outside the diff only to evaluate a concrete risk you can name — one focused check per named risk, and name both the risk and what you checked in your report. Cross-cutting changes are legitimate named risks: if the diff changes lock ordering, a function or API contract, or shared mutable state, checking the call sites is the right method. + New code inside unchanged code is a named risk by default: when new + state, an effect, a resource, or a side effect sits inside or is called + from code the diff does not show (a capped file, a caller), one focused + read of that code is expected. Your review is read-only on this checkout. Do not mutate the working tree, the index, HEAD, or branch state in any way. + ## Binding Instructions + + The diff file's "Instruction files (binding)" section holds every + AGENTS.md / CLAUDE.md that governs the changed files, with line numbers. + Their rules bind this task like the spec does. A change that breaks one + is an Important finding by default: cite the rule as path:line next to + the code's file:line. + ## Do Not Trust the Report Treat the implementer's report as unverified claims about the code. It @@ -105,6 +121,10 @@ Subagent (general-purpose): - Proper error handling? - DRY without premature abstraction? - Edge cases handled? + - For each piece of new state, effect, resource or side effect, check the + unchanged code that encloses or calls it: lifecycle and remount + behaviour, reactivity/keying, transaction or request scope, loops and + limits. A bug can come from new code placed inside old code. **Tests:** - Do the new and changed tests verify real behavior, not mocks? @@ -188,7 +208,8 @@ Subagent (general-purpose): - `[HEAD_SHA]` — tree-ish after this task (`scripts/snapshot` output) - `[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) + wrote; the package never enters the controller's context). It carries the + governing instruction files and each hunk's enclosing function. **Reviewer returns:** Spec Compliance verdict (✅/❌/⚠️), Strengths, Issues (Critical/Important/Minor), Task quality verdict diff --git a/tests/claude-code/test-sdd-review-context.sh b/tests/claude-code/test-sdd-review-context.sh new file mode 100755 index 0000000..e57911b --- /dev/null +++ b/tests/claude-code/test-sdd-review-context.sh @@ -0,0 +1,569 @@ +#!/usr/bin/env bash +# Tests for SDD review context: scripts/instruction-files collects the +# AGENTS.md / CLAUDE.md files that govern a set of paths, review-package +# inlines them and widens each hunk to its enclosing function, and +# task-brief appends them to a task brief. +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="" +REPO="" +GIT_ID=(-c user.email=t@example.com -c user.name=t -c commit.gpgsign=false) + +pass() { echo " [PASS] $1"; } +fail() { + echo " [FAIL] $1" + FAILURES=$((FAILURES + 1)) +} + +# assert_contains FILE NEEDLE DESCRIPTION — NEEDLE appears anywhere in FILE. +assert_contains() { + if grep -qF -- "$2" "$1"; then pass "$3"; else fail "$3"; echo " missing: $2"; fi +} + +# assert_exit EXPECTED DESCRIPTION CMD... — CMD, run silently, exits EXPECTED. +assert_exit() { + local want=$1 desc=$2 rc=0 + shift 2 + "$@" >/dev/null 2>&1 || rc=$? + if [[ "$rc" == "$want" ]]; then pass "$desc"; else fail "$desc"; echo " got exit: $rc (want $want)"; fi +} + +# assert_not_contains FILE NEEDLE DESCRIPTION +assert_not_contains() { + if grep -qF -- "$2" "$1"; then fail "$3"; echo " unexpected: $2"; else pass "$3"; fi +} + +# assert_has_line FILE LINE DESCRIPTION — LINE is a whole line of FILE. +assert_has_line() { + if grep -qxF -- "$2" "$1"; then pass "$3"; else fail "$3"; echo " missing line: $2"; fi +} + +cleanup() { + if [[ -n "$TEST_ROOT" && -d "$TEST_ROOT" ]]; then + rm -rf "$TEST_ROOT" + fi +} + +# filler N PREFIX — print N indented, unique filler lines. +filler() { + local i + for ((i = 1; i <= $1; i++)); do + printf ' const %s%d = %d;\n' "$2" "$i" "$i" + done +} + +# new_repo NAME — an empty repo under TEST_ROOT; prints its physical path. +new_repo() { + git init -q -b main "$TEST_ROOT/$1" + ( cd "$TEST_ROOT/$1" && git rev-parse --show-toplevel ) +} + +# commit_all REPO MESSAGE +commit_all() { + ( cd "$1" && git add -A && git "${GIT_ID[@]}" commit -qm "$2" ) +} + +# make_fixture — a repo with instruction files at several depths and two +# source files. No .gitattributes: function context comes from git's +# default funcname rule. +make_fixture() { + REPO="$(new_repo repo)" + mkdir -p "$REPO/pkg/sub/deep" "$REPO/pkg/other" + printf '# Root rules\nROOT_RULE: keep functions small.\n' > "$REPO/AGENTS.md" + printf '# Sub rules\nNESTED_RULE: never read a whole collection in one call.\n' > "$REPO/pkg/sub/AGENTS.md" + cp "$REPO/pkg/sub/AGENTS.md" "$REPO/pkg/sub/CLAUDE.md" + printf 'DEEP_RULE: deep only.\n' > "$REPO/pkg/sub/deep/AGENTS.md" + printf 'SIBLING_RULE: other only.\n' > "$REPO/pkg/other/AGENTS.md" + printf 'readme\n' > "$REPO/README.md" + printf 'export const other = 1;\n' > "$REPO/pkg/other/thing.js" + { + echo 'function renderPanel(items) {' + filler 12 before + echo ' wrapWithKey(items, () => {' + echo ' let count = 0;' + echo ' });' + filler 12 after + echo '} // end renderPanel' + echo '' + echo 'function trailing() {' + echo ' return 1;' + echo '}' + } > "$REPO/pkg/sub/widget.js" + { + echo 'function longTail() {' + echo ' let seed = 0;' + filler 60 tail + echo ' const farMarker = 1;' + echo '} // end longTail' + } > "$REPO/pkg/sub/long.js" + commit_all "$REPO" c1 +} + +test_instruction_files() { + echo "--- instruction-files ---" + local out="$TEST_ROOT/if-widget.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" pkg/sub/widget.js ) > "$out" + assert_has_line "$out" "## Instruction files (binding)" "section heading printed" + assert_has_line "$out" "- AGENTS.md" "root file listed" + assert_has_line "$out" "- pkg/sub/AGENTS.md" "nested file listed" + assert_has_line "$out" " 2 ROOT_RULE: keep functions small." "root content with line numbers" + assert_has_line "$out" " 2 NESTED_RULE: never read a whole collection in one call." "nested content with line numbers" + assert_has_line "$out" "### pkg/sub/CLAUDE.md — identical to pkg/sub/AGENTS.md" "identical CLAUDE.md deduped" + if [[ "$(grep -cF NESTED_RULE "$out")" -eq 1 ]]; then + pass "duplicate content printed once" + else + fail "duplicate content printed once" + fi + assert_not_contains "$out" "SIBLING_RULE" "sibling directory excluded" + assert_not_contains "$out" "DEEP_RULE" "child directory excluded" + local root_line nested_line + root_line="$(grep -nxF -- "- AGENTS.md" "$out" | cut -d: -f1)" + nested_line="$(grep -nxF -- "- pkg/sub/AGENTS.md" "$out" | cut -d: -f1)" + if [[ -n "$root_line" && -n "$nested_line" && "$root_line" -lt "$nested_line" ]]; then + pass "root listed before nested" + else + fail "root listed before nested" + fi + + out="$TEST_ROOT/if-new.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" pkg/sub/newdir/new.js ) > "$out" + assert_contains "$out" "NESTED_RULE" "path in a missing directory still gets ancestor files" + + out="$TEST_ROOT/if-subdir.txt" + ( cd "$REPO/pkg/sub" && "$SDD_SCRIPTS/instruction-files" pkg/sub/widget.js ) > "$out" + assert_contains "$out" "NESTED_RULE" "root-relative paths work from a subdirectory" + + out="$TEST_ROOT/if-none.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" ) > "$out" + if [[ ! -s "$out" ]]; then pass "no paths, no output"; else fail "no paths, no output"; fi + + printf 'UNCOMMITTED_RULE: working tree only.\n' >> "$REPO/pkg/sub/AGENTS.md" + out="$TEST_ROOT/if-tree.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" --tree HEAD pkg/sub/widget.js ) > "$out" + assert_not_contains "$out" "UNCOMMITTED_RULE" "--tree reads the tree, not the working tree" + out="$TEST_ROOT/if-wt.txt" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" pkg/sub/widget.js ) > "$out" + assert_contains "$out" " 3 UNCOMMITTED_RULE: working tree only." "default mode reads the working tree" + ( cd "$REPO" && git checkout -q -- pkg/sub/AGENTS.md ) +} + +# make_change — commit c2: one-line edits deep inside widget.js and long.js, +# an edit in pkg/other, and a new 60-line file. +make_change() { + ( cd "$REPO" \ + && sed -i.bak 's/ let count = 0;/ let count = items.length;/' pkg/sub/widget.js \ + && sed -i.bak 's/ let seed = 0;/ let seed = 1;/' pkg/sub/long.js \ + && rm -f pkg/sub/*.bak \ + && printf 'export const other = 2;\n' > pkg/other/thing.js \ + && { echo 'function fresh() {'; filler 60 fresh; echo '}'; } > pkg/sub/fresh.js ) + commit_all "$REPO" c2 +} + +# package_path DIR BASE HEAD [-- PATHSPEC...] — the package path, from running +# review-package --print-path in DIR (SDD_CONTEXT_CAP etc. pass through). +package_path() { + local dir=$1 + shift + ( cd "$dir" && "$SDD_SCRIPTS/review-package" --print-path "$@" ) +} + +test_review_package() { + echo "--- review-package ---" + make_change + local out pkg + + pkg="$(package_path "$REPO" HEAD~1 HEAD)" + assert_has_line "$pkg" "## Instruction files (binding)" "package has the instruction section" + assert_has_line "$pkg" " 2 ROOT_RULE: keep functions small." "root rule inlined" + assert_has_line "$pkg" " 2 NESTED_RULE: never read a whole collection in one call." "nested rule inlined" + assert_contains "$pkg" "SIBLING_RULE" "rules of every changed file's directories (pkg/other changed)" + assert_not_contains "$pkg" "DEEP_RULE" "directory below a changed file excluded" + local files_line instr_line diff_line + files_line="$(grep -nxF '## Files changed' "$pkg" | cut -d: -f1)" + instr_line="$(grep -nxF '## Instruction files (binding)' "$pkg" | cut -d: -f1)" + diff_line="$(grep -nxF '## Diff' "$pkg" | cut -d: -f1)" + if [[ -n "$files_line" && -n "$instr_line" && -n "$diff_line" \ + && "$files_line" -lt "$instr_line" && "$instr_line" -lt "$diff_line" ]]; then + pass "section order: files changed, instruction files, diff" + else + fail "section order: files changed, instruction files, diff" + fi + assert_has_line "$pkg" " function renderPanel(items) {" "enclosing function opening line" + assert_has_line "$pkg" " } // end renderPanel" "enclosing function closing line" + assert_has_line "$pkg" " const farMarker = 1;" "default cap keeps the whole long function" + assert_contains "$pkg" "# Context: each hunk shows its whole enclosing function (cap: 400 lines per file)" "header names the context rule" + assert_not_contains "$pkg" "# context capped:" "nothing capped at the default cap" + + pkg="$(SDD_CONTEXT_CAP=45 package_path "$REPO" HEAD~1 HEAD)" + assert_has_line "$pkg" "# context capped: pkg/sub/long.js (function context over 45 lines; -U10 shown)" "over-cap file marked" + assert_contains "$pkg" "# Context capped (-U10 shown): pkg/sub/long.js" "header lists capped files" + assert_not_contains "$pkg" "farMarker" "capped file falls back to -U10" + assert_not_contains "$pkg" "# context capped: pkg/sub/widget.js" "under-cap file not marked" + assert_has_line "$pkg" " } // end renderPanel" "under-cap file keeps function context" + assert_not_contains "$pkg" "# context capped: pkg/sub/fresh.js" "new file never marked capped" + + assert_exit 2 "non-numeric SDD_CONTEXT_CAP rejected" \ + bash -c "cd '$REPO' && SDD_CONTEXT_CAP=abc '$SDD_SCRIPTS/review-package' HEAD~1 HEAD" + + pkg="$(package_path "$REPO" HEAD~1 HEAD -- pkg/sub/widget.js)" + assert_contains "$pkg" "NESTED_RULE" "pathspec run keeps the scoped file's rules" + assert_not_contains "$pkg" "SIBLING_RULE" "pathspec run drops out-of-scope rules" + assert_not_contains "$pkg" "pkg/sub/long.js" "pathspec run drops out-of-scope diffs" + + printf 'SNAPSHOT_RULE: from the working tree.\n' >> "$REPO/pkg/sub/AGENTS.md" + local before after + before="$(cd "$REPO" && git rev-parse 'HEAD^{tree}')" + after="$(cd "$REPO" && "$SDD_SCRIPTS/snapshot")" + pkg="$(package_path "$REPO" "$before" "$after")" + assert_has_line "$pkg" " 3 SNAPSHOT_RULE: from the working tree." "instruction files read from the HEAD tree-ish (snapshot)" + ( cd "$REPO" && git checkout -q -- pkg/sub/AGENTS.md ) +} + +# brief_path DIR PLAN N [OUTFILE] — the brief path, from running +# task-brief --print-path in DIR. +brief_path() { + local dir=$1 + shift + ( cd "$dir" && "$SDD_SCRIPTS/task-brief" --print-path "$@" ) +} + +test_task_brief() { + echo "--- task-brief ---" + cat > "$REPO/plan.md" <<'PLAN' +# Plan + +### Task 1: Sub change + +**Files:** +- Modify: `pkg/sub/widget.js:10-20` +- Test: `pkg/sub/widget.test.js` + +Do the sub change. + +### Task 2: Root change + +**Files:** +- Modify: `README.md` + +Do the root change. + +### Task 3: No files + +Do something without a Files block. + +### Task 4: New directory + +**Files:** +- Create: `pkg/sub/newdir/new.js` + +Create it. +PLAN + local out brief + + brief="$(brief_path "$REPO" plan.md 1)" + assert_contains "$brief" "Do the sub change." "brief keeps the task text" + assert_has_line "$brief" " 2 NESTED_RULE: never read a whole collection in one call." "Modify path with a line range gets nested rules" + assert_has_line "$brief" " 2 ROOT_RULE: keep functions small." "brief gets root rules" + assert_not_contains "$brief" "SIBLING_RULE" "brief excludes unrelated directories" + assert_not_contains "$brief" "Do the root change." "brief stops at the next task" + + brief="$(brief_path "$REPO" plan.md 2)" + assert_contains "$brief" "ROOT_RULE" "root-level file gets root rules" + assert_not_contains "$brief" "NESTED_RULE" "root-level file excludes nested rules" + + brief="$(brief_path "$REPO" plan.md 3)" + assert_not_contains "$brief" "## Instruction files" "no Files block, no section" + + brief="$(brief_path "$REPO" plan.md 4)" + assert_contains "$brief" "NESTED_RULE" "Create path in a new directory gets ancestor rules" + + mkdir -p "$TEST_ROOT/nogit" + cp "$REPO/plan.md" "$TEST_ROOT/nogit/plan.md" + if ( cd "$TEST_ROOT/nogit" && GIT_CEILING_DIRECTORIES="$TEST_ROOT" \ + "$SDD_SCRIPTS/task-brief" plan.md 1 brief.md ) >/dev/null 2>&1 \ + && ! grep -qF "## Instruction files" "$TEST_ROOT/nogit/brief.md"; then + pass "outside a git repo: brief written, no section" + else + fail "outside a git repo: brief written, no section" + fi +} + +test_print_path() { + echo "--- --print-path ---" + local out lines pkg brief + out="$(cd "$REPO" && "$SDD_SCRIPTS/review-package" HEAD~1 HEAD)" + if [[ "$out" == "wrote $REPO/"*": "* ]]; then pass "review-package default output starts with 'wrote :'"; else fail "review-package default output starts with 'wrote :'"; echo " got: $out"; fi + out="$(cd "$REPO" && "$SDD_SCRIPTS/task-brief" plan.md 1)" + if [[ "$out" == "wrote $REPO/"*": "* ]]; then pass "task-brief default output starts with 'wrote :'"; else fail "task-brief default output starts with 'wrote :'"; echo " got: $out"; fi + + out="$(cd "$REPO" && "$SDD_SCRIPTS/review-package" --print-path HEAD~1 HEAD -- pkg/sub/widget.js)" + lines="$(printf '%s\n' "$out" | wc -l | tr -d ' ')" + if [[ "$lines" == 1 && "$out" == /* && -f "$out" ]]; then pass "review-package --print-path: one line, an existing absolute file"; else fail "review-package --print-path: one line, an existing absolute file"; echo " got: $out"; fi + + out="$(cd "$REPO" && "$SDD_SCRIPTS/task-brief" --print-path plan.md 1)" + lines="$(printf '%s\n' "$out" | wc -l | tr -d ' ')" + if [[ "$lines" == 1 && "$out" == /* && -f "$out" ]]; then pass "task-brief --print-path: one line, an existing absolute file"; else fail "task-brief --print-path: one line, an existing absolute file"; echo " got: $out"; fi + + out="$(cd "$REPO" && "$SDD_SCRIPTS/task-brief" --print-path plan.md 1 rel-brief.md)" + lines="$(printf '%s\n' "$out" | wc -l | tr -d ' ')" + if [[ "$lines" == 1 && "$out" == "$REPO/rel-brief.md" && -f "$out" ]]; then pass "task-brief --print-path with a relative OUTFILE prints it absolute"; else fail "task-brief --print-path with a relative OUTFILE prints it absolute"; echo " got: $out"; fi + rm -f "$REPO/rel-brief.md" + + assert_exit 3 "task-brief --print-path: unknown task still exits 3" \ + bash -c "cd '$REPO' && '$SDD_SCRIPTS/task-brief' --print-path plan.md 99" + assert_exit 2 "review-package --print-path: bad BASE still exits 2" \ + bash -c "cd '$REPO' && '$SDD_SCRIPTS/review-package' --print-path nosuchrev HEAD" +} + +test_instruction_files_extras() { + echo "--- instruction-files: arguments, ordering, symlinks ---" + local out + out="$TEST_ROOT/ife.txt" + + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" pkg/other/thing.js pkg/sub/widget.js ) > "$out" + local listed + listed="$(grep '^- ' "$out" | paste -sd' ' -)" + if [[ "$listed" == "- AGENTS.md - pkg/other/AGENTS.md - pkg/sub/AGENTS.md - pkg/sub/CLAUDE.md" ]]; then + pass "several PATHs merge, root first then by depth" + else + fail "several PATHs merge, root first then by depth"; echo " got: $listed" + fi + + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" ./pkg/sub/widget.js ) > "$out" + assert_has_line "$out" "- pkg/sub/AGENTS.md" "./-prefixed path resolves" + + local snap + snap="$(cd "$REPO" && "$SDD_SCRIPTS/snapshot")" + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" --tree "$snap" pkg/sub/widget.js ) > "$out" + assert_contains "$out" "NESTED_RULE" "--tree accepts a snapshot tree SHA" + + assert_exit 2 "--tree without an argument exits 2" \ + bash -c "cd '$REPO' && '$SDD_SCRIPTS/instruction-files' --tree" + assert_exit 2 "bad TREEISH exits 2" \ + bash -c "cd '$REPO' && '$SDD_SCRIPTS/instruction-files' --tree nosuchref x.js" + assert_exit 2 "unknown flag exits 2" \ + bash -c "cd '$REPO' && '$SDD_SCRIPTS/instruction-files' --trees HEAD x.js" + mkdir -p "$TEST_ROOT/nogit2" + assert_exit 2 "outside a git repo exits 2" \ + bash -c "cd '$TEST_ROOT/nogit2' && GIT_CEILING_DIRECTORIES='$TEST_ROOT' '$SDD_SCRIPTS/instruction-files' x.js" + + local lr + lr="$(new_repo linkrepo)" + mkdir -p "$lr/sub" "$lr/sub2" "$lr/sp ace" + printf 'LINK_RULE: root.\n' > "$lr/AGENTS.md" + ln -s AGENTS.md "$lr/CLAUDE.md" + printf 'SUB_RULE: sub.\n' > "$lr/sub/AGENTS.md" + ln -s ../AGENTS.md "$lr/sub/CLAUDE.md" + ln -s ../../missing "$lr/sub2/CLAUDE.md" + printf 'SPACE_RULE: spaced.\n' > "$lr/sp ace/AGENTS.md" + commit_all "$lr" links + ( cd "$lr" && "$SDD_SCRIPTS/instruction-files" sub/x.js ) > "$out" + assert_has_line "$out" "### CLAUDE.md — identical to AGENTS.md" "working tree: root symlink deduped" + assert_has_line "$out" "### sub/CLAUDE.md — identical to AGENTS.md" "working tree: relative symlink deduped" + ( cd "$lr" && "$SDD_SCRIPTS/instruction-files" --tree HEAD sub/x.js ) > "$out" + assert_has_line "$out" "### CLAUDE.md — identical to AGENTS.md" "--tree: root symlink deduped" + assert_has_line "$out" "### sub/CLAUDE.md — identical to AGENTS.md" "--tree: ../ symlink deduped" + ( cd "$lr" && "$SDD_SCRIPTS/instruction-files" --tree HEAD sub2/x.js ) > "$out" + assert_has_line "$out" "### sub2/CLAUDE.md — symlink to ../../missing" "--tree: unresolvable symlink named" + ( cd "$lr" && "$SDD_SCRIPTS/instruction-files" "sp ace/f.js" ) > "$out" + assert_contains "$out" "SPACE_RULE" "working tree: path with a space" + ( cd "$lr" && "$SDD_SCRIPTS/instruction-files" --tree HEAD "sp ace/f.js" ) > "$out" + assert_contains "$out" "SPACE_RULE" "--tree: path with a space" + + ( cd "$REPO" && "$SDD_SCRIPTS/instruction-files" -- pkg/sub/widget.js ) > "$TEST_ROOT/dd.txt" + assert_contains "$TEST_ROOT/dd.txt" "NESTED_RULE" "instruction-files accepts -- as end of options" + + local ol + ol="$(new_repo outlink)" + printf 'SECRET_OUTSIDE: do not print.\n' > "$TEST_ROOT/outside.md" + mkdir -p "$ol/d" "$ol/e" + printf 'IN_RULE: inside.\n' > "$ol/AGENTS.md" + ln -s "$TEST_ROOT/outside.md" "$ol/d/CLAUDE.md" + ln -s ../../outside.md "$ol/e/CLAUDE.md" + commit_all "$ol" ol + ( cd "$ol" && "$SDD_SCRIPTS/instruction-files" d/x.js e/y.js ) > "$TEST_ROOT/ol.txt" + assert_not_contains "$TEST_ROOT/ol.txt" "SECRET_OUTSIDE" "symlink outside the repo is not read" + assert_has_line "$TEST_ROOT/ol.txt" "### d/CLAUDE.md — symlink outside the repository (not read)" "absolute outside symlink named" + assert_has_line "$TEST_ROOT/ol.txt" "### e/CLAUDE.md — symlink outside the repository (not read)" "relative outside symlink named" + assert_contains "$TEST_ROOT/ol.txt" "IN_RULE" "in-repo rules still printed" + + local esc outd + esc="$(new_repo escape)" + outd="$TEST_ROOT/escape-outside" + mkdir -p "$outd" "$TEST_ROOT/b" + printf 'SECRET_ESCAPE: do not print.\n' > "$TEST_ROOT/b/x" + ln -s ../b/x "$outd/CLAUDE.md" + ln -s "$outd" "$esc/sub" + mkdir -p "$esc/b" + printf 'decoy\n' > "$esc/b/keep" + commit_all "$esc" esc + ( cd "$esc" && "$SDD_SCRIPTS/instruction-files" sub/f.js ) > "$TEST_ROOT/esc.txt" + assert_not_contains "$TEST_ROOT/esc.txt" "SECRET_ESCAPE" "dir symlink + ../ link target: outside file not read" + assert_contains "$TEST_ROOT/esc.txt" "symlink outside the repository (not read)" "dir symlink + ../ link target: named as outside" +} + +test_review_package_extras() { + echo "--- review-package: diff config, rename, binary, big file ---" + local out pkg + + ( cd "$REPO" && git config color.ui always && git config diff.external /bin/echo ) + pkg="$(package_path "$REPO" HEAD~1 HEAD)" + ( cd "$REPO" && git config --unset color.ui && git config --unset diff.external ) + assert_has_line "$pkg" " } // end renderPanel" "color.ui=always and diff.external do not empty the diff" + + assert_exit 2 "SDD_CONTEXT_CAP=0 rejected" \ + bash -c "cd '$REPO' && SDD_CONTEXT_CAP=0 '$SDD_SCRIPTS/review-package' HEAD~1 HEAD" + + local rr + rr="$(new_repo rr)" + seq 1 30 | sed 's/^/line /' > "$rr/old.txt" + printf '\000\001\002' > "$rr/bin.dat" + mkdir -p "$rr/dir b" + { echo 'function oldLong() {'; filler 60 rl; echo ' let mark = 0;'; filler 60 rm; echo '}'; } > "$rr/old long.js" + commit_all "$rr" r1 + ( cd "$rr" && git mv old.txt new.txt && sed -i.bak 's/^line 5$/line five/' new.txt && rm -f new.txt.bak \ + && printf '\000\001\003' > bin.dat \ + && git mv "old long.js" "dir b/new long.js" && sed -i.bak 's/ let mark = 0;/ let mark = 1;/' "dir b/new long.js" && rm -f "dir b/new long.js.bak" ) + commit_all "$rr" r2 + pkg="$(SDD_CONTEXT_CAP=45 package_path "$rr" HEAD~1 HEAD)" + assert_has_line "$pkg" "rename to new.txt" "rename shown" + assert_contains "$pkg" "Binary files" "binary change shown" + assert_has_line "$pkg" "# context capped: dir b/new long.js (function context over 45 lines; -U10 shown)" "capped path with a space and ' b/' extracted whole" + assert_has_line "$pkg" "# Context capped (-U10 shown): dir b/new long.js" "header lists that capped path" + + local big + big="$(new_repo big)" + { echo 'function huge() {'; filler 20000 hg; echo ' let target = 0;'; echo '}'; } > "$big/huge.js" + commit_all "$big" b1 + sed -i.bak 's/ let target = 0;/ let target = 1;/' "$big/huge.js" && rm -f "$big/huge.js.bak" + commit_all "$big" b2 + pkg="$(package_path "$big" HEAD~1 HEAD)" + assert_contains "$pkg" "# context capped: huge.js" "20k-line function file: package produced, capped" + assert_contains "$pkg" "+ let target = 1;" "20k-line function file: change present" + + local tc + tc="$(new_repo tc)" + printf 'plain\n' > "$tc/a.txt" + { echo 'function longOne() {'; filler 30 aa; echo ' let mark = 0;'; filler 30 bb; echo '}'; } > "$tc/z.js" + commit_all "$tc" t1 + ( cd "$tc" && rm a.txt && ln -s z.js a.txt && sed -i.bak 's/ let mark = 0;/ let mark = 1;/' z.js && rm -f z.js.bak ) + commit_all "$tc" t2 + pkg="$(SDD_CONTEXT_CAP=45 package_path "$tc" HEAD~1 HEAD)" + assert_has_line "$pkg" "# context capped: z.js (function context over 45 lines; -U10 shown)" "typechange before a capped file: label names the capped file" + assert_not_contains "$pkg" "# context capped: a.txt" "typechanged file not labelled capped" +} + +test_snapshot_filemode() { + echo "--- snapshot: core.fileMode=false ---" + local fm out pkg before after + fm="$(new_repo fm)" + printf '#!/bin/sh\necho hi\n' > "$fm/run.sh" + chmod +x "$fm/run.sh" + printf 'a\n' > "$fm/other.txt" + commit_all "$fm" f1 + ( cd "$fm" && git config core.fileMode false ) + printf 'b\n' >> "$fm/other.txt" + before="$(cd "$fm" && git rev-parse 'HEAD^{tree}')" + after="$(cd "$fm" && "$SDD_SCRIPTS/snapshot")" + pkg="$(package_path "$fm" "$before" "$after")" + assert_contains "$pkg" "+b" "unrelated change present" + assert_not_contains "$pkg" "old mode" "no bogus mode change under core.fileMode=false" +} + +test_task_brief_extras() { + echo "--- task-brief: Files block parsing ---" + local out brief + cat > "$REPO/plan2.md" <<'PLAN' +# Plan + +### Task 1: Prose bullet after the block + +**Files:** +- Modify: `README.md` + +- A prose bullet mentioning `pkg/sub/widget.js` in passing. + +### Task 2: Fenced example + +Example of the format: + +``` +**Files:** +- Modify: `pkg/sub/widget.js` +``` + +Nothing real here. + +### Task 3: Non-path token + +**Files:** +- Modify: `README.md` and call `renderPanel()` +PLAN + brief="$(brief_path "$REPO" plan2.md 1)" + assert_contains "$brief" "ROOT_RULE" "block item parsed" + assert_not_contains "$brief" "NESTED_RULE" "prose bullet after a blank line not parsed" + brief="$(brief_path "$REPO" plan2.md 2)" + assert_not_contains "$brief" "## Instruction files" "fenced Files example ignored" + brief="$(brief_path "$REPO" plan2.md 3)" + assert_contains "$brief" "ROOT_RULE" "real path still resolved beside a non-path token" + assert_not_contains "$brief" "NESTED_RULE" "backticked non-path token pulls in no nested rules" + + cat > "$REPO/plan3.md" <<'PLAN' +# Plan + +### Task 1: Dash-leading token + +**Files:** +- Modify: `--verbose` handling in `pkg/sub/cli.sh` + +Do it. + +### Task 2: Wrapped item + +**Files:** +- Modify: `README.md`, and a long description that wraps onto + a second line naming `pkg/sub/widget.js` +- Test: `pkg/other/thing.js` + +Do it. +PLAN + brief="$(brief_path "$REPO" plan3.md 1)" + if [[ -n "$brief" && -f "$brief" ]]; then pass "dash-leading first token: brief written"; else fail "dash-leading first token: brief written"; fi + assert_contains "$brief" "NESTED_RULE" "dash-leading first token: later path still resolved" + + brief="$(brief_path "$REPO" plan3.md 2)" + assert_contains "$brief" "NESTED_RULE" "wrapped item: continuation line path resolved" + assert_contains "$brief" "SIBLING_RULE" "wrapped item: following item still resolved" +} + + +main() { + echo "=== Test: sdd review context ===" + + TEST_ROOT="$(mktemp -d)" + trap cleanup EXIT + + make_fixture + test_instruction_files + test_review_package + test_task_brief + test_print_path + test_instruction_files_extras + test_review_package_extras + test_snapshot_filemode + test_task_brief_extras + + echo "" + if [[ "$FAILURES" -ne 0 ]]; then + echo "FAILED: $FAILURES assertion(s)." + exit 1 + fi + echo "PASS" +} + +main "$@"