Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 68 additions & 17 deletions scripts/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@
uv run python scripts/repo.py validate-remote org/repo
uv run python scripts/repo.py safe-checkout ~/Code/repo branch
uv run python scripts/repo.py safe-checkout ~/Code/repo branch --remote target
uv run python scripts/repo.py publish-artifacts ~/Code/repo feature "msg"
uv run python scripts/repo.py stage ~/Code/repo feature
uv run python scripts/repo.py publish-artifacts ~/Code/repo plans/feature "msg"
uv run python scripts/repo.py stage ~/Code/repo plans/feature
uv run python scripts/repo.py pr-create org/repo branch "Title" "Body"
uv run python scripts/repo.py pr-comments org/repo 10
"""
Expand Down Expand Up @@ -176,66 +176,115 @@ def _handle_github_pr(owner, repo, pr_number):
exit_error(f"ERROR: Failed to fetch PR {pr_number}: {e}")


# Treat staged paths as literal names, not wildcard pathspecs, so a name containing
# *, ? or [...] cannot match sibling paths.
_LITERAL_PATHSPEC_ENV = {**os.environ, "GIT_LITERAL_PATHSPECS": "1"}


def _feature_dir_and_rel(repo_path, feature_name):
"""Resolve a feature basename or path to (dir, repo-relative posix path, error)."""
repo = Path(repo_path).expanduser().resolve()
raw = Path(os.path.expanduser(str(feature_name)))
feature_dir = raw.resolve() if raw.is_absolute() else (repo / raw).resolve()
try:
rel = feature_dir.relative_to(repo)
except ValueError:
return None, None, f"feature path is outside the repository: {feature_name}"
if rel == Path("."):
return None, None, "feature path must be a subdirectory of the repository"
return feature_dir, rel.as_posix(), None


def stage_artifacts(repo_path, feature_name):
"""Selectively stage test plan artifacts for commit.

