From aeafc6291fd11ab92f9294fc1c2d8a1c86d02bae Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 25 Nov 2026 18:22:12 -0500 Subject: [PATCH] fix(loop): refuse to cut a feature branch from a base that lacks the feature MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3601. When PLAN.md's `branch` did not exist, ensure_feature_branch cut it from the declared `base` with `git checkout -B`. A feature folder committed only on the current branch is absent from that base, so the new branch had no PLAN.md: the next read raised a bare FileNotFoundError and the operator was left on the new branch. ensure_feature_branch now checks, before switching, whether the feature's PLAN.md is committed at HEAD but missing from the base, and raises FeatureBranchError naming the path, the base and the two ways forward. The operator stays on their branch. An untracked folder (the --prepare path) and a base that holds the feature behave as before. The normal `specfuse run` path now prints a FeatureBranchError and exits 1 instead of a traceback, as --prepare already did. Tests: - tests/test_feature_branch_missing_on_base.py:TestFeatureMissingOnBase — refusal before switching (red on unchanged code), plus two controls: base holding the feature, and an untracked folder riding along. Verification: - scripts/smoke-test.sh: 5104 tests OK, smoke test OK Co-Authored-By: Claude Opus 5.5 --- ...pecfuse-run-no-longer-cuts-a-missing-fe.md | 5 + specfuse/loop/loop.py | 51 ++++++- tests/test_feature_branch_missing_on_base.py | 127 ++++++++++++++++++ 3 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 changelog.d/3601-specfuse-run-no-longer-cuts-a-missing-fe.md create mode 100644 tests/test_feature_branch_missing_on_base.py diff --git a/changelog.d/3601-specfuse-run-no-longer-cuts-a-missing-fe.md b/changelog.d/3601-specfuse-run-no-longer-cuts-a-missing-fe.md new file mode 100644 index 00000000..e449ccfa --- /dev/null +++ b/changelog.d/3601-specfuse-run-no-longer-cuts-a-missing-fe.md @@ -0,0 +1,5 @@ +--- +class: fixed +trace: #3601 +--- +specfuse run no longer cuts a missing feature branch from a base that lacks the feature folder and then crashes; it refuses before switching branches and says how to proceed. diff --git a/specfuse/loop/loop.py b/specfuse/loop/loop.py index 021674ad..bf0c78f2 100644 --- a/specfuse/loop/loop.py +++ b/specfuse/loop/loop.py @@ -3554,6 +3554,34 @@ def _checked_checkout(checkout_args: list[str], action: str) -> str: return proc.stdout.strip() +def _feature_plan_missing_on_base(feature_dir: "Path | None", base: str) -> "str | None": + """Repo-relative PLAN.md path when it is committed at HEAD but absent from + *base*, else None (#3601). None too when it cannot be resolved: this guard + only ever adds a refusal, never a new way to fail.""" + if feature_dir is None: + return None + try: + top = subprocess.run( + ["git", "rev-parse", "--show-toplevel"], + capture_output=True, text=True, check=True, + ).stdout.strip() + rel = (Path(feature_dir) / "PLAN.md").resolve().relative_to( + Path(top).resolve() + ).as_posix() + except (subprocess.CalledProcessError, ValueError): + return None + + def _present(rev: str) -> bool: + return subprocess.run( + ["git", "cat-file", "-e", f"{rev}:{rel}"], + capture_output=True, check=False, + ).returncode == 0 + + if _present("HEAD") and not _present(base): + return rel + return None + + def ensure_feature_branch(feat_fm: dict, feature_dir: "Path | None" = None) -> None: """Ensure HEAD is on the feature's declared branch, creating it if needed. @@ -3712,6 +3740,22 @@ def ensure_feature_branch(feat_fm: dict, feature_dir: "Path | None" = None) -> N ) print(f"Switched to feature branch '{branch}' (was on '{current}').") else: + # A feature folder committed on the current branch but absent from the + # base would not exist on a branch cut from that base: the next read of + # PLAN.md would crash with the operator already moved off their branch + # (#3601). Refuse before switching. An untracked folder is unaffected + # -- `checkout -B` carries it along, which is what --prepare relies on. + plan_rel = _feature_plan_missing_on_base(feature_dir, base) + if plan_rel: + raise FeatureBranchError( + f"feature branch '{branch}' does not exist, and its base " + f"'{base}' does not contain '{plan_rel}': a branch cut from " + f"'{base}' would not hold this feature. The feature is " + f"committed on '{current}'. Either create the branch from here " + f"(`git branch {branch}`) or merge the feature into '{base}' " + f"first, then re-run. Nothing was switched; you are still on " + f"'{current}'." + ) # Create-from-base carries the working tree onto the new branch. Only # the expected /pick-feature flips may ride along; anything else stops. dirty = _tracked_dirty_paths() @@ -11862,7 +11906,12 @@ def run( require_session_env_writable() require_feature_folder_committed(feature_dir, feat_fm, feature_id) require_feature_folder_unmodified(feature_dir, feat_fm, feature_id) - ensure_feature_branch(feat_fm, feature_dir) + try: + ensure_feature_branch(feat_fm, feature_dir) + except FeatureBranchError as exc: + print(f"specfuse run cannot enter the feature branch:\n{exc}", + file=sys.stderr) + return 1 try: diff --git a/tests/test_feature_branch_missing_on_base.py b/tests/test_feature_branch_missing_on_base.py new file mode 100644 index 00000000..a9fcdf66 --- /dev/null +++ b/tests/test_feature_branch_missing_on_base.py @@ -0,0 +1,127 @@ +# +# Copyright 2026 Specfuse contributors +# Licensed under the Apache License, Version 2.0. See LICENSE. +# +"""ensure_feature_branch must not cut a branch that lacks the feature (#3601). + +A feature folder committed on a working branch, whose PLAN.md names a branch +that does not exist yet and a `base` that does not contain the folder, used to +be cut from that base: the new branch had no PLAN.md, the next read raised a +bare FileNotFoundError, and the operator was left on the new branch. The driver +now refuses before switching, and leaves the operator where they were. + +Real git in a tmpdir; no mocking. +""" + +from __future__ import annotations + +import os +import subprocess +import unittest +from contextlib import contextmanager +from pathlib import Path +from tempfile import TemporaryDirectory + +from tests._loop_loader import load_loop + +loop = load_loop() + +FEATURE = ".specfuse/features/FEAT-X-0001-demo" +FM = {"branch": "feat/FEAT-X-0001-demo", "base": "main"} + + +def _git(root: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(root), *args], + capture_output=True, text=True, check=True, + ).stdout.strip() + + +@contextmanager +def _chdir(path: Path): + prev = Path.cwd() + os.chdir(path) + try: + yield + finally: + os.chdir(prev) + + +@contextmanager +def _repo(): + """A temp git repo on `main` with one commit, no origin configured.""" + with TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + subprocess.run(["git", "init", "-q", "-b", "main", str(root)], check=True) + _git(root, "config", "user.email", "test@example.com") + _git(root, "config", "user.name", "Test") + _git(root, "config", "commit.gpgSign", "false") + (root / "README.md").write_text("# fixture\n") + _git(root, "add", ".") + _git(root, "commit", "-q", "-m", "init") + yield root + + +def _write_feature(root: Path) -> Path: + fd = root / FEATURE + fd.mkdir(parents=True) + (fd / "PLAN.md").write_text( + "---\nfeature_id: FEAT-X-0001\nbranch: feat/FEAT-X-0001-demo\nbase: main\n---\n" + ) + return fd + + +def _branch_exists(root: Path, name: str) -> bool: + return subprocess.run( + ["git", "-C", str(root), "rev-parse", "--verify", "-q", name], + capture_output=True, check=False, + ).returncode == 0 + + +class TestFeatureMissingOnBase(unittest.TestCase): + def test_refuses_before_switching_when_base_lacks_the_committed_feature(self): + with _repo() as root: + _git(root, "checkout", "-q", "-b", "work") + fd = _write_feature(root) + _git(root, "add", ".") + _git(root, "commit", "-q", "-m", "draft feature on work") + + with _chdir(root): + with self.assertRaises(loop.FeatureBranchError) as ctx: + loop.ensure_feature_branch(dict(FM), fd) + + msg = str(ctx.exception) + self.assertIn(f"{FEATURE}/PLAN.md", msg) + self.assertIn("'main'", msg) + self.assertIn("'work'", msg) + self.assertEqual(_git(root, "branch", "--show-current"), "work") + self.assertFalse(_branch_exists(root, FM["branch"])) + self.assertTrue((fd / "PLAN.md").is_file()) + + def test_base_that_holds_the_feature_still_creates_the_branch(self): + with _repo() as root: + fd = _write_feature(root) + _git(root, "add", ".") + _git(root, "commit", "-q", "-m", "feature on main") + + with _chdir(root): + loop.ensure_feature_branch(dict(FM), fd) + + self.assertEqual(_git(root, "branch", "--show-current"), FM["branch"]) + self.assertTrue((fd / "PLAN.md").is_file()) + + def test_untracked_feature_folder_still_rides_onto_the_new_branch(self): + # The draft-feature / --prepare path: the folder is not committed + # anywhere yet, so `checkout -B` carries it along untouched. + with _repo() as root: + fd = _write_feature(root) + + with _chdir(root): + loop.ensure_feature_branch(dict(FM), fd) + + self.assertEqual(_git(root, "branch", "--show-current"), FM["branch"]) + self.assertTrue((fd / "PLAN.md").is_file()) + + +if __name__ == "__main__": + unittest.main()