Stages required files (TestPlan.md, README.md) and optional files
(TestPlanGaps.md, TestPlanReview.md, .source-design-spec.md, test_cases/*.md)
if they exist.
if they exist. Tracked test_cases/*.md files deleted from the working tree are
staged as deletions; other files under test_cases/ are never staged.

Args:
repo_path: Path to git repository root
feature_name: Name of the feature directory (basename)
feature_name: Feature directory basename, repo-relative path, or absolute path
inside the repository

Returns:
(exit_code, result_dict) where result_dict contains:
- staged_files: list of staged relative paths
- skipped_files: list of skipped relative paths
- error: error message (only on failure)
"""
feature_dir = Path(repo_path) / feature_name
feature_dir, rel_feature, error = _feature_dir_and_rel(repo_path, feature_name)
if error:
return 1, {"error": error}

staged = []
skipped = []

required = ["TestPlan.md", "README.md"]
for name in required:
if not (feature_dir / name).is_file():
return 1, {"error": f"{name} not found in {feature_name}/"}
return 1, {"error": f"{name} not found in {rel_feature}/"}

optional = ["TestPlanGaps.md", "TestPlanReview.md", ".source-design-spec.md"]

# Discover test case paths before staging anything so a failure leaves the index untouched.
# Only direct-child test_cases/*.md files are published; other files and
# nested directories stay unstaged. Deleted tracked *.md files are staged too.
tc_rel = f"{rel_feature}/test_cases"
tc_dir = feature_dir / "test_cases"
tc_files = []
if tc_dir.is_dir():
tc_files.extend(f"{tc_rel}/{md.name}" for md in sorted(tc_dir.glob("*.md")) if md.is_file())
try:
# -z emits raw path bytes; decode with surrogateescape to round-trip non-UTF-8 names.
deleted_out = subprocess.run(
["git", "ls-files", "--deleted", "-z", "--", tc_rel],
cwd=repo_path,
capture_output=True,
check=True,
env=_LITERAL_PATHSPEC_ENV,
).stdout
except subprocess.CalledProcessError as e:
return 1, {"error": f"git ls-files failed for {tc_rel}: {e}"}
tc_prefix = f"{tc_rel}/"
for path in deleted_out.decode("utf-8", errors="surrogateescape").split("\0"):
name = path[len(tc_prefix) :]
if path.startswith(tc_prefix) and name.endswith(".md") and "/" not in name:
tc_files.append(path)

for name in required + optional:
rel = f"{feature_name}/{name}"
rel = f"{rel_feature}/{name}"
if (feature_dir / name).is_file():
try:
subprocess.run(
["git", "add", rel],
["git", "add", "--", rel],
cwd=repo_path,
capture_output=True,
check=True,
env=_LITERAL_PATHSPEC_ENV,
)
staged.append(rel)
except subprocess.CalledProcessError as e:
return 1, {"error": f"git add failed for {rel}: {e}"}
else:
skipped.append(rel)

tc_dir = feature_dir / "test_cases"
if tc_dir.is_dir():
for md_file in tc_dir.glob("*.md"):
rel = f"{feature_name}/test_cases/{md_file.name}"
if tc_dir.is_dir() or tc_files:
for rel in tc_files:
try:
subprocess.run(
["git", "add", rel],
["git", "add", "-A", "--", rel],
Comment thread
fullsend-ai-coder[bot] marked this conversation as resolved.
Resolved
Comment thread
fege marked this conversation as resolved.
Resolved
cwd=repo_path,
capture_output=True,
check=True,
env=_LITERAL_PATHSPEC_ENV,
)
staged.append(rel)
except subprocess.CalledProcessError as e:
return 1, {"error": f"git add failed for {rel}: {e}"}
else:
skipped.append(f"{feature_name}/test_cases/")
skipped.append(f"{tc_rel}/")

return 0, {"staged_files": staged, "skipped_files": skipped}

Expand All @@ -248,7 +297,7 @@ def publish_artifacts(repo_path, feature_name, message):

Args:
repo_path: Path to git repository root
feature_name: Name of the feature directory (basename)
feature_name: Feature directory basename, repo-relative path, or absolute path
message: Commit message

Returns:
Expand Down Expand Up @@ -850,14 +899,16 @@ def main():
"publish-artifacts", help="Stage test plan artifacts, check for changes, and commit"
)
parser_publish.add_argument("repo_path", help="Path to git repository root")
parser_publish.add_argument("feature_name", help="Feature directory name (basename)")
parser_publish.add_argument(
"feature_name", help="Feature directory (basename, repo-relative path, or absolute path)"
)
parser_publish.add_argument("message", help="Commit message")
parser_publish.set_defaults(func=cmd_publish_artifacts)

# stage command
parser_stage = subparsers.add_parser("stage", help="Selectively stage test plan artifacts for commit")
parser_stage.add_argument("repo_path", help="Path to git repository root")
parser_stage.add_argument("feature_name", help="Feature directory name (basename)")
parser_stage.add_argument("feature_name", help="Feature directory (basename, repo-relative path, or absolute path)")
parser_stage.set_defaults(func=cmd_stage)

# safe-checkout command
Expand Down
3 changes: 1 addition & 2 deletions skills/test-plan-case-implement/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -544,9 +544,8 @@ Returns JSON with `updated_count`, `updated_tcs`, `errors`. Show any errors to u

If feature source is a GitHub branch, stage, commit, and push updated TC files:
```bash
feature_name=$(basename "$feature_dir")
repo_root=$(git -C "$feature_dir" rev-parse --show-toplevel)
if ! publish_result=$(cd "$(cd -P "${CLAUDE_SKILL_DIR}/../.." && pwd -P)" && uv run python scripts/repo.py publish-artifacts "$repo_root" "$feature_name" "test-plan(<source_key>): mark TCs as implemented"); then
if ! publish_result=$(cd "$(cd -P "${CLAUDE_SKILL_DIR}/../.." && pwd -P)" && uv run python scripts/repo.py publish-artifacts "$repo_root" "$feature_dir" "test-plan(<source_key>): mark TCs as implemented"); then
echo "ERROR: publish-artifacts failed"; exit 1
fi
git push origin <branch_name>
Expand Down
3 changes: 1 addition & 2 deletions skills/test-plan-publish/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,7 @@ If the user declines, stop.

4. Stage, check for changes, and commit in one call:
```bash
feature_name=$(basename "$feature_dir")
if ! publish_result=$(cd $(git -C ${CLAUDE_SKILL_DIR} rev-parse --show-toplevel) && uv run python scripts/repo.py publish-artifacts "$repo_root" "$feature_name" "test-plan(<source_key>): publish <feature> v<version>"); then
if ! publish_result=$(cd $(git -C ${CLAUDE_SKILL_DIR} rev-parse --show-toplevel) && uv run python scripts/repo.py publish-artifacts "$repo_root" "$feature_dir" "test-plan(<source_key>): publish <feature> v<version>"); then
echo "ERROR: publish-artifacts failed"; exit 1
fi
committed=$(printf '%s\n' "$publish_result" | jq -r '.committed')
Expand Down
7 changes: 4 additions & 3 deletions skills/test-plan-resolve-feedback/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,10 @@ If NOT found (exit code 1, empty output):
#### 0.5 Locate feature directory
Find the feature directory by looking for `TestPlan.md` on the branch:
```bash
find . -name "TestPlan.md" -not -path "./.claude/*"
repo_path=$(cd "$repo_path" && pwd -P)
find "$repo_path" -name "TestPlan.md" -not -path "$repo_path/.claude/*"
```
Search from the located checkout (`$repo_path`), never the current directory, which may be a different repo or a subdirectory. Set `feature_dir` to the absolute directory containing the selected `TestPlan.md` (e.g. `$(dirname "<found_path>")`).
If multiple feature directories are found, ask the user which one to use via AskUserQuestion.

#### 0.6 Validate frontmatter
Expand Down Expand Up @@ -215,9 +217,8 @@ If any validation fails, fix the issue before proceeding.
2. Stage, check for changes, and commit in one call:

```bash
feature_name=$(basename "$feature_dir")
repo_root=$(git -C "$feature_dir" rev-parse --show-toplevel)
if ! publish_result=$(cd "$(cd -P "${CLAUDE_SKILL_DIR}/../.." && pwd -P)" && uv run python scripts/repo.py publish-artifacts "$repo_root" "$feature_name" "test-plan(<source_key>): <short summary of changes> (PR #<PR_NUMBER>)"); then
if ! publish_result=$(cd "$(cd -P "${CLAUDE_SKILL_DIR}/../.." && pwd -P)" && uv run python scripts/repo.py publish-artifacts "$repo_root" "$feature_dir" "test-plan(<source_key>): <short summary of changes> (PR #<PR_NUMBER>)"); then
Comment thread
fege marked this conversation as resolved.
Resolved
echo "ERROR: publish-artifacts failed"; exit 1
fi
```
Expand Down
148 changes: 148 additions & 0 deletions tests/unit/test_repo_stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,151 @@ def test_fails_when_required_file_missing(git_repo, missing, present):

assert exit_code == 1
assert missing in result["error"]


def test_nested_feature_dir_with_full_path(git_repo):
"""A feature under plans/ is staged when the full path is passed, not the basename."""
add_feature(git_repo, "plans/feat", ["TestPlan.md", "README.md"])

exit_code, result = stage_artifacts(str(git_repo), "feat")
assert exit_code == 1
assert "TestPlan.md" in result["error"]

exit_code, result = stage_artifacts(str(git_repo), str(git_repo / "plans" / "feat"))
assert exit_code == 0
assert "plans/feat/TestPlan.md" in result["staged_files"]
assert "plans/feat/README.md" in result["staged_files"]
staged = _staged_files(git_repo)
assert "plans/feat/TestPlan.md" in staged


def test_nested_feature_dir_with_relative_path(git_repo):
"""A repo-relative feature path (plans/feat) stages files under that prefix."""
add_feature(git_repo, "plans/feat", ["TestPlan.md", "README.md"])

exit_code, result = stage_artifacts(str(git_repo), "plans/feat")

assert exit_code == 0
assert "plans/feat/TestPlan.md" in result["staged_files"]
staged = _staged_files(git_repo)
assert "plans/feat/TestPlan.md" in staged


def test_rejects_feature_path_outside_repo(git_repo, tmp_path):
"""A feature directory outside the git root is rejected."""
outside = tmp_path.parent / "outside-feature"
outside.mkdir()
(outside / "TestPlan.md").write_text("# TestPlan.md\n")
(outside / "README.md").write_text("# README.md\n")

exit_code, result = stage_artifacts(str(git_repo), str(outside))

assert exit_code == 1
assert "outside" in result["error"]


def test_deleted_test_case_is_staged(git_repo):
"""Removing a tracked TC stages the deletion so the working tree is clean after commit."""
add_feature(
git_repo,
"feat",
["TestPlan.md", "README.md", "test_cases/TC-E2E-001.md", "test_cases/TC-E2E-002.md"],
)
exit_code, _ = stage_artifacts(str(git_repo), "feat")
assert exit_code == 0
subprocess.run(["git", "commit", "-m", "add tcs"], cwd=git_repo, capture_output=True, check=True)

(git_repo / "feat" / "test_cases" / "TC-E2E-002.md").unlink()
exit_code, result = stage_artifacts(str(git_repo), "feat")

assert exit_code == 0
status = subprocess.run(
["git", "diff", "--cached", "--name-status"],
cwd=git_repo,
capture_output=True,
text=True,
check=True,
).stdout
assert "D\tfeat/test_cases/TC-E2E-002.md" in status
assert "feat/test_cases/TC-E2E-002.md" in result["staged_files"]


def test_non_markdown_and_nested_test_case_files_not_staged(git_repo):
"""Only direct-child test_cases/*.md is staged; other files and subdirectories stay unstaged."""
add_feature(
git_repo,
"feat",
["TestPlan.md", "README.md", "test_cases/TC-E2E-001.md", "test_cases/TC-E2E-002.md"],
)
exit_code, _ = stage_artifacts(str(git_repo), "feat")
assert exit_code == 0
subprocess.run(["git", "commit", "-m", "add tcs"], cwd=git_repo, capture_output=True, check=True)

tc_dir = git_repo / "feat" / "test_cases"
(tc_dir / "TC-E2E-002.md").unlink()
(tc_dir / "debug.json").write_text("{}\n")
(tc_dir / "draft").mkdir()
(tc_dir / "draft" / "secret.env").write_text("TOKEN=x\n")
(tc_dir / "draft" / "notes.md").write_text("# notes\n")

exit_code, result = stage_artifacts(str(git_repo), "feat")

assert exit_code == 0
assert "feat/test_cases/TC-E2E-002.md" in result["staged_files"]
assert "feat/test_cases/TC-E2E-001.md" in result["staged_files"]
staged = _staged_files(git_repo)
assert "feat/test_cases/TC-E2E-002.md" in staged
assert not any(path.endswith(("debug.json", "secret.env", "notes.md")) for path in staged)
assert not any("debug.json" in p or "draft" in p for p in result["staged_files"])


def test_feature_path_wildcards_are_literal(git_repo):
"""A wildcard-named feature dir does not stage a modified sibling that the glob would match."""
add_feature(git_repo, "feat1", ["TestPlan.md", "README.md"])
add_feature(git_repo, "feat[1]", ["TestPlan.md", "README.md"])

exit_code, _ = stage_artifacts(str(git_repo), "feat[1]")

assert exit_code == 0
staged = _staged_files(git_repo)
assert sorted(staged) == ["feat[1]/README.md", "feat[1]/TestPlan.md"]


def test_test_case_wildcards_are_literal(git_repo):
"""A tracked TC named with a wildcard stages only itself, not siblings or nested files."""
add_feature(
git_repo,
"feat",
["TestPlan.md", "README.md", "test_cases/TC-1?.md", "test_cases/TC-10.md"],
)
subprocess.run(["git", "add", "--", "feat/test_cases/TC-1?.md"], cwd=git_repo, capture_output=True, check=True)
subprocess.run(["git", "add", "--", "feat/TestPlan.md", "feat/README.md"], cwd=git_repo, check=True)
subprocess.run(["git", "commit", "-m", "base"], cwd=git_repo, capture_output=True, check=True)
(git_repo / "feat" / "test_cases" / "TC-1?.md").unlink()
(git_repo / "feat" / "test_cases" / "TC-10.md").write_text("# untracked sibling\n")

exit_code, result = stage_artifacts(str(git_repo), "feat")

assert exit_code == 0
assert "feat/test_cases/TC-1?.md" in result["staged_files"]
# TC-10.md is a direct-child *.md so it is staged on its own, but only once, via its literal name.
assert result["staged_files"].count("feat/test_cases/TC-10.md") == 1


def test_discovery_failure_returns_json_error_without_staging(git_repo, monkeypatch):
"""A git ls-files failure returns a JSON error and leaves the index untouched."""
add_feature(git_repo, "feat", ["TestPlan.md", "README.md"])
real_run = subprocess.run

def fake_run(cmd, *args, **kwargs):
if cmd[:2] == ["git", "ls-files"]:
raise subprocess.CalledProcessError(128, cmd)
return real_run(cmd, *args, **kwargs)

monkeypatch.setattr("scripts.repo.subprocess.run", fake_run)

exit_code, result = stage_artifacts(str(git_repo), "feat")

assert exit_code == 1
assert "git ls-files failed" in result["error"]
assert _staged_files(git_repo) == []
Loading