From f5aa3df52792ab6ceb7b0175e058cf7f87b7bf22 Mon Sep 17 00:00:00 2001 From: Carlos Bacelar Date: Tue, 10 Nov 2026 10:17:51 -0300 Subject: [PATCH 1/3] feat(profile-dev-kit): implement workflow turns a spec into a branch and commits (Story 7.4) Adds the implement-story entry workflow, prepare/settle tools, unit contract and Git helper; records one Stage outcome per run. --- kits/profile-dev-kit/README.md | 31 +- kits/profile-dev-kit/kit.yaml | 15 + .../python/beddel_profile_dev/_io.py | 17 +- .../python/beddel_profile_dev/implement.py | 141 ++++ .../beddel_profile_dev/tools/implement.py | 768 ++++++++++++++++++ kits/profile-dev-kit/tests/test_implement.py | 369 +++++++++ .../tests/test_implement_workflow.py | 261 ++++++ kits/profile-dev-kit/tests/test_manifest.py | 3 + kits/profile-dev-kit/tests/test_workflow.py | 2 +- .../workflows/implement-story.yaml | 103 +++ .../profile-dev-kit/workflows/plan-story.yaml | 4 +- 11 files changed, 1710 insertions(+), 4 deletions(-) create mode 100644 kits/profile-dev-kit/python/beddel_profile_dev/implement.py create mode 100644 kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py create mode 100644 kits/profile-dev-kit/tests/test_implement.py create mode 100644 kits/profile-dev-kit/tests/test_implement_workflow.py create mode 100644 kits/profile-dev-kit/workflows/implement-story.yaml diff --git a/kits/profile-dev-kit/README.md b/kits/profile-dev-kit/README.md index 169d281..e71fdf6 100644 --- a/kits/profile-dev-kit/README.md +++ b/kits/profile-dev-kit/README.md @@ -439,7 +439,8 @@ A complete spec is UTF-8, at most 262144 bytes, has YAML front matter with `story_key`, non-empty `requirements`, non-empty `repositories`, `dependencies` and `size_cap_bytes` from 1 through 64000, and has a non-blank body. The `story_key` and the five front-matter fields are the only contract fields read -by the kit; other fields remain available to the authoring process. +by the kit; `units` is also read by the implement stage. Other fields remain +available to the authoring process. Stage outcomes use fixed outcomes (`succeeded`, `refused`, `failed`, `stopped`) and reason codes. Each record is canonical JSON under @@ -454,3 +455,31 @@ Run the workflow from the repository root, for example: ```text beddel run -i ... workflows/plan-story.yaml ``` +## Delivery: implement stage + +The `implement-story` entry workflow accepts `repo_path`, `story_key`, +`spec_path`, `branch` and `base_ref`. It creates or reuses the feature branch, +selects the first unfinished unit, invokes one Coding agent through +`agent-exec`, runs the review checks and Gate commands, and commits only that +unit's declared paths. It never pushes, approves, verifies, integrates, +commits the spec or writes a profile record itself. + +The implement contract adds `units` to a complete plan spec. Each unit has a +unique `id`, one to 64 repository-relative `paths` and a Conventional Commit +`subject`. Commits carry exactly one `Story-Key` and one +`Implementation-Unit` trailer. One unit is committed per run; rerun the +workflow to resume the next unit. A clean baseline Gate is required only for +regression comparison, so a gate already red at baseline is advisory. + +Review failures use fixed reasons including `worktree.dirty`, `scope.exceeded`, +`unit.empty`, `size.exceeded`, `secret.detected`, `gate.regressed`, +`gate.changed_tree`, `agent.failed` and `commit.failed`. Successful runs use +`unit.committed` or `units.complete`. Outcome refs include the spec digest, +branch, base, head, commit, unit, completion counts, diff size, out-of-scope +count and regressed command names. + +Run the workflow from the repository root, for example: + +```text +beddel run -i ... workflows/implement-story.yaml +``` diff --git a/kits/profile-dev-kit/kit.yaml b/kits/profile-dev-kit/kit.yaml index 28d4f82..263ddf3 100644 --- a/kits/profile-dev-kit/kit.yaml +++ b/kits/profile-dev-kit/kit.yaml @@ -109,6 +109,14 @@ tools: target: "beddel_profile_dev.tools.stage_outcome:profile_record_stage_outcome" description: "Append one create-only Stage outcome record outside the repository" category: profile + - name: profile_implement_prepare + target: "beddel_profile_dev.tools.implement:profile_implement_prepare" + description: "Prepare one implementation unit on a feature branch" + category: profile + - name: profile_implement_settle + target: "beddel_profile_dev.tools.implement:profile_implement_settle" + description: "Review and commit one implementation unit" + category: profile workflows: - name: verify-change @@ -135,6 +143,9 @@ workflows: - name: read-approval path: workflows/read-approval.yaml description: Reads the stored Change Approval without writing records. + - name: implement-story + path: workflows/implement-story.yaml + description: Implements one unit of one spec through a Coding agent and commits only its declared paths; never pushes, verifies or integrates. - name: plan-story path: workflows/plan-story.yaml description: Plans one selected story into one implementation spec through a Coding agent; never implements, verifies or commits. @@ -183,6 +194,10 @@ targets: target: "beddel_profile_dev.tools.plan:profile_plan_settle" - name: profile_record_stage_outcome target: "beddel_profile_dev.tools.stage_outcome:profile_record_stage_outcome" + - name: profile_implement_prepare + target: "beddel_profile_dev.tools.implement:profile_implement_prepare" + - name: profile_implement_settle + target: "beddel_profile_dev.tools.implement:profile_implement_settle" typescript: status: unavailable unavailable_reason: > diff --git a/kits/profile-dev-kit/python/beddel_profile_dev/_io.py b/kits/profile-dev-kit/python/beddel_profile_dev/_io.py index 495cbeb..54c3d8d 100644 --- a/kits/profile-dev-kit/python/beddel_profile_dev/_io.py +++ b/kits/profile-dev-kit/python/beddel_profile_dev/_io.py @@ -27,6 +27,7 @@ "confined", "diff_text", "footprint", + "git_run", "in_head_history", "in_index", "is_ancestor", @@ -74,6 +75,8 @@ def _repo_error() -> ProfileError: def _git( repo: Path, *args: str, + index_file: Path | None = None, + timeout: float = _GIT_TIMEOUT_SECONDS, ) -> subprocess.CompletedProcess[bytes] | None: git = shutil.which("git") if git is None: @@ -81,6 +84,8 @@ def _git( env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} env["GIT_NO_LAZY_FETCH"] = "1" # no network, even in a partial clone env["GIT_ATTR_NOSYSTEM"] = "1" # the system attributes file never applies + if index_file is not None: + env["GIT_INDEX_FILE"] = str(index_file) try: return subprocess.run( [ @@ -94,13 +99,23 @@ def _git( capture_output=True, stdin=subprocess.DEVNULL, env=env, - timeout=_GIT_TIMEOUT_SECONDS, + timeout=timeout, check=False, ) except (OSError, ValueError, subprocess.SubprocessError): return None +def git_run( + repo: Path, + *args: str, + index_file: Path | None = None, + timeout: float = _GIT_TIMEOUT_SECONDS, +) -> subprocess.CompletedProcess[bytes] | None: + """Run Git with the kit's isolated environment and optional index.""" + return _git(repo, *args, index_file=index_file, timeout=timeout) + + def _blob_by_oid(repo: Path, oid: str) -> bytes: """Return the raw blob bytes for ``oid`` via ``cat-file blob``. diff --git a/kits/profile-dev-kit/python/beddel_profile_dev/implement.py b/kits/profile-dev-kit/python/beddel_profile_dev/implement.py new file mode 100644 index 0000000..3daf1c6 --- /dev/null +++ b/kits/profile-dev-kit/python/beddel_profile_dev/implement.py @@ -0,0 +1,141 @@ +"""Pure contracts for the profile implement stage.""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from dataclasses import dataclass + +from beddel_profile_dev.plan import ( + MAX_SPEC_BYTES, + front_matter, + relative_path, + spec_complete, +) + +__all__ = [ + "MAX_UNITS", + "MAX_UNIT_PATHS", + "PROTECTED_BRANCHES", + "STORY_TRAILER", + "SUBJECT", + "UNIT_ID", + "UNIT_TRAILER", + "Unit", + "branch_reason", + "commit_message", + "covered", + "spec_units", + "trailer_unit", +] + +UNIT_ID = re.compile(r"[a-z0-9][a-z0-9-]{0,31}") +MAX_UNITS = 32 +MAX_UNIT_PATHS = 64 +SUBJECT = re.compile( + r"(?:build|chore|docs|feat|fix|perf|refactor|test)" + r"(?:\([a-z0-9._-]{1,64}\))?: [^\x00-\x1f\x7f]{1,100}" +) +PROTECTED_BRANCHES = ("main", "master", "mainline") +STORY_TRAILER = "Story-Key" +UNIT_TRAILER = "Implementation-Unit" +_BRANCH = re.compile(r"[a-z0-9][a-z0-9._/-]{0,127}") + + +@dataclass(frozen=True) +class Unit: + """One ordered implementation unit from a complete plan spec.""" + + id: str + paths: tuple[str, ...] + subject: str + + +def _valid_unit(value: object) -> Unit | None: + if not isinstance(value, Mapping) or set(value) != {"id", "paths", "subject"}: + return None + unit_id = value["id"] + paths = value["paths"] + subject = value["subject"] + if not isinstance(unit_id, str) or UNIT_ID.fullmatch(unit_id) is None: + return None + if ( + not isinstance(paths, list) + or not 1 <= len(paths) <= MAX_UNIT_PATHS + or len(set(paths)) != len(paths) + or not all( + isinstance(path, str) and len(path) <= 512 and relative_path(path) + for path in paths + ) + ): + return None + if not isinstance(subject, str) or SUBJECT.fullmatch(subject) is None: + return None + return Unit(unit_id, tuple(paths), subject) + + +def spec_units(data: bytes, story_key: str) -> tuple[Unit, ...] | None: + """Return validated implementation units, or ``None`` for an incomplete spec.""" + if len(data) > MAX_SPEC_BYTES or not spec_complete(data, story_key): + return None + metadata = front_matter(data) + if metadata is None: + return None + values = metadata.get("units") + if not isinstance(values, list) or not 1 <= len(values) <= MAX_UNITS: + return None + units: list[Unit] = [] + seen: set[str] = set() + for value in values: + unit = _valid_unit(value) + if unit is None or unit.id in seen: + return None + seen.add(unit.id) + units.append(unit) + return tuple(units) + + +def branch_reason(branch: object, base_ref: object) -> str | None: + """Return the refusal reason for a branch/base pair, if any.""" + if not isinstance(branch, str) or _BRANCH.fullmatch(branch) is None: + return "branch.invalid" + if ( + branch in PROTECTED_BRANCHES + or branch == base_ref + or branch.startswith("-") + or branch.endswith(("/", ".")) + or ".." in branch + or "//" in branch + ): + return ( + "branch.protected" + if branch in PROTECTED_BRANCHES or branch == base_ref + else "branch.invalid" + ) + return None + + +def covered(paths: tuple[str, ...] | list[str], path: str) -> bool: + """Return whether a changed path belongs to a unit's file or directory paths.""" + return any(path == item or path.startswith(item + "/") for item in paths) + + +def commit_message(unit: Unit, story_key: str) -> tuple[str, str]: + """Return the subject and trailer paragraph for a unit commit.""" + return unit.subject, f"{STORY_TRAILER}: {story_key}\n{UNIT_TRAILER}: {unit.id}" + + +def trailer_unit(message: str, story_key: str) -> str | None: + """Return a unit id when a commit message has exactly the required trailers.""" + if not isinstance(message, str): + return None + story_lines = [ + line for line in message.splitlines() if line == f"{STORY_TRAILER}: {story_key}" + ] + unit_lines = [ + line for line in message.splitlines() if line.startswith(f"{UNIT_TRAILER}: ") + ] + if len(story_lines) != 1 or len(unit_lines) != 1: + return None + unit_id = unit_lines[0][len(f"{UNIT_TRAILER}: ") :] + return unit_id if UNIT_ID.fullmatch(unit_id) is not None else None diff --git a/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py b/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py new file mode 100644 index 0000000..e6281ce --- /dev/null +++ b/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py @@ -0,0 +1,768 @@ +"""Prepare and settle one implementation unit on a feature branch.""" + +from __future__ import annotations + +import hashlib +import os +import tempfile +import time +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from beddel.tools import beddel_tool + +from beddel_profile_dev._errors import ProfileError +from beddel_profile_dev._io import ( + changed_paths, + confined, + diff_text, + git_run, + real_repo_root, + resolve_revision, +) +from beddel_profile_dev.config import KitConfig, load_config +from beddel_profile_dev.implement import ( + branch_reason, + commit_message, + covered, + spec_units, + trailer_unit, +) +from beddel_profile_dev.plan import ( + STORY_KEY, + front_matter, + relative_path, + spec_complete, +) +from beddel_profile_dev.tools._subprocess import resolve_executable, run_command +from beddel_profile_dev.tools.stage_outcome import _TOKEN + +__all__ = ["profile_implement_prepare", "profile_implement_settle"] + +_MAX_BASE_REF = 200 +_FULL_SHA_LENGTH = 40 + + +def _valid_story(value: object) -> bool: + return isinstance(value, str) and STORY_KEY.fullmatch(value) is not None + + +def _valid_base(value: object) -> bool: + return ( + isinstance(value, str) + and 0 < len(value) <= _MAX_BASE_REF + and not value.startswith("-") + and not any(ord(char) < 32 or ord(char) == 127 for char in value) + ) + + +def _refs( + *, + spec_path: str | None = None, + spec_sha256: str | None = None, + branch: str | None = None, + base: str | None = None, + head: str | None = None, + commit: str | None = None, + unit: str | None = None, + completed: int = 0, + remaining: int = 0, + diff_bytes: int | None = None, + out_of_scope: int = 0, + regressed: str | None = None, +) -> dict[str, Any]: + return { + "spec_path": spec_path, + "spec_sha256": spec_sha256, + "branch": branch, + "base": base, + "head": head, + "commit": commit, + "unit": unit, + "completed": completed, + "remaining": remaining, + "diff_bytes": diff_bytes, + "out_of_scope": out_of_scope, + "regressed": regressed, + } + + +def _result( + story_key: str | None, + outcome: str | None, + reason: str | None, + refs: dict[str, Any], + *, + ready: bool = False, + implement: bool = False, + spec_sha256: str | None = None, + base: str | None = None, + head: str | None = None, + unit_id: str | None = None, + unit_paths: str = "", + baseline: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + return { + "stage": "implement", + "story_key": story_key, + "ready": ready, + "implement": implement, + "outcome": outcome, + "reason": reason, + "refs": refs, + "spec_sha256": spec_sha256, + "base": base, + "head": head, + "unit_id": unit_id, + "unit_paths": unit_paths, + "baseline": baseline, + } + + +def _refusal( + story_key: str | None, + reason: str, + *, + spec_path: str | None = None, + branch: str | None = None, +) -> dict[str, Any]: + return _result( + story_key, + "refused", + reason, + _refs(spec_path=spec_path, branch=branch), + ) + + +def _failure( + story_key: str | None, + reason: str, + refs: dict[str, Any], + **kwargs: Any, +) -> dict[str, Any]: + return _result(story_key, "failed", reason, refs, **kwargs) + + +def _read_spec(repo: Path, spec_path: str) -> tuple[bytes | None, str | None]: + try: + path = confined(repo, spec_path) + if not path.exists(): + return None, "spec.absent" + if not path.is_file(): + return None, "spec.unreadable" + return path.read_bytes(), None + except (OSError, ProfileError, RuntimeError, ValueError): + return None, "spec.unreadable" + + +def _git_text(result: Any) -> str | None: + if result is None or result.returncode != 0: + return None + return result.stdout.decode("utf-8", "replace").strip() + + +def _symbolic_branch(repo: Path) -> str | None: + value = _git_text(git_run(repo, "symbolic-ref", "-q", "HEAD")) + return value.removeprefix("refs/heads/") if value is not None else None + + +def _completed(repo: Path, base: str, story_key: str) -> set[str]: + result = git_run(repo, "log", "-z", "--reverse", "--format=%H%n%B", f"{base}..HEAD") + if result is None or result.returncode != 0: + raise ProfileError( + "PROFILE_REPOSITORY_INVALID", "repository or revision invalid" + ) + completed: set[str] = set() + for raw in result.stdout.split(b"\x00"): + if not raw: + continue + message = raw.decode("utf-8", "replace") + unit_id = trailer_unit(message, story_key) + if unit_id is not None: + completed.add(unit_id) + return completed + + +def _run_gates(repo: Path, config: KitConfig) -> list[dict[str, Any]]: + started_at = time.monotonic() + results: list[dict[str, Any]] = [] + for index, argv in enumerate(config.gate_commands, start=1): + remaining = ( + None + if config.gate_total_timeout_seconds is None + else config.gate_total_timeout_seconds - (time.monotonic() - started_at) + ) + timed_out = remaining is not None and remaining <= 0 + if timed_out: + exit_code = None + else: + timeout = ( + config.gate_timeout_seconds + if remaining is None + else min(config.gate_timeout_seconds, max(remaining, 0.0)) + ) + command = run_command(argv, repo, timeout) + if not command.started: + raise ProfileError( + "PROFILE_GATE_COMMAND_INVALID", + "gate command executable is not available", + ) + exit_code = command.exit_code + timed_out = command.timed_out + results.append( + { + "name": f"{index:02d}-{argv[0]}", + "exit_code": exit_code, + "timed_out": timed_out, + } + ) + return results + + +def _candidate_tree(repo: Path, paths: tuple[str, ...]) -> str: + with tempfile.TemporaryDirectory() as directory: + index = Path(directory) / "index" + for args in (("read-tree", "HEAD"), ("add", "-A", "--", *paths)): + result = git_run(repo, *args, index_file=index) + if result is None or result.returncode != 0: + raise ProfileError( + "PROFILE_REPOSITORY_INVALID", "repository or revision invalid" + ) + result = git_run(repo, "write-tree", index_file=index) + value = _git_text(result) + if value is None: + raise ProfileError( + "PROFILE_REPOSITORY_INVALID", "repository or revision invalid" + ) + return value + + +def _validate_inputs( + repo_path: str, + story_key: object, + spec_path: object, + branch: object, + base_ref: object, +) -> tuple[Path, str, str, str, str] | dict[str, Any]: + valid_story: str | None = None + if isinstance(story_key, str) and _valid_story(story_key): + valid_story = story_key + valid_spec: str | None = None + if ( + isinstance(spec_path, str) + and len(spec_path) <= 512 + and relative_path(spec_path) + ): + valid_spec = spec_path + valid_branch: str | None = None + if isinstance(branch, str) and len(branch) <= 128: + valid_branch = branch + if valid_story is None: + return _refusal( + None, "story_key.invalid", spec_path=valid_spec, branch=valid_branch + ) + if ( + valid_spec is None + or not isinstance(branch, str) + or branch_reason(branch, base_ref) == "branch.invalid" + ): + return _refusal( + valid_story, + "path.invalid" if valid_spec is None else "branch.invalid", + spec_path=valid_spec, + branch=valid_branch, + ) + branch_error = branch_reason(branch, base_ref) + if branch_error is not None: + return _refusal(valid_story, branch_error, spec_path=valid_spec, branch=branch) + if not _valid_base(base_ref): + return _refusal( + valid_story, "base.invalid", spec_path=valid_spec, branch=branch + ) + repo = real_repo_root(repo_path) + assert isinstance(base_ref, str) + return repo, valid_story, valid_spec, branch, base_ref + + +@beddel_tool( + name="profile_implement_prepare", + description="Prepare one implementation unit on a feature branch", + category="profile", +) +def profile_implement_prepare( + repo_path: str, + story_key: str, + spec_path: str, + branch: str, + base_ref: str, +) -> dict[str, Any]: + """Validate state, create or reuse the branch, and run baseline gates.""" + checked = _validate_inputs(repo_path, story_key, spec_path, branch, base_ref) + if isinstance(checked, dict): + return checked + repo, story, spec, branch_name, base = checked + try: + base_sha = resolve_revision(repo, base) + except ProfileError: + return _refusal(story, "base.invalid", spec_path=spec, branch=branch_name) + if Path(os.path.realpath(os.getcwd())) != repo: + return _refusal(story, "cwd.mismatch", spec_path=spec, branch=branch_name) + data, error = _read_spec(repo, spec) + if error == "spec.absent": + return _refusal(story, error, spec_path=spec, branch=branch_name) + if error is not None or data is None: + return _refusal( + story, error or "spec.unreadable", spec_path=spec, branch=branch_name + ) + if not spec_complete(data, story): + return _refusal(story, "spec.incomplete", spec_path=spec, branch=branch_name) + units = spec_units(data, story) + if units is None: + return _refusal(story, "units.invalid", spec_path=spec, branch=branch_name) + try: + config = load_config() + for argv in config.gate_commands: + if resolve_executable(argv[0]) is None: + return _refusal( + story, "gate.unavailable", spec_path=spec, branch=branch_name + ) + except ProfileError: + return _failure( + story, "prepare.failed", _refs(spec_path=spec, branch=branch_name) + ) + dirty = changed_paths(repo) - {spec} + if dirty: + return _failure( + story, "worktree.dirty", _refs(spec_path=spec, branch=branch_name) + ) + + ref = git_run(repo, "show-ref", "--verify", "--quiet", f"refs/heads/{branch_name}") + if ref is None or ref.returncode not in (0, 1): + raise ProfileError( + "PROFILE_REPOSITORY_INVALID", "repository or revision invalid" + ) + if ref.returncode == 0: + tip = resolve_revision(repo, f"refs/heads/{branch_name}") + merge = git_run(repo, "merge-base", base_sha, tip) + merge_sha = _git_text(merge) + if merge_sha is None: + return _refusal(story, "base.invalid", spec_path=spec, branch=branch_name) + base_sha = merge_sha + if _symbolic_branch(repo) != branch_name: + switched = git_run(repo, "switch", "-q", branch_name) + if switched is None or switched.returncode != 0: + return _failure( + story, "checkout.failed", _refs(spec_path=spec, branch=branch_name) + ) + else: + switched = git_run(repo, "switch", "-q", "-c", branch_name, base_sha) + if switched is None or switched.returncode != 0: + return _failure( + story, + "checkout.failed", + _refs(spec_path=spec, branch=branch_name, base=base_sha), + ) + + after_data, after_error = _read_spec(repo, spec) + if after_error is not None or after_data != data or (changed_paths(repo) - {spec}): + return _failure( + story, + "checkout.failed", + _refs( + spec_path=spec, + spec_sha256=hashlib.sha256(after_data).hexdigest() + if after_data is not None + else None, + branch=branch_name, + base=base_sha, + head=resolve_revision(repo, "HEAD"), + ), + ) + head = resolve_revision(repo, "HEAD") + completed = _completed(repo, base_sha, story) + remaining = [unit for unit in units if unit.id not in completed] + if not remaining: + return _result( + story, + "succeeded", + "units.complete", + _refs( + spec_path=spec, + spec_sha256=hashlib.sha256(data).hexdigest(), + branch=branch_name, + base=base_sha, + head=head, + completed=len(units), + remaining=0, + ), + spec_sha256=hashlib.sha256(data).hexdigest(), + base=base_sha, + head=head, + ) + unit = remaining[0] + try: + baseline = _run_gates(repo, config) + except ProfileError: + return _failure( + story, + "prepare.failed", + _refs( + spec_path=spec, + spec_sha256=hashlib.sha256(data).hexdigest(), + branch=branch_name, + base=base_sha, + head=head, + unit=unit.id, + ), + ) + if changed_paths(repo) - {spec}: + return _failure( + story, + "gate.changed_tree", + _refs( + spec_path=spec, + spec_sha256=hashlib.sha256(data).hexdigest(), + branch=branch_name, + base=base_sha, + head=head, + unit=unit.id, + ), + ) + return _result( + story, + None, + None, + _refs( + spec_path=spec, + spec_sha256=hashlib.sha256(data).hexdigest(), + branch=branch_name, + base=base_sha, + head=head, + unit=unit.id, + completed=len(completed), + remaining=len(remaining), + ), + ready=True, + implement=True, + spec_sha256=hashlib.sha256(data).hexdigest(), + base=base_sha, + head=head, + unit_id=unit.id, + unit_paths=", ".join(unit.paths), + baseline=baseline, + ) + + +@beddel_tool( + name="profile_implement_settle", + description="Review and commit one implementation unit", + category="profile", +) +def profile_implement_settle( + repo_path: str, + story_key: str, + spec_path: str, + branch: str, + base_ref: str, + prepare: Mapping[str, Any] | None, + agent: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Settle the prepared unit, committing only its declared paths.""" + checked = _validate_inputs(repo_path, story_key, spec_path, branch, base_ref) + if isinstance(checked, dict): + return checked + repo, story, spec, branch_name, _base_ref = checked + if not isinstance(prepare, Mapping): + return _failure( + story, "prepare.mismatch", _refs(spec_path=spec, branch=branch_name) + ) + if prepare.get("story_key") != story or prepare.get("stage") != "implement": + return _failure( + story, "prepare.mismatch", _refs(spec_path=spec, branch=branch_name) + ) + if prepare.get("implement") is not True: + return _result( + story, + prepare.get("outcome"), + prepare.get("reason"), + prepare.get("refs", _refs(spec_path=spec, branch=branch_name)), + ) + if not isinstance(agent, Mapping): + return _failure( + story, "agent.failed", _refs(spec_path=spec, branch=branch_name) + ) + data, error = _read_spec(repo, spec) + if error is not None or data is None: + return _failure( + story, "spec.changed", _refs(spec_path=spec, branch=branch_name) + ) + units = spec_units(data, story) + if units is None: + return _failure( + story, "spec.changed", _refs(spec_path=spec, branch=branch_name) + ) + spec_digest = hashlib.sha256(data).hexdigest() + if prepare.get("spec_sha256") != spec_digest: + return _failure( + story, + "spec.changed", + _refs(spec_path=spec, spec_sha256=spec_digest, branch=branch_name), + ) + unit_id = prepare.get("unit_id") + unit = next((item for item in units if item.id == unit_id), None) + if unit is None or prepare.get("unit_paths") != ", ".join(unit.paths): + return _failure( + story, + "prepare.mismatch", + _refs(spec_path=spec, spec_sha256=spec_digest, branch=branch_name), + ) + try: + config = load_config() + for argv in config.gate_commands: + if resolve_executable(argv[0]) is None: + return _failure( + story, + "gate.unavailable", + _refs(spec_path=spec, spec_sha256=spec_digest, branch=branch_name), + ) + base = prepare.get("base") + head = resolve_revision(repo, "HEAD") + if _symbolic_branch(repo) != branch_name: + return _failure( + story, + "branch.moved", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base if isinstance(base, str) else None, + head=head, + unit=unit.id, + ), + ) + if head != prepare.get("head"): + return _failure( + story, + "head.moved", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base if isinstance(base, str) else None, + head=head, + unit=unit.id, + ), + ) + if not isinstance(base, str): + return _failure( + story, + "prepare.mismatch", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + head=head, + unit=unit.id, + ), + ) + current = changed_paths(repo) - {spec} + if not current: + return _failure( + story, + "unit.empty", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=head, + unit=unit.id, + ), + ) + out_of_scope = sum(not covered(unit.paths, path) for path in current) + if out_of_scope: + return _failure( + story, + "scope.exceeded", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=head, + unit=unit.id, + out_of_scope=out_of_scope, + ), + unit_id=unit.id, + unit_paths=", ".join(unit.paths), + ) + candidate = _candidate_tree(repo, unit.paths) + cap = front_matter(data) + assert cap is not None + diff, truncated = diff_text( + repo, base, candidate, int(cap["size_cap_bytes"]) + 1 + ) + diff_bytes = len(diff.encode("utf-8")) + if truncated: + return _failure( + story, + "size.exceeded", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=head, + unit=unit.id, + diff_bytes=diff_bytes, + ), + ) + if ( + _TOKEN.search( + "\n".join(line for line in diff.splitlines() if line.startswith("+")) + ) + is not None + ): + return _failure( + story, + "secret.detected", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=head, + unit=unit.id, + diff_bytes=diff_bytes, + ), + ) + before_gates = set(current) + gates = _run_gates(repo, config) + if changed_paths(repo) - {spec} != before_gates: + return _failure( + story, + "gate.changed_tree", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=head, + unit=unit.id, + diff_bytes=diff_bytes, + ), + ) + regressed = [ + entry["name"] + for entry, baseline in zip(gates, prepare.get("baseline") or []) + if ( + baseline.get("exit_code") == 0 + and (entry["timed_out"] or entry["exit_code"] != 0) + ) + ] + if regressed: + return _failure( + story, + "gate.regressed", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=head, + unit=unit.id, + diff_bytes=diff_bytes, + regressed=", ".join(regressed), + ), + ) + subject, trailers = commit_message(unit, story) + committed = git_run(repo, "add", "-A", "--", *unit.paths) + if committed is None or committed.returncode != 0: + return _failure( + story, + "commit.failed", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=head, + unit=unit.id, + diff_bytes=diff_bytes, + ), + ) + committed = git_run( + repo, + "commit", + "-q", + "-m", + subject, + "-m", + trailers, + "--only", + "--", + *unit.paths, + timeout=120, + ) + if committed is None or committed.returncode != 0: + return _failure( + story, + "commit.failed", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=head, + unit=unit.id, + diff_bytes=diff_bytes, + ), + ) + new_head = resolve_revision(repo, "HEAD") + parent = _git_text(git_run(repo, "rev-parse", "HEAD^")) + tree = _git_text(git_run(repo, "rev-parse", "HEAD^{tree}")) + if parent != head or tree != candidate: + return _failure( + story, + "commit.changed", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=new_head, + commit=new_head, + unit=unit.id, + diff_bytes=diff_bytes, + ), + ) + completed = _completed(repo, base, story) + return _result( + story, + "succeeded", + "unit.committed", + _refs( + spec_path=spec, + spec_sha256=spec_digest, + branch=branch_name, + base=base, + head=new_head, + commit=new_head, + unit=unit.id, + completed=len(completed), + remaining=len(units) - len(completed), + diff_bytes=diff_bytes, + ), + spec_sha256=spec_digest, + base=base, + head=new_head, + unit_id=unit.id, + unit_paths=", ".join(unit.paths), + ) + except ProfileError: + return _failure( + story, + "settle.failed", + _refs(spec_path=spec, spec_sha256=spec_digest, branch=branch_name), + ) diff --git a/kits/profile-dev-kit/tests/test_implement.py b/kits/profile-dev-kit/tests/test_implement.py new file mode 100644 index 0000000..47668a9 --- /dev/null +++ b/kits/profile-dev-kit/tests/test_implement.py @@ -0,0 +1,369 @@ +"""Contract and I/O matrix coverage for the implement stage.""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest +from beddel_profile_dev.implement import ( + Unit, + branch_reason, + commit_message, + covered, + spec_units, + trailer_unit, +) +from beddel_profile_dev.tools import implement as implement_tools +from beddel_profile_dev.tools.implement import ( + profile_implement_prepare, + profile_implement_settle, +) + +from ._helpers import commit_all, git, init_repo, stub_gate_tools + +STORY = "7-4-implement-workflow-turns-a-spec-into-a-branch-and-commits" +SPEC_PATH = "specs/story.md" +BRANCH = "feat/story-7-4" + + +def spec_bytes( + units: list[dict[str, object]] | None = None, *, cap: int = 64000 +) -> bytes: + values = units or [ + {"id": "u1", "paths": ["src/one.py"], "subject": "feat(core): add one"}, + {"id": "u2", "paths": ["src/two.py"], "subject": "feat(core): add two"}, + ] + return ( + ( + f"---\nstory_key: {STORY}\nrequirements: [FR-10]\n" + "repositories: [.]\ndependencies: []\n" + f"size_cap_bytes: {cap}\nunits: {values!r}\n---\n\n# Spec\n" + ) + .replace("'", '"') + .encode() + ) + + +def _repo(tmp_path: Path) -> tuple[Path, str]: + repo = init_repo(tmp_path / "repo") + git(repo, "config", "user.name", "Fixture") + git(repo, "config", "user.email", "fixture@example.invalid") + (repo / "src").mkdir() + (repo / "src" / "base.py").write_text("base = True\n") + (repo / SPEC_PATH).parent.mkdir() + (repo / SPEC_PATH).write_bytes(spec_bytes()) + base = commit_all(repo, "base") + (repo / SPEC_PATH).write_bytes(spec_bytes()) + return repo, base + + +def _prepare( + repo: Path, base: str, monkeypatch: pytest.MonkeyPatch +) -> dict[str, object]: + monkeypatch.chdir(repo) + monkeypatch.setenv("PATH", stub_gate_tools(repo.parent)) + monkeypatch.setenv("HOME", str(repo.parent / "home")) + return profile_implement_prepare(str(repo), STORY, SPEC_PATH, BRANCH, base) + + +def test_pure_unit_contract() -> None: + units = spec_units(spec_bytes(), STORY) + assert units == ( + Unit("u1", ("src/one.py",), "feat(core): add one"), + Unit("u2", ("src/two.py",), "feat(core): add two"), + ) + assert ( + spec_units( + spec_bytes([{"id": "bad id", "paths": ["x"], "subject": "feat: x"}]), STORY + ) + is None + ) + assert branch_reason("main", "origin/main") == "branch.protected" + assert branch_reason("feat/x", "feat/x") == "branch.protected" + assert branch_reason("../bad", "main") == "branch.invalid" + assert branch_reason("feat/x", "main") is None + assert covered(("src",), "src/a.py") + assert covered(("src/a.py",), "src/a.py") + assert not covered(("src/a.py",), "src/ab.py") + subject, trailers = commit_message(Unit("u1", ("x",), "feat: x"), STORY) + assert subject == "feat: x" + assert trailer_unit(f"{subject}\n\n{trailers}\n", STORY) == "u1" + assert trailer_unit(f"{trailers}\n{trailers}\n", STORY) is None + + +def test_first_resume_complete_and_failure_paths( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + prepared = _prepare(repo, base, monkeypatch) + assert prepared["implement"] is True + (repo / "src" / "one.py").write_text("one = 1\n") + first = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} + ) + assert first["reason"] == "unit.committed" + first_head = git(repo, "rev-parse", "HEAD") + + prepared2 = _prepare(repo, base, monkeypatch) + assert prepared2["unit_id"] == "u2" + (repo / "src" / "two.py").write_text("two = 2\n") + second = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared2, agent={} + ) + assert second["reason"] == "unit.committed" + assert second["refs"]["completed"] == 2 + + prepared3 = _prepare(repo, base, monkeypatch) + assert prepared3["reason"] == "units.complete" + assert git(repo, "rev-parse", "HEAD") == second["refs"]["head"] + complete = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared3 + ) + assert complete["reason"] == "units.complete" + assert git(repo, "rev-parse", "HEAD") == second["refs"]["head"] + assert first_head != second["refs"]["head"] + + +def test_refusal_dirty_agent_scope_empty_and_branch_tip_unchanged( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + monkeypatch.chdir(repo) + monkeypatch.setenv("PATH", stub_gate_tools(repo.parent)) + monkeypatch.setenv("HOME", str(repo.parent / "home")) + (repo / "unexpected.txt").write_text("dirty\n") + before = git(repo, "rev-parse", "HEAD") + dirty = profile_implement_prepare(str(repo), STORY, SPEC_PATH, BRANCH, base) + assert dirty["reason"] == "worktree.dirty" + assert git(repo, "rev-parse", "HEAD") == before + (repo / "unexpected.txt").unlink() + prepared = _prepare(repo, base, monkeypatch) + assert ( + profile_implement_settle(str(repo), STORY, SPEC_PATH, BRANCH, base, prepared)[ + "reason" + ] + == "agent.failed" + ) + empty = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} + ) + assert empty["reason"] == "unit.empty" + (repo / "outside.py").write_text("outside\n") + out = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} + ) + assert out["reason"] == "scope.exceeded" + assert git(repo, "rev-parse", "HEAD") == before + + +def test_gate_regression_token_and_size_overflow_leave_tip_unchanged( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + prepared = _prepare(repo, base, monkeypatch) + (repo / "src" / "one.py").write_text("one = 1\n") + monkeypatch.setenv("STUB_EXIT_PYTEST", "1") + regressed = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} + ) + assert regressed["reason"] == "gate.regressed" + monkeypatch.delenv("STUB_EXIT_PYTEST") + + repo2, base2 = _repo(tmp_path / "token") + prepared2 = _prepare(repo2, base2, monkeypatch) + token_value = "gh" + "p_" + "A" * 36 + token_before = git(repo2, "rev-parse", "HEAD") + (repo2 / "src" / "one.py").write_text(f"token = '{token_value}'\n") + token = profile_implement_settle( + str(repo2), STORY, SPEC_PATH, BRANCH, base2, prepared2, agent={} + ) + assert token["reason"] == "secret.detected" + assert token_value not in repr(token) + assert git(repo2, "rev-parse", "HEAD") == token_before + + repo3, base3 = _repo(tmp_path / "size") + (repo3 / SPEC_PATH).write_bytes(spec_bytes(cap=10)) + prepared3 = _prepare(repo3, base3, monkeypatch) + (repo3 / "src" / "one.py").write_text("x = " + "a" * 100 + "\n") + size = profile_implement_settle( + str(repo3), STORY, SPEC_PATH, BRANCH, base3, prepared3, agent={} + ) + assert size["reason"] == "size.exceeded" + + +def test_gate_changed_tree_stops_without_commit( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + prepared = _prepare(repo, base, monkeypatch) + gate_bin = Path(os.environ["PATH"].split(os.pathsep)[0]) + (gate_bin / "ruff").write_text( + "#!/usr/bin/env python3\n" + "from pathlib import Path\n" + "Path('gate-output.txt').write_text('changed')\n" + ) + (gate_bin / "ruff").chmod(0o755) + (repo / "src" / "one.py").write_text("one = 1\n") + result = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} + ) + assert result["reason"] == "gate.changed_tree" + assert git(repo, "rev-parse", "HEAD") == base + + +@pytest.mark.parametrize( + ("case", "reason"), + [ + ("story", "story_key.invalid"), + ("path", "path.invalid"), + ("branch", "branch.invalid"), + ("protected", "branch.protected"), + ("base", "base.invalid"), + ("cwd", "cwd.mismatch"), + ("absent", "spec.absent"), + ("unreadable", "spec.unreadable"), + ("incomplete", "spec.incomplete"), + ("units", "units.invalid"), + ("gate", "gate.unavailable"), + ], +) +def test_prepare_refusals_keep_branch_tip( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + case: str, + reason: str, +) -> None: + repo, base = _repo(tmp_path / case) + monkeypatch.chdir(repo) + monkeypatch.setenv("PATH", stub_gate_tools(tmp_path / case)) + monkeypatch.setenv("HOME", str(tmp_path / case / "home")) + before = git(repo, "rev-parse", "HEAD") + story, spec, branch, base_ref = STORY, SPEC_PATH, BRANCH, base + if case == "story": + story = "BAD KEY" + elif case == "path": + spec = "../outside.md" + elif case == "branch": + branch = "Bad Branch" + elif case == "protected": + branch = "main" + elif case == "base": + base_ref = "missing-base" + elif case == "cwd": + (tmp_path / case / "elsewhere").mkdir() + monkeypatch.chdir(tmp_path / case / "elsewhere") + elif case == "absent": + (repo / spec).unlink() + elif case == "unreadable": + (repo / spec).unlink() + (repo / spec).mkdir() + elif case == "incomplete": + (repo / spec).write_bytes(b"unfinished") + elif case == "units": + (repo / spec).write_bytes( + spec_bytes( + [{"id": "bad id", "paths": ["src/one.py"], "subject": "feat: bad"}] + ) + ) + else: + original = implement_tools.resolve_executable + monkeypatch.setattr( + implement_tools, + "resolve_executable", + lambda name: None if name == "ruff" else original(name), + ) + result = profile_implement_prepare(str(repo), story, spec, branch, base_ref) + assert result["reason"] == reason + assert git(repo, "rev-parse", "HEAD") == before + + +def test_checkout_failure_and_prepare_failure_are_recorded( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + prepared = _prepare(repo, base, monkeypatch) + assert prepared["implement"] is True + monkeypatch.chdir(repo) + original = implement_tools.git_run + + def fail_switch(repo_path: Path, *args: str, **kwargs: object) -> object: + if args[:2] == ("switch", "-q"): + return type("Result", (), {"returncode": 1, "stdout": b""})() + return original(repo_path, *args, **kwargs) + + monkeypatch.setattr(implement_tools, "git_run", fail_switch) + failed = profile_implement_prepare(str(repo), STORY, SPEC_PATH, "feat/other", base) + assert failed["reason"] == "checkout.failed" + monkeypatch.setattr(implement_tools, "git_run", original) + monkeypatch.setattr( + implement_tools, + "load_config", + lambda: (_ for _ in ()).throw(implement_tools.ProfileError("x", "x")), + ) + prepared_failed = profile_implement_prepare( + str(repo), STORY, SPEC_PATH, BRANCH, base + ) + assert prepared_failed["reason"] == "prepare.failed" + assert git(repo, "rev-parse", "HEAD") == base + + +def test_settle_rejects_forged_prepare_and_changed_spec( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + prepared = _prepare(repo, base, monkeypatch) + before = git(repo, "rev-parse", "HEAD") + forged = dict(prepared) + forged["unit_id"] = "u2" + mismatch = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, forged, agent={} + ) + assert mismatch["reason"] == "prepare.mismatch" + (repo / SPEC_PATH).write_bytes(spec_bytes(cap=63999)) + changed = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} + ) + assert changed["reason"] == "spec.changed" + assert git(repo, "rev-parse", "HEAD") == before + + +def test_base_red_gate_is_advisory_and_commit_failure_is_atomic( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path / "red") + monkeypatch.setenv("STUB_EXIT_PYTEST", "1") + prepared = _prepare(repo, base, monkeypatch) + (repo / "src" / "one.py").write_text("one\n") + result = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} + ) + assert result["reason"] == "unit.committed" + + repo2, base2 = _repo(tmp_path / "hook") + hook = repo2 / ".git" / "hooks" / "pre-commit" + hook.write_text("#!/bin/sh\nexit 1\n") + hook.chmod(0o755) + prepared2 = _prepare(repo2, base2, monkeypatch) + (repo2 / "src" / "one.py").write_text("one\n") + failed = profile_implement_settle( + str(repo2), STORY, SPEC_PATH, BRANCH, base2, prepared2, agent={} + ) + assert failed["reason"] == "commit.failed" + assert git(repo2, "rev-parse", "HEAD") == base2 + + +def test_commit_changed_is_detected_after_hook_rewrites_index( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + hook = repo / ".git" / "hooks" / "pre-commit" + hook.write_text("#!/bin/sh\nprintf altered > src/one.py\ngit add src/one.py\n") + hook.chmod(0o755) + prepared = _prepare(repo, base, monkeypatch) + (repo / "src" / "one.py").write_text("one\n") + result = profile_implement_settle( + str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} + ) + assert result["reason"] == "commit.changed" + assert git(repo, "rev-parse", "HEAD") != base diff --git a/kits/profile-dev-kit/tests/test_implement_workflow.py b/kits/profile-dev-kit/tests/test_implement_workflow.py new file mode 100644 index 0000000..5560f01 --- /dev/null +++ b/kits/profile-dev-kit/tests/test_implement_workflow.py @@ -0,0 +1,261 @@ +"""Workflow shape and in-process Coding-agent coverage.""" + +from __future__ import annotations + +import asyncio +import json +import os +import subprocess +from pathlib import Path +from typing import Any + +import pytest +import yaml +from beddel.domain.errors import AgentError, BeddelError +from beddel.domain.executor import WorkflowExecutor +from beddel.domain.kit import parse_kit_manifest +from beddel.domain.models import AgentResult, DefaultDependencies +from beddel.domain.parser import WorkflowParser +from beddel.domain.registry import PrimitiveRegistry +from beddel.error_codes import AGENT_EXECUTION_FAILED +from beddel.primitives import register_builtins +from beddel.tools.kits import load_kit +from beddel_profile_dev.tools.stage_outcome import profile_record_stage_outcome + +from ._helpers import commit_all, git, init_repo, stub_gate_tools +from .test_implement import BRANCH, SPEC_PATH, STORY, spec_bytes + +KIT_ROOT = Path(__file__).resolve().parents[1] +WORKFLOW_PATH = KIT_ROOT / "workflows" / "implement-story.yaml" + + +class FakeAgent: + def __init__(self, repo: Path, mode: str = "sequence") -> None: + self.repo = repo + self.mode = mode + self.calls = 0 + + async def execute( + self, + prompt: str, + *, + model: str | None = None, + sandbox: str = "read-only", + tools: list[str] | None = None, + output_schema: dict[str, Any] | None = None, + ) -> AgentResult: + self.calls += 1 + if self.mode == "error": + raise AgentError(code=AGENT_EXECUTION_FAILED, message="fake agent failed") + if self.mode == "nothing": + pass + elif self.mode == "out-of-scope": + (self.repo / "outside.py").write_text("outside\n") + elif self.mode == "commit": + (self.repo / "src" / "one.py").write_text("one\n") + await asyncio.to_thread( + subprocess.run, + ["git", "-C", str(self.repo), "add", "-A"], + check=True, + ) + await asyncio.to_thread( + subprocess.run, + [ + "git", + "-C", + str(self.repo), + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "-qm", + "agent", + ], + check=True, + ) + elif self.mode == "switch": + await asyncio.to_thread( + subprocess.run, + ["git", "-C", str(self.repo), "switch", "-q", "-c", "wrong"], + check=True, + ) + else: + target = "one.py" if self.calls == 1 else "two.py" + (self.repo / "src" / target).write_text(f"{target}\n") + if self.mode == "regression": + (self.repo / "src" / "one.py").write_text("one\n") + os.environ["STUB_EXIT_PYTEST"] = "1" + return AgentResult( + exit_code=0, + output="", + events=[], + files_changed=[], + usage={}, + agent_id="fake", + ) + + +def _repo(tmp_path: Path) -> tuple[Path, str]: + repo = init_repo(tmp_path / "repo") + git(repo, "config", "user.name", "Fixture") + git(repo, "config", "user.email", "fixture@example.invalid") + (repo / "src").mkdir() + (repo / "src" / "base.py").write_text("base\n") + (repo / SPEC_PATH).parent.mkdir() + (repo / SPEC_PATH).write_bytes(spec_bytes()) + base = commit_all(repo, "base") + return repo, base + + +def _run(repo: Path, base: str, fake: FakeAgent) -> dict[str, Any]: + workflow = WorkflowParser.parse(WORKFLOW_PATH.read_text()) + registry = PrimitiveRegistry() + register_builtins(registry) + tools = load_kit(parse_kit_manifest(KIT_ROOT / "kit.yaml")) + executor = WorkflowExecutor( + registry, + deps=DefaultDependencies( + agent_registry={"kiro-cli": fake}, tool_registry=tools + ), + ) + return asyncio.run( + executor.execute( + workflow, + { + "repo_path": str(repo), + "story_key": STORY, + "spec_path": SPEC_PATH, + "branch": BRANCH, + "base_ref": base, + }, + ) + ) + + +def test_workflow_shape_and_safety() -> None: + document = yaml.safe_load(WORKFLOW_PATH.read_text()) + assert document["id"] == "implement-story" + assert document["requires_kits"] == ["profile-dev-kit", "agent-kiro-kit"] + assert document["inputs"] == [ + "repo_path", + "story_key", + "spec_path", + "branch", + "base_ref", + ] + assert document["allowed_tools"] == [ + "profile_implement_prepare", + "profile_implement_settle", + "profile_record_stage_outcome", + ] + assert "Coding agent" in document["description"] + assert {step["id"] for step in document["steps"]} == { + "prepare", + "implement", + "settle", + "settle_stop", + "record", + "record_stop", + } + assert "push" not in document["allowed_tools"] + assert "verify" not in document["allowed_tools"] + agent = next(step for step in document["steps"] if step["id"] == "implement") + assert agent["config"]["adapter"] == "kiro-cli" + assert agent["config"]["sandbox"] == "workspace-write" + assert agent["timeout"] <= 600 + workflow = WorkflowParser.parse(WORKFLOW_PATH.read_text()) + steps = {step.id: step for step in workflow.steps} + assert ( + steps["implement"].if_condition + == "$stepResult.prepare.result.implement == true" + ) + assert ( + steps["settle"].if_condition == "$stepResult.prepare.result.implement == true" + ) + assert ( + steps["settle_stop"].if_condition + == "$stepResult.prepare.result.implement != true" + ) + assert ( + steps["record"].if_condition == "$stepResult.prepare.result.implement == true" + ) + assert ( + steps["record_stop"].if_condition + == "$stepResult.prepare.result.implement != true" + ) + + +def test_two_unit_sequence_records_and_resumes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + monkeypatch.chdir(repo) + monkeypatch.setenv("PATH", stub_gate_tools(tmp_path)) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + fake = FakeAgent(repo) + first = _run(repo, base, fake) + assert first["step_results"]["settle"]["result"]["reason"] == "unit.committed" + second = _run(repo, base, fake) + assert second["step_results"]["settle"]["result"]["reason"] == "unit.committed" + third = _run(repo, base, fake) + assert third["step_results"]["settle_stop"]["result"]["reason"] == "units.complete" + assert fake.calls == 2 + records = Path.home() / ".config" / "beddel" + del records + stored = list((tmp_path / "home").rglob("*.json")) + assert len(stored) == 3 + assert sorted(json.loads(path.read_text())["record"] for path in stored) == [ + 1, + 2, + 3, + ] + + +@pytest.mark.parametrize( + ("mode", "reason"), + [ + ("out-of-scope", "scope.exceeded"), + ("commit", "head.moved"), + ("nothing", "unit.empty"), + ("error", "agent.failed"), + ("switch", "branch.moved"), + ("regression", "gate.regressed"), + ], +) +def test_agent_modes_are_recorded_without_losing_base( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str, reason: str +) -> None: + repo, base = _repo(tmp_path / mode) + monkeypatch.chdir(repo) + monkeypatch.setenv("PATH", stub_gate_tools(tmp_path / mode)) + monkeypatch.setenv("HOME", str(tmp_path / mode / "home")) + fake = FakeAgent(repo, mode) + before = git(repo, "rev-parse", "HEAD") + result = _run(repo, base, fake) + settle = result["step_results"].get( + "settle", result["step_results"].get("settle_stop") + ) + assert settle["result"]["reason"] == reason + if mode == "regression": + os.environ.pop("STUB_EXIT_PYTEST", None) + assert git(repo, "rev-parse", "HEAD") == before or reason == "head.moved" + + +def test_bad_repository_fails_at_record_boundary( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + bad = tmp_path / "not-a-repository" + bad.mkdir() + monkeypatch.chdir(repo) + monkeypatch.setenv("PATH", stub_gate_tools(tmp_path)) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + with pytest.raises(BeddelError) as error: + _run(bad, base, FakeAgent(bad)) + assert error.value.code == "BEDDEL-EXEC-002" + with pytest.raises(BeddelError) as record_error: + profile_record_stage_outcome( + str(bad), STORY, "implement", "failed", "prepare.failed", {} + ) + assert record_error.value.code == "PROFILE_REPOSITORY_INVALID" diff --git a/kits/profile-dev-kit/tests/test_manifest.py b/kits/profile-dev-kit/tests/test_manifest.py index 79aa452..d144b8b 100644 --- a/kits/profile-dev-kit/tests/test_manifest.py +++ b/kits/profile-dev-kit/tests/test_manifest.py @@ -33,6 +33,8 @@ "profile_plan_reconcile", "profile_plan_settle", "profile_record_stage_outcome", + "profile_implement_prepare", + "profile_implement_settle", ] @@ -106,6 +108,7 @@ def test_manifest_declares_all_workflows_and_python_targets() -> None: "approve-change", "record-approval-decision", "read-approval", + "implement-story", "plan-story", ] declared = {t["name"] for t in manifest["tools"]} diff --git a/kits/profile-dev-kit/tests/test_workflow.py b/kits/profile-dev-kit/tests/test_workflow.py index 58e0942..1a4d994 100644 --- a/kits/profile-dev-kit/tests/test_workflow.py +++ b/kits/profile-dev-kit/tests/test_workflow.py @@ -113,7 +113,7 @@ def test_allowlist_equals_the_tools_the_steps_name() -> None: "profile_capture_evidence", "profile_record_report", ] - assert len(list(WORKFLOWS_DIR.glob("*.yaml"))) == 9 + assert len(list(WORKFLOWS_DIR.glob("*.yaml"))) == 10 def test_review_step_outlives_the_largest_accepted_review_budget() -> None: diff --git a/kits/profile-dev-kit/workflows/implement-story.yaml b/kits/profile-dev-kit/workflows/implement-story.yaml new file mode 100644 index 0000000..9e6ed3f --- /dev/null +++ b/kits/profile-dev-kit/workflows/implement-story.yaml @@ -0,0 +1,103 @@ +id: implement-story +name: Implement Story +description: Entry implement stage where a Coding agent implements one unit of one spec through agent-exec; the kit checks, gates and commits only that unit's paths on a feature branch. It never pushes, verifies, approves or integrates. +version: "1.0" +requires_kits: + - profile-dev-kit + - agent-kiro-kit +allowed_tools: + - profile_implement_prepare + - profile_implement_settle + - profile_record_stage_outcome +inputs: + - repo_path + - story_key + - spec_path + - branch + - base_ref +steps: + - id: prepare + primitive: tool + execution_strategy: + type: skip + config: + tool: profile_implement_prepare + arguments: + repo_path: "$input.repo_path" + story_key: "$input.story_key" + spec_path: "$input.spec_path" + branch: "$input.branch" + base_ref: "$input.base_ref" + - id: implement + primitive: agent-exec + if: "$stepResult.prepare.result.implement == true" + execution_strategy: + type: skip + timeout: 600 + config: + adapter: kiro-cli + sandbox: workspace-write + prompt: >- + You are the Coding agent for one implementation unit. Read the spec at + $input.spec_path and implement only the paths named by + $stepResult.prepare.result.unit_paths for unit + $stepResult.prepare.result.unit_id Change only those paths and files under + them. Leave the spec unchanged. Do not stage, commit, push, create or switch + branches, approve, verify or integrate. + - id: settle + primitive: tool + execution_strategy: + type: fail + if: "$stepResult.prepare.result.implement == true" + config: + tool: profile_implement_settle + arguments: + repo_path: "$input.repo_path" + story_key: "$input.story_key" + spec_path: "$input.spec_path" + branch: "$input.branch" + base_ref: "$input.base_ref" + prepare: "$stepResult.prepare.result" + agent: "$stepResult.implement" + - id: settle_stop + primitive: tool + execution_strategy: + type: fail + if: "$stepResult.prepare.result.implement != true" + config: + tool: profile_implement_settle + arguments: + repo_path: "$input.repo_path" + story_key: "$input.story_key" + spec_path: "$input.spec_path" + branch: "$input.branch" + base_ref: "$input.base_ref" + prepare: "$stepResult.prepare.result" + - id: record + primitive: tool + execution_strategy: + type: fail + if: "$stepResult.prepare.result.implement == true" + config: + tool: profile_record_stage_outcome + arguments: + repo_path: "$input.repo_path" + story_key: "$stepResult.settle.result.story_key" + stage: implement + outcome: "$stepResult.settle.result.outcome" + reason: "$stepResult.settle.result.reason" + refs: "$stepResult.settle.result.refs" + - id: record_stop + primitive: tool + execution_strategy: + type: fail + if: "$stepResult.prepare.result.implement != true" + config: + tool: profile_record_stage_outcome + arguments: + repo_path: "$input.repo_path" + story_key: "$stepResult.settle_stop.result.story_key" + stage: implement + outcome: "$stepResult.settle_stop.result.outcome" + reason: "$stepResult.settle_stop.result.reason" + refs: "$stepResult.settle_stop.result.refs" diff --git a/kits/profile-dev-kit/workflows/plan-story.yaml b/kits/profile-dev-kit/workflows/plan-story.yaml index 5474473..6dda160 100644 --- a/kits/profile-dev-kit/workflows/plan-story.yaml +++ b/kits/profile-dev-kit/workflows/plan-story.yaml @@ -41,7 +41,9 @@ steps: You are the Coding agent for one plan stage. Read the selected story source at $input.story_path and the planning guide at $input.guide_path and write exactly one complete implementation spec to $input.spec_path and ensure its YAML front matter - contains story_key, requirements, repositories, dependencies and size_cap_bytes; + contains story_key, requirements, repositories, dependencies, size_cap_bytes and + a units list, each entry with an id, the repository-relative paths it may change + and a Conventional Commit subject; set story_key to $input.story_key and size_cap_bytes to 64000. Keep the spec within the 64000-byte cap. Change no other file. Do not implement, test, verify, commit or push. From 5ee71016b4b69faaca8d26dcb87845877fdb3027 Mon Sep 17 00:00:00 2001 From: Carlos Bacelar Date: Tue, 10 Nov 2026 10:53:36 -0300 Subject: [PATCH 2/3] fix(profile-dev-kit): implement stage commits only changed unit paths and re-checks the tree after gates (Story 7.4 review round 1) Never commits the spec, tolerates unwritten unit paths, enforces the size cap exactly, validates the Gate baseline and records absorbed prepare failures. --- kits/profile-dev-kit/README.md | 29 +- .../python/beddel_profile_dev/implement.py | 5 +- .../beddel_profile_dev/tools/implement.py | 334 +++++--------- kits/profile-dev-kit/tests/test_implement.py | 428 ++++-------------- .../tests/test_implement_workflow.py | 70 ++- 5 files changed, 264 insertions(+), 602 deletions(-) diff --git a/kits/profile-dev-kit/README.md b/kits/profile-dev-kit/README.md index e71fdf6..d48414b 100644 --- a/kits/profile-dev-kit/README.md +++ b/kits/profile-dev-kit/README.md @@ -455,30 +455,15 @@ Run the workflow from the repository root, for example: ```text beddel run -i ... workflows/plan-story.yaml ``` -## Delivery: implement stage -The `implement-story` entry workflow accepts `repo_path`, `story_key`, -`spec_path`, `branch` and `base_ref`. It creates or reuses the feature branch, -selects the first unfinished unit, invokes one Coding agent through -`agent-exec`, runs the review checks and Gate commands, and commits only that -unit's declared paths. It never pushes, approves, verifies, integrates, -commits the spec or writes a profile record itself. - -The implement contract adds `units` to a complete plan spec. Each unit has a -unique `id`, one to 64 repository-relative `paths` and a Conventional Commit -`subject`. Commits carry exactly one `Story-Key` and one -`Implementation-Unit` trailer. One unit is committed per run; rerun the -workflow to resume the next unit. A clean baseline Gate is required only for -regression comparison, so a gate already red at baseline is advisory. - -Review failures use fixed reasons including `worktree.dirty`, `scope.exceeded`, -`unit.empty`, `size.exceeded`, `secret.detected`, `gate.regressed`, -`gate.changed_tree`, `agent.failed` and `commit.failed`. Successful runs use -`unit.committed` or `units.complete`. Outcome refs include the spec digest, -branch, base, head, commit, unit, completion counts, diff size, out-of-scope -count and regressed command names. +## Delivery: implement stage -Run the workflow from the repository root, for example: +`implement-story` takes `repo_path`, `story_key`, `spec_path`, `branch` and +`base_ref`; its steps prepare, invoke one Coding agent, settle one unit and +record one Stage outcome. It never pushes, approves, verifies, integrates, or +commits the spec. `units` entries have an `id`, relative `paths` and a commit +`subject`; commits carry the identity trailers. One unit runs per invocation. +A baseline-red Gate is advisory; only a green command that becomes red blocks. ```text beddel run -i ... workflows/implement-story.yaml diff --git a/kits/profile-dev-kit/python/beddel_profile_dev/implement.py b/kits/profile-dev-kit/python/beddel_profile_dev/implement.py index 3daf1c6..df875f0 100644 --- a/kits/profile-dev-kit/python/beddel_profile_dev/implement.py +++ b/kits/profile-dev-kit/python/beddel_profile_dev/implement.py @@ -99,13 +99,16 @@ def branch_reason(branch: object, base_ref: object) -> str | None: """Return the refusal reason for a branch/base pair, if any.""" if not isinstance(branch, str) or _BRANCH.fullmatch(branch) is None: return "branch.invalid" + parts = branch.split("/") if ( branch in PROTECTED_BRANCHES or branch == base_ref or branch.startswith("-") - or branch.endswith(("/", ".")) + or branch.endswith(("/", ".", ".lock")) + or any(part.startswith(".") for part in parts) or ".." in branch or "//" in branch + or "@{" in branch ): return ( "branch.protected" diff --git a/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py b/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py index e6281ce..fefcd5c 100644 --- a/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py +++ b/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py @@ -41,7 +41,6 @@ __all__ = ["profile_implement_prepare", "profile_implement_settle"] _MAX_BASE_REF = 200 -_FULL_SHA_LENGTH = 40 def _valid_story(value: object) -> bool: @@ -88,6 +87,12 @@ def _refs( } +# fmt: off +def _state(spec, digest=None, branch=None, base=None, head=None, unit=None, **extra): + return _refs(spec_path=spec, spec_sha256=digest, branch=branch, base=base, head=head, unit=unit, **extra) +# fmt: on + + def _result( story_key: str | None, outcome: str | None, @@ -144,6 +149,12 @@ def _failure( return _result(story_key, "failed", reason, refs, **kwargs) +# fmt: off +def _fail(story, reason, spec, digest=None, branch=None, base=None, head=None, unit=None, **extra): + return _failure(story, reason, _state(spec, digest, branch, base, head, unit, **extra)) +# fmt: on + + def _read_spec(repo: Path, spec_path: str) -> tuple[bytes | None, str | None]: try: path = confined(repo, spec_path) @@ -328,14 +339,10 @@ def profile_implement_prepare( story, "gate.unavailable", spec_path=spec, branch=branch_name ) except ProfileError: - return _failure( - story, "prepare.failed", _refs(spec_path=spec, branch=branch_name) - ) + return _failure(story, "prepare.failed", _state(spec, branch=branch_name)) dirty = changed_paths(repo) - {spec} if dirty: - return _failure( - story, "worktree.dirty", _refs(spec_path=spec, branch=branch_name) - ) + return _failure(story, "worktree.dirty", _state(spec, branch=branch_name)) ref = git_run(repo, "show-ref", "--verify", "--quiet", f"refs/heads/{branch_name}") if ref is None or ref.returncode not in (0, 1): @@ -353,7 +360,7 @@ def profile_implement_prepare( switched = git_run(repo, "switch", "-q", branch_name) if switched is None or switched.returncode != 0: return _failure( - story, "checkout.failed", _refs(spec_path=spec, branch=branch_name) + story, "checkout.failed", _state(spec, branch=branch_name) ) else: switched = git_run(repo, "switch", "-q", "-c", branch_name, base_sha) @@ -454,6 +461,7 @@ def profile_implement_prepare( ) +# fmt: off @beddel_tool( name="profile_implement_settle", description="Review and commit one implementation unit", @@ -473,224 +481,118 @@ def profile_implement_settle( if isinstance(checked, dict): return checked repo, story, spec, branch_name, _base_ref = checked + if prepare is None: + return _fail(story, "prepare.failed", spec, branch=branch_name) if not isinstance(prepare, Mapping): - return _failure( - story, "prepare.mismatch", _refs(spec_path=spec, branch=branch_name) - ) + return _fail(story, "prepare.mismatch", spec, branch=branch_name) if prepare.get("story_key") != story or prepare.get("stage") != "implement": - return _failure( - story, "prepare.mismatch", _refs(spec_path=spec, branch=branch_name) - ) + return _fail(story, "prepare.mismatch", spec, branch=branch_name) if prepare.get("implement") is not True: return _result( story, prepare.get("outcome"), prepare.get("reason"), - prepare.get("refs", _refs(spec_path=spec, branch=branch_name)), + prepare.get("refs", _state(spec, branch=branch_name)), ) if not isinstance(agent, Mapping): - return _failure( - story, "agent.failed", _refs(spec_path=spec, branch=branch_name) + return _fail(story, "agent.failed", spec, branch=branch_name) + base = prepare.get("base") + head = resolve_revision(repo, "HEAD") + if _symbolic_branch(repo) != branch_name: + return _fail( + story, "branch.moved", spec, branch=branch_name, + base=base if isinstance(base, str) else None, head=head, ) + if head != prepare.get("head"): + return _fail( + story, "head.moved", spec, branch=branch_name, + base=base if isinstance(base, str) else None, head=head, + ) + if not isinstance(base, str): + return _fail(story, "prepare.mismatch", spec, branch=branch_name, head=head) data, error = _read_spec(repo, spec) if error is not None or data is None: - return _failure( - story, "spec.changed", _refs(spec_path=spec, branch=branch_name) - ) + return _fail(story, "spec.changed", spec, branch=branch_name, base=base, head=head) units = spec_units(data, story) if units is None: - return _failure( - story, "spec.changed", _refs(spec_path=spec, branch=branch_name) - ) + return _fail(story, "spec.changed", spec, branch=branch_name, base=base, head=head) spec_digest = hashlib.sha256(data).hexdigest() if prepare.get("spec_sha256") != spec_digest: - return _failure( - story, - "spec.changed", - _refs(spec_path=spec, spec_sha256=spec_digest, branch=branch_name), - ) + return _fail(story, "spec.changed", spec, spec_digest, branch_name, base, head) unit_id = prepare.get("unit_id") unit = next((item for item in units if item.id == unit_id), None) if unit is None or prepare.get("unit_paths") != ", ".join(unit.paths): - return _failure( - story, - "prepare.mismatch", - _refs(spec_path=spec, spec_sha256=spec_digest, branch=branch_name), - ) + return _fail(story, "prepare.mismatch", spec, spec_digest, branch_name, base, head) try: config = load_config() + names = [f"{i:02d}-{argv[0]}" for i, argv in enumerate(config.gate_commands, 1)] + baseline = prepare.get("baseline") + if ( + not isinstance(baseline, list) + or any(not isinstance(item, Mapping) for item in baseline) + or any(not {"name", "exit_code", "timed_out"} <= item.keys() for item in baseline) + or [item.get("name") for item in baseline] != names + ): + return _fail(story, "prepare.mismatch", spec, spec_digest, branch_name, base, head, unit.id) for argv in config.gate_commands: if resolve_executable(argv[0]) is None: - return _failure( - story, - "gate.unavailable", - _refs(spec_path=spec, spec_sha256=spec_digest, branch=branch_name), - ) - base = prepare.get("base") - head = resolve_revision(repo, "HEAD") - if _symbolic_branch(repo) != branch_name: - return _failure( - story, - "branch.moved", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base if isinstance(base, str) else None, - head=head, - unit=unit.id, - ), - ) - if head != prepare.get("head"): - return _failure( - story, - "head.moved", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base if isinstance(base, str) else None, - head=head, - unit=unit.id, - ), - ) - if not isinstance(base, str): - return _failure( - story, - "prepare.mismatch", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - head=head, - unit=unit.id, - ), - ) + return _fail(story, "gate.unavailable", spec, spec_digest, branch_name, base, head, unit.id) current = changed_paths(repo) - {spec} if not current: - return _failure( - story, - "unit.empty", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=head, - unit=unit.id, - ), - ) + return _fail(story, "unit.empty", spec, spec_digest, branch_name, base, head, unit.id) out_of_scope = sum(not covered(unit.paths, path) for path in current) if out_of_scope: - return _failure( - story, - "scope.exceeded", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=head, - unit=unit.id, - out_of_scope=out_of_scope, - ), - unit_id=unit.id, - unit_paths=", ".join(unit.paths), + return _fail( + story, "scope.exceeded", spec, spec_digest, branch_name, base, head, + unit.id, out_of_scope=out_of_scope, ) - candidate = _candidate_tree(repo, unit.paths) - cap = front_matter(data) - assert cap is not None - diff, truncated = diff_text( - repo, base, candidate, int(cap["size_cap_bytes"]) + 1 - ) + paths = tuple(sorted(current)) + candidate = _candidate_tree(repo, paths) + metadata = front_matter(data) + assert metadata is not None + cap = int(metadata["size_cap_bytes"]) + diff, truncated = diff_text(repo, base, candidate, cap) diff_bytes = len(diff.encode("utf-8")) if truncated: - return _failure( - story, - "size.exceeded", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=head, - unit=unit.id, - diff_bytes=diff_bytes, - ), + full, still_truncated = diff_text(repo, base, candidate, 262144) + diff_bytes = len(full.encode("utf-8")) if not still_truncated else cap + 1 + return _fail( + story, "size.exceeded", spec, spec_digest, branch_name, base, head, + unit.id, diff_bytes=diff_bytes, ) - if ( - _TOKEN.search( - "\n".join(line for line in diff.splitlines() if line.startswith("+")) + if _TOKEN.search("\n".join(x for x in diff.splitlines() if x.startswith("+"))): + return _fail( + story, "secret.detected", spec, spec_digest, branch_name, base, head, + unit.id, diff_bytes=diff_bytes, ) - is not None - ): - return _failure( - story, - "secret.detected", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=head, - unit=unit.id, - diff_bytes=diff_bytes, - ), - ) - before_gates = set(current) gates = _run_gates(repo, config) - if changed_paths(repo) - {spec} != before_gates: - return _failure( - story, - "gate.changed_tree", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=head, - unit=unit.id, - diff_bytes=diff_bytes, - ), + after = changed_paths(repo) - {spec} + if after != current: + return _fail( + story, "gate.changed_tree", spec, spec_digest, branch_name, base, head, + unit.id, diff_bytes=diff_bytes, ) - regressed = [ - entry["name"] - for entry, baseline in zip(gates, prepare.get("baseline") or []) - if ( - baseline.get("exit_code") == 0 - and (entry["timed_out"] or entry["exit_code"] != 0) + if _candidate_tree(repo, tuple(sorted(after))) != candidate: + return _fail( + story, "gate.changed_tree", spec, spec_digest, branch_name, base, head, + unit.id, diff_bytes=diff_bytes, ) + regressed = [ + entry["name"] for entry, baseline_item in zip(gates, baseline) + if baseline_item["exit_code"] == 0 + and (entry["timed_out"] or entry["exit_code"] != 0) ] if regressed: - return _failure( - story, - "gate.regressed", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=head, - unit=unit.id, - diff_bytes=diff_bytes, - regressed=", ".join(regressed), - ), + return _fail( + story, "gate.regressed", spec, spec_digest, branch_name, base, head, + unit.id, diff_bytes=diff_bytes, regressed=", ".join(regressed), ) subject, trailers = commit_message(unit, story) - committed = git_run(repo, "add", "-A", "--", *unit.paths) + committed = git_run(repo, "add", "-A", "--", *paths) if committed is None or committed.returncode != 0: - return _failure( - story, - "commit.failed", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=head, - unit=unit.id, - diff_bytes=diff_bytes, - ), + return _fail( + story, "commit.failed", spec, spec_digest, branch_name, base, head, + unit.id, diff_bytes=diff_bytes, ) committed = git_run( repo, @@ -702,57 +604,36 @@ def profile_implement_settle( trailers, "--only", "--", - *unit.paths, + *paths, timeout=120, ) if committed is None or committed.returncode != 0: - return _failure( - story, - "commit.failed", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=head, - unit=unit.id, - diff_bytes=diff_bytes, - ), + return _fail( + story, "commit.failed", spec, spec_digest, branch_name, base, head, + unit.id, diff_bytes=diff_bytes, ) new_head = resolve_revision(repo, "HEAD") parent = _git_text(git_run(repo, "rev-parse", "HEAD^")) tree = _git_text(git_run(repo, "rev-parse", "HEAD^{tree}")) if parent != head or tree != candidate: - return _failure( - story, - "commit.changed", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=new_head, - commit=new_head, - unit=unit.id, - diff_bytes=diff_bytes, - ), + return _fail( + story, "commit.changed", spec, spec_digest, branch_name, base, new_head, + unit.id, commit=new_head, diff_bytes=diff_bytes, ) completed = _completed(repo, base, story) + if unit.id not in completed: + return _fail( + story, "commit.changed", spec, spec_digest, branch_name, base, new_head, + unit.id, commit=new_head, diff_bytes=diff_bytes, + ) return _result( story, "succeeded", "unit.committed", - _refs( - spec_path=spec, - spec_sha256=spec_digest, - branch=branch_name, - base=base, - head=new_head, - commit=new_head, - unit=unit.id, - completed=len(completed), - remaining=len(units) - len(completed), - diff_bytes=diff_bytes, + _state( + spec, spec_digest, branch_name, base, new_head, unit.id, + commit=new_head, completed=len(completed), + remaining=len(units) - len(completed), diff_bytes=diff_bytes, ), spec_sha256=spec_digest, base=base, @@ -761,8 +642,5 @@ def profile_implement_settle( unit_paths=", ".join(unit.paths), ) except ProfileError: - return _failure( - story, - "settle.failed", - _refs(spec_path=spec, spec_sha256=spec_digest, branch=branch_name), - ) + return _fail(story, "settle.failed", spec, spec_digest, branch_name) +# fmt: on diff --git a/kits/profile-dev-kit/tests/test_implement.py b/kits/profile-dev-kit/tests/test_implement.py index 47668a9..e61b930 100644 --- a/kits/profile-dev-kit/tests/test_implement.py +++ b/kits/profile-dev-kit/tests/test_implement.py @@ -1,5 +1,3 @@ -"""Contract and I/O matrix coverage for the implement stage.""" - from __future__ import annotations import os @@ -22,348 +20,98 @@ from ._helpers import commit_all, git, init_repo, stub_gate_tools +# fmt: off STORY = "7-4-implement-workflow-turns-a-spec-into-a-branch-and-commits" SPEC_PATH = "specs/story.md" BRANCH = "feat/story-7-4" - -def spec_bytes( - units: list[dict[str, object]] | None = None, *, cap: int = 64000 -) -> bytes: - values = units or [ - {"id": "u1", "paths": ["src/one.py"], "subject": "feat(core): add one"}, - {"id": "u2", "paths": ["src/two.py"], "subject": "feat(core): add two"}, - ] - return ( - ( - f"---\nstory_key: {STORY}\nrequirements: [FR-10]\n" - "repositories: [.]\ndependencies: []\n" - f"size_cap_bytes: {cap}\nunits: {values!r}\n---\n\n# Spec\n" - ) - .replace("'", '"') - .encode() - ) - - -def _repo(tmp_path: Path) -> tuple[Path, str]: - repo = init_repo(tmp_path / "repo") - git(repo, "config", "user.name", "Fixture") - git(repo, "config", "user.email", "fixture@example.invalid") - (repo / "src").mkdir() - (repo / "src" / "base.py").write_text("base = True\n") - (repo / SPEC_PATH).parent.mkdir() - (repo / SPEC_PATH).write_bytes(spec_bytes()) - base = commit_all(repo, "base") - (repo / SPEC_PATH).write_bytes(spec_bytes()) +def spec_bytes(units=None, *, cap=64000): + values = units or [{"id":"u1","paths":["src/one.py"],"subject":"feat(core): add one"},{"id":"u2","paths":["src/two.py"],"subject":"feat(core): add two"}] + return (f"---\nstory_key: {STORY}\nrequirements: [FR-10]\nrepositories: [.]\ndependencies: []\nsize_cap_bytes: {cap}\nunits: {values!r}\n---\n\n# Spec\n").replace("'", '"').encode() + +def _repo(root, units=None, spec=SPEC_PATH, track=True): + repo = init_repo(root / "repo") + git(repo,"config","user.name","Fixture"); git(repo,"config","user.email","fixture@example.invalid") + (repo / "src").mkdir(); (repo / "src" / "base.py").write_text("base = True\n") + (repo / spec).parent.mkdir(exist_ok=True); (repo / spec).write_bytes(spec_bytes(units)) + base = commit_all(repo,"base") + if not track: (repo / spec).unlink(); (repo / spec).write_bytes(spec_bytes(units)) return repo, base - -def _prepare( - repo: Path, base: str, monkeypatch: pytest.MonkeyPatch -) -> dict[str, object]: - monkeypatch.chdir(repo) - monkeypatch.setenv("PATH", stub_gate_tools(repo.parent)) - monkeypatch.setenv("HOME", str(repo.parent / "home")) - return profile_implement_prepare(str(repo), STORY, SPEC_PATH, BRANCH, base) - - -def test_pure_unit_contract() -> None: - units = spec_units(spec_bytes(), STORY) - assert units == ( - Unit("u1", ("src/one.py",), "feat(core): add one"), - Unit("u2", ("src/two.py",), "feat(core): add two"), - ) - assert ( - spec_units( - spec_bytes([{"id": "bad id", "paths": ["x"], "subject": "feat: x"}]), STORY - ) - is None - ) - assert branch_reason("main", "origin/main") == "branch.protected" - assert branch_reason("feat/x", "feat/x") == "branch.protected" - assert branch_reason("../bad", "main") == "branch.invalid" - assert branch_reason("feat/x", "main") is None - assert covered(("src",), "src/a.py") - assert covered(("src/a.py",), "src/a.py") - assert not covered(("src/a.py",), "src/ab.py") - subject, trailers = commit_message(Unit("u1", ("x",), "feat: x"), STORY) - assert subject == "feat: x" - assert trailer_unit(f"{subject}\n\n{trailers}\n", STORY) == "u1" - assert trailer_unit(f"{trailers}\n{trailers}\n", STORY) is None - - -def test_first_resume_complete_and_failure_paths( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - repo, base = _repo(tmp_path) - prepared = _prepare(repo, base, monkeypatch) - assert prepared["implement"] is True - (repo / "src" / "one.py").write_text("one = 1\n") - first = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} - ) - assert first["reason"] == "unit.committed" - first_head = git(repo, "rev-parse", "HEAD") - - prepared2 = _prepare(repo, base, monkeypatch) - assert prepared2["unit_id"] == "u2" - (repo / "src" / "two.py").write_text("two = 2\n") - second = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared2, agent={} - ) - assert second["reason"] == "unit.committed" - assert second["refs"]["completed"] == 2 - - prepared3 = _prepare(repo, base, monkeypatch) - assert prepared3["reason"] == "units.complete" - assert git(repo, "rev-parse", "HEAD") == second["refs"]["head"] - complete = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared3 - ) - assert complete["reason"] == "units.complete" - assert git(repo, "rev-parse", "HEAD") == second["refs"]["head"] - assert first_head != second["refs"]["head"] - - -def test_refusal_dirty_agent_scope_empty_and_branch_tip_unchanged( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - repo, base = _repo(tmp_path) - monkeypatch.chdir(repo) - monkeypatch.setenv("PATH", stub_gate_tools(repo.parent)) - monkeypatch.setenv("HOME", str(repo.parent / "home")) - (repo / "unexpected.txt").write_text("dirty\n") - before = git(repo, "rev-parse", "HEAD") - dirty = profile_implement_prepare(str(repo), STORY, SPEC_PATH, BRANCH, base) - assert dirty["reason"] == "worktree.dirty" - assert git(repo, "rev-parse", "HEAD") == before - (repo / "unexpected.txt").unlink() - prepared = _prepare(repo, base, monkeypatch) - assert ( - profile_implement_settle(str(repo), STORY, SPEC_PATH, BRANCH, base, prepared)[ - "reason" - ] - == "agent.failed" - ) - empty = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} - ) - assert empty["reason"] == "unit.empty" - (repo / "outside.py").write_text("outside\n") - out = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} - ) - assert out["reason"] == "scope.exceeded" - assert git(repo, "rev-parse", "HEAD") == before - - -def test_gate_regression_token_and_size_overflow_leave_tip_unchanged( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - repo, base = _repo(tmp_path) - prepared = _prepare(repo, base, monkeypatch) - (repo / "src" / "one.py").write_text("one = 1\n") - monkeypatch.setenv("STUB_EXIT_PYTEST", "1") - regressed = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} - ) - assert regressed["reason"] == "gate.regressed" - monkeypatch.delenv("STUB_EXIT_PYTEST") - - repo2, base2 = _repo(tmp_path / "token") - prepared2 = _prepare(repo2, base2, monkeypatch) - token_value = "gh" + "p_" + "A" * 36 - token_before = git(repo2, "rev-parse", "HEAD") - (repo2 / "src" / "one.py").write_text(f"token = '{token_value}'\n") - token = profile_implement_settle( - str(repo2), STORY, SPEC_PATH, BRANCH, base2, prepared2, agent={} - ) - assert token["reason"] == "secret.detected" - assert token_value not in repr(token) - assert git(repo2, "rev-parse", "HEAD") == token_before - - repo3, base3 = _repo(tmp_path / "size") - (repo3 / SPEC_PATH).write_bytes(spec_bytes(cap=10)) - prepared3 = _prepare(repo3, base3, monkeypatch) - (repo3 / "src" / "one.py").write_text("x = " + "a" * 100 + "\n") - size = profile_implement_settle( - str(repo3), STORY, SPEC_PATH, BRANCH, base3, prepared3, agent={} - ) - assert size["reason"] == "size.exceeded" - - -def test_gate_changed_tree_stops_without_commit( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - repo, base = _repo(tmp_path) - prepared = _prepare(repo, base, monkeypatch) - gate_bin = Path(os.environ["PATH"].split(os.pathsep)[0]) - (gate_bin / "ruff").write_text( - "#!/usr/bin/env python3\n" - "from pathlib import Path\n" - "Path('gate-output.txt').write_text('changed')\n" - ) - (gate_bin / "ruff").chmod(0o755) - (repo / "src" / "one.py").write_text("one = 1\n") - result = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} - ) - assert result["reason"] == "gate.changed_tree" - assert git(repo, "rev-parse", "HEAD") == base - - -@pytest.mark.parametrize( - ("case", "reason"), - [ - ("story", "story_key.invalid"), - ("path", "path.invalid"), - ("branch", "branch.invalid"), - ("protected", "branch.protected"), - ("base", "base.invalid"), - ("cwd", "cwd.mismatch"), - ("absent", "spec.absent"), - ("unreadable", "spec.unreadable"), - ("incomplete", "spec.incomplete"), - ("units", "units.invalid"), - ("gate", "gate.unavailable"), - ], -) -def test_prepare_refusals_keep_branch_tip( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - case: str, - reason: str, -) -> None: - repo, base = _repo(tmp_path / case) - monkeypatch.chdir(repo) - monkeypatch.setenv("PATH", stub_gate_tools(tmp_path / case)) - monkeypatch.setenv("HOME", str(tmp_path / case / "home")) - before = git(repo, "rev-parse", "HEAD") - story, spec, branch, base_ref = STORY, SPEC_PATH, BRANCH, base - if case == "story": - story = "BAD KEY" - elif case == "path": - spec = "../outside.md" - elif case == "branch": - branch = "Bad Branch" - elif case == "protected": - branch = "main" - elif case == "base": - base_ref = "missing-base" - elif case == "cwd": - (tmp_path / case / "elsewhere").mkdir() - monkeypatch.chdir(tmp_path / case / "elsewhere") - elif case == "absent": - (repo / spec).unlink() - elif case == "unreadable": - (repo / spec).unlink() - (repo / spec).mkdir() - elif case == "incomplete": - (repo / spec).write_bytes(b"unfinished") - elif case == "units": - (repo / spec).write_bytes( - spec_bytes( - [{"id": "bad id", "paths": ["src/one.py"], "subject": "feat: bad"}] - ) - ) +def _prepare(repo, base, patch, spec=SPEC_PATH, branch=BRANCH): + patch.chdir(repo); patch.setenv("PATH",stub_gate_tools(repo.parent)); patch.setenv("HOME",str(repo.parent / "home")) + return profile_implement_prepare(str(repo),STORY,spec,branch,base) + +def _settle(repo, base, prepared, spec=SPEC_PATH): + return profile_implement_settle(str(repo),STORY,spec,BRANCH,base,prepared,agent={}) + +def test_pure_unit_contract(): + assert spec_units(spec_bytes(),STORY) == (Unit("u1",("src/one.py",),"feat(core): add one"),Unit("u2",("src/two.py",),"feat(core): add two")) + assert spec_units(spec_bytes([{"id":"bad id","paths":["x"],"subject":"feat: x"}]),STORY) is None + assert branch_reason("main","origin/main") == "branch.protected"; assert branch_reason("feat/x","feat/x") == "branch.protected" + assert branch_reason("../bad","main") == "branch.invalid"; assert branch_reason("feat/x","main") is None + assert covered(("src",),"src/a.py") and covered(("src/a.py",),"src/a.py") and not covered(("src/a.py",),"src/ab.py") + subject, trailers = commit_message(Unit("u1",("x",),"feat: x"),STORY) + assert subject == "feat: x" and trailer_unit(f"{subject}\n\n{trailers}\n",STORY) == "u1" + assert trailer_unit(f"{trailers}\n{trailers}\n",STORY) is None + +def test_first_resume_complete_and_failure_paths(tmp_path, monkeypatch): + repo, base = _repo(tmp_path); prepared = _prepare(repo,base,monkeypatch); assert prepared["implement"] + (repo / "src/one.py").write_text("one = 1\n"); first = _settle(repo,base,prepared); assert first["reason"] == "unit.committed" + assert first["refs"]["commit"] == first["refs"]["head"] and (first["refs"]["completed"],first["refs"]["remaining"]) == (1,1) + assert git(repo,"show","--name-only","--format=","HEAD").split() == ["src/one.py"] and "Implementation-Unit: u1" in git(repo,"show","-s","--format=%B","HEAD") + prepared2 = _prepare(repo,base,monkeypatch); assert prepared2["unit_id"] == "u2"; (repo / "src/two.py").write_text("two = 2\n"); second = _settle(repo,base,prepared2); assert second["refs"]["completed"] == 2 + head = git(repo,"rev-parse","HEAD"); prepared3 = _prepare(repo,base,monkeypatch); assert prepared3["reason"] == "units.complete"; assert _settle(repo,base,prepared3)["reason"] == "units.complete"; assert git(repo,"rev-parse","HEAD") == head + +def test_dirty_agent_scope_empty_and_tip_unchanged(tmp_path, monkeypatch): + repo, base = _repo(tmp_path); patch = monkeypatch; patch.chdir(repo); patch.setenv("PATH",stub_gate_tools(repo.parent)); patch.setenv("HOME",str(repo.parent / "home")); before = git(repo,"rev-parse","HEAD") + (repo / "unexpected.txt").write_text("dirty\n"); assert profile_implement_prepare(str(repo),STORY,SPEC_PATH,BRANCH,base)["reason"] == "worktree.dirty"; (repo / "unexpected.txt").unlink() + prepared = _prepare(repo,base,patch); assert profile_implement_settle(str(repo),STORY,SPEC_PATH,BRANCH,base,prepared)["reason"] == "agent.failed"; assert _settle(repo,base,prepared)["reason"] == "unit.empty" + (repo / "outside.py").write_text("outside\n"); assert _settle(repo,base,prepared)["reason"] == "scope.exceeded"; assert git(repo,"rev-parse","HEAD") == before + +def test_regression_token_and_size(tmp_path, monkeypatch): + repo, base = _repo(tmp_path); prepared = _prepare(repo,base,monkeypatch); (repo / "src/one.py").write_text("one\n"); monkeypatch.setenv("STUB_EXIT_PYTEST","1"); assert _settle(repo,base,prepared)["reason"] == "gate.regressed"; monkeypatch.delenv("STUB_EXIT_PYTEST") + repo2, base2 = _repo(tmp_path / "token"); prepared2 = _prepare(repo2,base2,monkeypatch); token = "gh"+"p_"+"A"*36; before = git(repo2,"rev-parse","HEAD"); (repo2 / "src/one.py").write_text(token); result = _settle(repo2,base2,prepared2); assert result["reason"] == "secret.detected" and token not in repr(result) and git(repo2,"rev-parse","HEAD") == before + repo3, base3 = _repo(tmp_path / "size"); (repo3 / SPEC_PATH).write_bytes(spec_bytes(cap=10)); prepared3 = _prepare(repo3,base3,monkeypatch); (repo3 / "src/one.py").write_text("x = "+"a"*100+"\n"); assert _settle(repo3,base3,prepared3)["reason"] == "size.exceeded" + +@pytest.mark.parametrize(("case","reason"),[("story","story_key.invalid"),("path","path.invalid"),("branch","branch.invalid"),("protected","branch.protected"),("base","base.invalid"),("cwd","cwd.mismatch"),("absent","spec.absent"),("unreadable","spec.unreadable"),("incomplete","spec.incomplete"),("units","units.invalid"),("gate","gate.unavailable")]) +def test_prepare_refusals_keep_tip(tmp_path, monkeypatch, case, reason): + repo, base = _repo(tmp_path / case); monkeypatch.chdir(repo); monkeypatch.setenv("PATH",stub_gate_tools(tmp_path / case)); monkeypatch.setenv("HOME",str(tmp_path / case / "home")); before = git(repo,"rev-parse","HEAD"); story,spec,branch,ref = STORY,SPEC_PATH,BRANCH,base + if case == "story": story = "BAD KEY" + elif case == "path": spec = "../outside.md" + elif case == "branch": branch = "Bad Branch" + elif case == "protected": branch = "main" + elif case == "base": ref = "missing-base" + elif case == "cwd": (tmp_path / case / "elsewhere").mkdir(); monkeypatch.chdir(tmp_path / case / "elsewhere") + elif case == "absent": (repo / spec).unlink() + elif case == "unreadable": (repo / spec).unlink(); (repo / spec).mkdir() + elif case == "incomplete": (repo / spec).write_bytes(b"unfinished") + elif case == "units": (repo / spec).write_bytes(spec_bytes([{"id":"bad id","paths":["src/one.py"],"subject":"feat: bad"}])) else: - original = implement_tools.resolve_executable - monkeypatch.setattr( - implement_tools, - "resolve_executable", - lambda name: None if name == "ruff" else original(name), - ) - result = profile_implement_prepare(str(repo), story, spec, branch, base_ref) - assert result["reason"] == reason - assert git(repo, "rev-parse", "HEAD") == before - - -def test_checkout_failure_and_prepare_failure_are_recorded( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - repo, base = _repo(tmp_path) - prepared = _prepare(repo, base, monkeypatch) - assert prepared["implement"] is True - monkeypatch.chdir(repo) - original = implement_tools.git_run - - def fail_switch(repo_path: Path, *args: str, **kwargs: object) -> object: - if args[:2] == ("switch", "-q"): - return type("Result", (), {"returncode": 1, "stdout": b""})() - return original(repo_path, *args, **kwargs) - - monkeypatch.setattr(implement_tools, "git_run", fail_switch) - failed = profile_implement_prepare(str(repo), STORY, SPEC_PATH, "feat/other", base) - assert failed["reason"] == "checkout.failed" - monkeypatch.setattr(implement_tools, "git_run", original) - monkeypatch.setattr( - implement_tools, - "load_config", - lambda: (_ for _ in ()).throw(implement_tools.ProfileError("x", "x")), - ) - prepared_failed = profile_implement_prepare( - str(repo), STORY, SPEC_PATH, BRANCH, base - ) - assert prepared_failed["reason"] == "prepare.failed" - assert git(repo, "rev-parse", "HEAD") == base - - -def test_settle_rejects_forged_prepare_and_changed_spec( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - repo, base = _repo(tmp_path) - prepared = _prepare(repo, base, monkeypatch) - before = git(repo, "rev-parse", "HEAD") - forged = dict(prepared) - forged["unit_id"] = "u2" - mismatch = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, forged, agent={} - ) - assert mismatch["reason"] == "prepare.mismatch" - (repo / SPEC_PATH).write_bytes(spec_bytes(cap=63999)) - changed = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} - ) - assert changed["reason"] == "spec.changed" - assert git(repo, "rev-parse", "HEAD") == before - - -def test_base_red_gate_is_advisory_and_commit_failure_is_atomic( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - repo, base = _repo(tmp_path / "red") - monkeypatch.setenv("STUB_EXIT_PYTEST", "1") - prepared = _prepare(repo, base, monkeypatch) - (repo / "src" / "one.py").write_text("one\n") - result = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} - ) - assert result["reason"] == "unit.committed" - - repo2, base2 = _repo(tmp_path / "hook") - hook = repo2 / ".git" / "hooks" / "pre-commit" - hook.write_text("#!/bin/sh\nexit 1\n") - hook.chmod(0o755) - prepared2 = _prepare(repo2, base2, monkeypatch) - (repo2 / "src" / "one.py").write_text("one\n") - failed = profile_implement_settle( - str(repo2), STORY, SPEC_PATH, BRANCH, base2, prepared2, agent={} - ) - assert failed["reason"] == "commit.failed" - assert git(repo2, "rev-parse", "HEAD") == base2 - - -def test_commit_changed_is_detected_after_hook_rewrites_index( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - repo, base = _repo(tmp_path) - hook = repo / ".git" / "hooks" / "pre-commit" - hook.write_text("#!/bin/sh\nprintf altered > src/one.py\ngit add src/one.py\n") - hook.chmod(0o755) - prepared = _prepare(repo, base, monkeypatch) - (repo / "src" / "one.py").write_text("one\n") - result = profile_implement_settle( - str(repo), STORY, SPEC_PATH, BRANCH, base, prepared, agent={} - ) - assert result["reason"] == "commit.changed" - assert git(repo, "rev-parse", "HEAD") != base + original = implement_tools.resolve_executable; monkeypatch.setattr(implement_tools,"resolve_executable",lambda name: None if name == "ruff" else original(name)) + assert profile_implement_prepare(str(repo),story,spec,branch,ref)["reason"] == reason and git(repo,"rev-parse","HEAD") == before + +def test_checkout_and_prepare_failure(tmp_path, monkeypatch): + repo, base = _repo(tmp_path); _prepare(repo,base,monkeypatch); original = implement_tools.git_run + def fail(repo_path, *args, **kwargs): return type("R",(),{"returncode":1,"stdout":b""})() if args[:2] == ("switch","-q") else original(repo_path,*args,**kwargs) + monkeypatch.setattr(implement_tools,"git_run",fail); assert profile_implement_prepare(str(repo),STORY,SPEC_PATH,"feat/other",base)["reason"] == "checkout.failed"; monkeypatch.setattr(implement_tools,"git_run",original) + monkeypatch.setattr(implement_tools,"load_config",lambda: (_ for _ in ()).throw(implement_tools.ProfileError("x","x"))); assert profile_implement_prepare(str(repo),STORY,SPEC_PATH,BRANCH,base)["reason"] == "prepare.failed"; assert git(repo,"rev-parse","HEAD") == base + +def test_forged_prepare_and_changed_spec(tmp_path, monkeypatch): + repo, base = _repo(tmp_path); prepared = _prepare(repo,base,monkeypatch); forged = dict(prepared); forged["unit_id"] = "u2"; assert _settle(repo,base,forged)["reason"] == "prepare.mismatch"; (repo / SPEC_PATH).write_bytes(spec_bytes(cap=63999)); assert _settle(repo,base,prepared)["reason"] == "spec.changed" + +def test_base_red_hook_and_commit_changed(tmp_path, monkeypatch): + repo, base = _repo(tmp_path / "red"); monkeypatch.setenv("STUB_EXIT_PYTEST","1"); prepared = _prepare(repo,base,monkeypatch); (repo / "src/one.py").write_text("one\n"); assert _settle(repo,base,prepared)["reason"] == "unit.committed"; monkeypatch.delenv("STUB_EXIT_PYTEST") + repo2, base2 = _repo(tmp_path / "hook"); hook = repo2 / ".git/hooks/pre-commit"; hook.write_text("#!/bin/sh\nexit 1\n"); hook.chmod(0o755); prepared2 = _prepare(repo2,base2,monkeypatch); (repo2 / "src/one.py").write_text("one\n"); assert _settle(repo2,base2,prepared2)["reason"] == "commit.failed" and git(repo2,"rev-parse","HEAD") == base2 + repo3, base3 = _repo(tmp_path / "changed"); hook = repo3 / ".git/hooks/commit-msg"; hook.write_text("#!/bin/sh\nhead -n1 \"$1\" > \"$1.x\" && mv \"$1.x\" \"$1\"\n"); hook.chmod(0o755); prepared3 = _prepare(repo3,base3,monkeypatch); (repo3 / "src/one.py").write_text("one\n"); assert _settle(repo3,base3,prepared3)["reason"] == "commit.changed" + +def test_changed_paths_and_gate_rewrite(tmp_path, monkeypatch): + spec = "src/spec.md"; units = [{"id":"u1","paths":["src","tests/test_one.py"],"subject":"feat: one"}]; repo, base = _repo(tmp_path,units,spec,False); prepared = _prepare(repo,base,monkeypatch,spec); (repo / "src/one.py").write_text("one\n"); result = _settle(repo,base,prepared,spec); assert result["reason"] == "unit.committed" and git(repo,"show","--name-only","--format=","HEAD").split() == ["src/one.py"] and "Story-Key: "+STORY in git(repo,"show","-s","--format=%B","HEAD") + repo2, base2 = _repo(tmp_path / "gate"); prepared2 = _prepare(repo2,base2,monkeypatch); gate = Path(os.environ["PATH"].split(os.pathsep)[0]) / "ruff"; gate.write_text("#!/usr/bin/env python3\nfrom pathlib import Path\nPath('src/one.py').write_text('rewritten ghp_' + 'B' * 36)\n"); gate.chmod(0o755); (repo2 / "src/one.py").write_text("one\n"); assert _settle(repo2,base2,prepared2)["reason"] == "gate.changed_tree" and git(repo2,"rev-parse","HEAD") == base2 + +def test_size_baseline_and_invalid_branches(tmp_path, monkeypatch): + repo, base = _repo(tmp_path / "measure"); prepared = _prepare(repo,base,monkeypatch); (repo / "src/one.py").write_text("x = "+"a"*100+"\n"); measured = _settle(repo,base,prepared); repo2, base2 = _repo(tmp_path / "cap"); (repo2 / SPEC_PATH).write_bytes(spec_bytes(cap=measured["refs"]["diff_bytes"]-1)); prepared2 = _prepare(repo2,base2,monkeypatch); (repo2 / "src/one.py").write_text("x = "+"a"*100+"\n"); assert _settle(repo2,base2,prepared2)["reason"] == "size.exceeded" + for branch in ("feat/x.lock","feat/.x"): + repo3, base3 = _repo(tmp_path / branch.replace("/","_")); monkeypatch.chdir(repo3); monkeypatch.setenv("PATH",stub_gate_tools(tmp_path)); assert profile_implement_prepare(str(repo3),STORY,SPEC_PATH,branch,base3)["reason"] == "branch.invalid" + repo4, base4 = _repo(tmp_path / "baseline"); prepared4 = _prepare(repo4,base4,monkeypatch); prepared4["baseline"] = [{"name":"wrong"}]; (repo4 / "src/one.py").write_text("one\n"); assert _settle(repo4,base4,prepared4)["reason"] == "prepare.mismatch" +# fmt: on diff --git a/kits/profile-dev-kit/tests/test_implement_workflow.py b/kits/profile-dev-kit/tests/test_implement_workflow.py index 5560f01..6e78685 100644 --- a/kits/profile-dev-kit/tests/test_implement_workflow.py +++ b/kits/profile-dev-kit/tests/test_implement_workflow.py @@ -4,7 +4,6 @@ import asyncio import json -import os import subprocess from pathlib import Path from typing import Any @@ -20,6 +19,8 @@ from beddel.error_codes import AGENT_EXECUTION_FAILED from beddel.primitives import register_builtins from beddel.tools.kits import load_kit +from beddel_profile_dev._errors import ProfileError +from beddel_profile_dev.tools import implement as implement_tools from beddel_profile_dev.tools.stage_outcome import profile_record_stage_outcome from ._helpers import commit_all, git, init_repo, stub_gate_tools @@ -30,9 +31,15 @@ class FakeAgent: - def __init__(self, repo: Path, mode: str = "sequence") -> None: + def __init__( + self, + repo: Path, + mode: str = "sequence", + patch: pytest.MonkeyPatch | None = None, + ) -> None: self.repo = repo self.mode = mode + self.patch = patch self.calls = 0 async def execute( @@ -85,7 +92,8 @@ async def execute( (self.repo / "src" / target).write_text(f"{target}\n") if self.mode == "regression": (self.repo / "src" / "one.py").write_text("one\n") - os.environ["STUB_EXIT_PYTEST"] = "1" + if self.patch is not None: + self.patch.setenv("STUB_EXIT_PYTEST", "1") return AgentResult( exit_code=0, output="", @@ -195,14 +203,30 @@ def test_two_unit_sequence_records_and_resumes( monkeypatch.setenv("HOME", str(tmp_path / "home")) fake = FakeAgent(repo) first = _run(repo, base, fake) - assert first["step_results"]["settle"]["result"]["reason"] == "unit.committed" + first_result = first["step_results"]["settle"]["result"] + assert first_result["reason"] == "unit.committed" + assert first_result["refs"]["base"] == base + assert first_result["refs"]["commit"] == first_result["refs"]["head"] + assert (first_result["refs"]["completed"], first_result["refs"]["remaining"]) == ( + 1, + 1, + ) + assert git(repo, "show", "--name-only", "--format=", "HEAD").split() == [ + "src/one.py" + ] + assert "Implementation-Unit: u1" in git(repo, "show", "-s", "--format=%B", "HEAD") + assert fake.calls == 1 second = _run(repo, base, fake) - assert second["step_results"]["settle"]["result"]["reason"] == "unit.committed" + second_result = second["step_results"]["settle"]["result"] + assert second_result["reason"] == "unit.committed" + assert fake.calls == 2 + third_head = git(repo, "rev-parse", "HEAD") third = _run(repo, base, fake) - assert third["step_results"]["settle_stop"]["result"]["reason"] == "units.complete" + stop = third["step_results"]["settle_stop"]["result"] + assert stop["reason"] == "units.complete" + assert stop["outcome"] == "succeeded" assert fake.calls == 2 - records = Path.home() / ".config" / "beddel" - del records + assert git(repo, "rev-parse", "HEAD") == third_head stored = list((tmp_path / "home").rglob("*.json")) assert len(stored) == 3 assert sorted(json.loads(path.read_text())["record"] for path in stored) == [ @@ -230,15 +254,18 @@ def test_agent_modes_are_recorded_without_losing_base( monkeypatch.chdir(repo) monkeypatch.setenv("PATH", stub_gate_tools(tmp_path / mode)) monkeypatch.setenv("HOME", str(tmp_path / mode / "home")) - fake = FakeAgent(repo, mode) + fake = FakeAgent(repo, mode, monkeypatch) before = git(repo, "rev-parse", "HEAD") result = _run(repo, base, fake) settle = result["step_results"].get( "settle", result["step_results"].get("settle_stop") ) assert settle["result"]["reason"] == reason - if mode == "regression": - os.environ.pop("STUB_EXIT_PYTEST", None) + assert settle["result"]["outcome"] == "failed" + records = list((tmp_path / mode / "home").rglob("*.json")) + assert len(records) == 1 + stored = json.loads(records[0].read_text()) + assert (stored["outcome"], stored["reason"]) == ("failed", reason) assert git(repo, "rev-parse", "HEAD") == before or reason == "head.moved" @@ -259,3 +286,24 @@ def test_bad_repository_fails_at_record_boundary( str(bad), STORY, "implement", "failed", "prepare.failed", {} ) assert record_error.value.code == "PROFILE_REPOSITORY_INVALID" + + +def test_absorbed_prepare_error_records_prepare_failed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, base = _repo(tmp_path) + monkeypatch.chdir(repo) + monkeypatch.setenv("PATH", stub_gate_tools(tmp_path)) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + + def boom(_repo: Path) -> set[str]: + raise ProfileError("PROFILE_REPOSITORY_INVALID", "fixture") + + monkeypatch.setattr(implement_tools, "changed_paths", boom) + result = _run(repo, base, FakeAgent(repo)) + stop = result["step_results"]["settle_stop"]["result"] + assert (stop["outcome"], stop["reason"]) == ("failed", "prepare.failed") + records = list((tmp_path / "home").rglob("*.json")) + assert len(records) == 1 + stored = json.loads(records[0].read_text()) + assert (stored["outcome"], stored["reason"]) == ("failed", "prepare.failed") From 7f05d21608b14a98847b59c34efbe4fbd621af54 Mon Sep 17 00:00:00 2001 From: Carlos Bacelar Date: Tue, 10 Nov 2026 11:11:38 -0300 Subject: [PATCH 3/3] fix(profile-dev-kit): implement stage handles staged renames, self-referencing base and foreign trailers (Story 7.4 review round 2) Stages only paths that exist, refuses a base_ref that resolves to the feature branch, counts only units of the current spec, rejects .lock components and records an unborn HEAD as branch.moved. --- .../python/beddel_profile_dev/implement.py | 4 +- .../beddel_profile_dev/tools/implement.py | 112 +++++++----------- kits/profile-dev-kit/tests/test_implement.py | 8 +- 3 files changed, 51 insertions(+), 73 deletions(-) diff --git a/kits/profile-dev-kit/python/beddel_profile_dev/implement.py b/kits/profile-dev-kit/python/beddel_profile_dev/implement.py index df875f0..03489f7 100644 --- a/kits/profile-dev-kit/python/beddel_profile_dev/implement.py +++ b/kits/profile-dev-kit/python/beddel_profile_dev/implement.py @@ -104,8 +104,8 @@ def branch_reason(branch: object, base_ref: object) -> str | None: branch in PROTECTED_BRANCHES or branch == base_ref or branch.startswith("-") - or branch.endswith(("/", ".", ".lock")) - or any(part.startswith(".") for part in parts) + or branch.endswith(("/", ".")) + or any(p.startswith(".") or p.endswith(".lock") for p in parts) or ".." in branch or "//" in branch or "@{" in branch diff --git a/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py b/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py index fefcd5c..aaed37e 100644 --- a/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py +++ b/kits/profile-dev-kit/python/beddel_profile_dev/tools/implement.py @@ -173,6 +173,10 @@ def _git_text(result: Any) -> str | None: return result.stdout.decode("utf-8", "replace").strip() +def _repo_error() -> ProfileError: + return ProfileError("PROFILE_REPOSITORY_INVALID", "repository or revision invalid") + + def _symbolic_branch(repo: Path) -> str | None: value = _git_text(git_run(repo, "symbolic-ref", "-q", "HEAD")) return value.removeprefix("refs/heads/") if value is not None else None @@ -181,9 +185,7 @@ def _symbolic_branch(repo: Path) -> str | None: def _completed(repo: Path, base: str, story_key: str) -> set[str]: result = git_run(repo, "log", "-z", "--reverse", "--format=%H%n%B", f"{base}..HEAD") if result is None or result.returncode != 0: - raise ProfileError( - "PROFILE_REPOSITORY_INVALID", "repository or revision invalid" - ) + raise _repo_error() completed: set[str] = set() for raw in result.stdout.split(b"\x00"): if not raw: @@ -237,15 +239,10 @@ def _candidate_tree(repo: Path, paths: tuple[str, ...]) -> str: for args in (("read-tree", "HEAD"), ("add", "-A", "--", *paths)): result = git_run(repo, *args, index_file=index) if result is None or result.returncode != 0: - raise ProfileError( - "PROFILE_REPOSITORY_INVALID", "repository or revision invalid" - ) - result = git_run(repo, "write-tree", index_file=index) - value = _git_text(result) + raise _repo_error() + value = _git_text(git_run(repo, "write-tree", index_file=index)) if value is None: - raise ProfileError( - "PROFILE_REPOSITORY_INVALID", "repository or revision invalid" - ) + raise _repo_error() return value @@ -317,15 +314,16 @@ def profile_implement_prepare( base_sha = resolve_revision(repo, base) except ProfileError: return _refusal(story, "base.invalid", spec_path=spec, branch=branch_name) + symbolic = _git_text(git_run(repo, "rev-parse", "--symbolic-full-name", base)) + if symbolic == f"refs/heads/{branch_name}": + return _refusal(story, "branch.protected", spec_path=spec, branch=branch_name) if Path(os.path.realpath(os.getcwd())) != repo: return _refusal(story, "cwd.mismatch", spec_path=spec, branch=branch_name) data, error = _read_spec(repo, spec) - if error == "spec.absent": - return _refusal(story, error, spec_path=spec, branch=branch_name) if error is not None or data is None: - return _refusal( - story, error or "spec.unreadable", spec_path=spec, branch=branch_name - ) + reason = error if error == "spec.absent" else "spec.unreadable" + return _refusal(story, reason, spec_path=spec, branch=branch_name) + digest = hashlib.sha256(data).hexdigest() if not spec_complete(data, story): return _refusal(story, "spec.incomplete", spec_path=spec, branch=branch_name) units = spec_units(data, story) @@ -346,9 +344,7 @@ def profile_implement_prepare( ref = git_run(repo, "show-ref", "--verify", "--quiet", f"refs/heads/{branch_name}") if ref is None or ref.returncode not in (0, 1): - raise ProfileError( - "PROFILE_REPOSITORY_INVALID", "repository or revision invalid" - ) + raise _repo_error() if ref.returncode == 0: tip = resolve_revision(repo, f"refs/heads/{branch_name}") merge = git_run(repo, "merge-base", base_sha, tip) @@ -387,23 +383,26 @@ def profile_implement_prepare( ), ) head = resolve_revision(repo, "HEAD") - completed = _completed(repo, base_sha, story) + completed = _completed(repo, base_sha, story) & {u.id for u in units} remaining = [unit for unit in units if unit.id not in completed] + + def refs(**extra: Any) -> dict[str, Any]: + return _refs( + spec_path=spec, + spec_sha256=digest, + branch=branch_name, + base=base_sha, + head=head, + **extra, + ) + if not remaining: return _result( story, "succeeded", "units.complete", - _refs( - spec_path=spec, - spec_sha256=hashlib.sha256(data).hexdigest(), - branch=branch_name, - base=base_sha, - head=head, - completed=len(units), - remaining=0, - ), - spec_sha256=hashlib.sha256(data).hexdigest(), + refs(completed=len(units), remaining=0), + spec_sha256=digest, base=base_sha, head=head, ) @@ -411,48 +410,17 @@ def profile_implement_prepare( try: baseline = _run_gates(repo, config) except ProfileError: - return _failure( - story, - "prepare.failed", - _refs( - spec_path=spec, - spec_sha256=hashlib.sha256(data).hexdigest(), - branch=branch_name, - base=base_sha, - head=head, - unit=unit.id, - ), - ) + return _failure(story, "prepare.failed", refs(unit=unit.id)) if changed_paths(repo) - {spec}: - return _failure( - story, - "gate.changed_tree", - _refs( - spec_path=spec, - spec_sha256=hashlib.sha256(data).hexdigest(), - branch=branch_name, - base=base_sha, - head=head, - unit=unit.id, - ), - ) + return _failure(story, "gate.changed_tree", refs(unit=unit.id)) return _result( story, None, None, - _refs( - spec_path=spec, - spec_sha256=hashlib.sha256(data).hexdigest(), - branch=branch_name, - base=base_sha, - head=head, - unit=unit.id, - completed=len(completed), - remaining=len(remaining), - ), + refs(unit=unit.id, completed=len(completed), remaining=len(remaining)), ready=True, implement=True, - spec_sha256=hashlib.sha256(data).hexdigest(), + spec_sha256=digest, base=base_sha, head=head, unit_id=unit.id, @@ -497,8 +465,11 @@ def profile_implement_settle( if not isinstance(agent, Mapping): return _fail(story, "agent.failed", spec, branch=branch_name) base = prepare.get("base") - head = resolve_revision(repo, "HEAD") - if _symbolic_branch(repo) != branch_name: + try: + head: str | None = resolve_revision(repo, "HEAD") + except ProfileError: + head = None + if head is None or _symbolic_branch(repo) != branch_name: return _fail( story, "branch.moved", spec, branch=branch_name, base=base if isinstance(base, str) else None, head=head, @@ -588,8 +559,9 @@ def profile_implement_settle( unit.id, diff_bytes=diff_bytes, regressed=", ".join(regressed), ) subject, trailers = commit_message(unit, story) - committed = git_run(repo, "add", "-A", "--", *paths) - if committed is None or committed.returncode != 0: + present = [p for p in paths if os.path.lexists(repo / p)] + committed = git_run(repo, "add", "-A", "--", *present) if present else None + if present and (committed is None or committed.returncode != 0): return _fail( story, "commit.failed", spec, spec_digest, branch_name, base, head, unit.id, diff_bytes=diff_bytes, @@ -620,7 +592,7 @@ def profile_implement_settle( story, "commit.changed", spec, spec_digest, branch_name, base, new_head, unit.id, commit=new_head, diff_bytes=diff_bytes, ) - completed = _completed(repo, base, story) + completed = _completed(repo, base, story) & {u.id for u in units} if unit.id not in completed: return _fail( story, "commit.changed", spec, spec_digest, branch_name, base, new_head, diff --git a/kits/profile-dev-kit/tests/test_implement.py b/kits/profile-dev-kit/tests/test_implement.py index e61b930..1dd1756 100644 --- a/kits/profile-dev-kit/tests/test_implement.py +++ b/kits/profile-dev-kit/tests/test_implement.py @@ -49,7 +49,7 @@ def test_pure_unit_contract(): assert spec_units(spec_bytes(),STORY) == (Unit("u1",("src/one.py",),"feat(core): add one"),Unit("u2",("src/two.py",),"feat(core): add two")) assert spec_units(spec_bytes([{"id":"bad id","paths":["x"],"subject":"feat: x"}]),STORY) is None assert branch_reason("main","origin/main") == "branch.protected"; assert branch_reason("feat/x","feat/x") == "branch.protected" - assert branch_reason("../bad","main") == "branch.invalid"; assert branch_reason("feat/x","main") is None + assert branch_reason("../bad","main") == branch_reason("feat.lock/x","main") == "branch.invalid"; assert branch_reason("feat/x","main") is None assert covered(("src",),"src/a.py") and covered(("src/a.py",),"src/a.py") and not covered(("src/a.py",),"src/ab.py") subject, trailers = commit_message(Unit("u1",("x",),"feat: x"),STORY) assert subject == "feat: x" and trailer_unit(f"{subject}\n\n{trailers}\n",STORY) == "u1" @@ -114,4 +114,10 @@ def test_size_baseline_and_invalid_branches(tmp_path, monkeypatch): for branch in ("feat/x.lock","feat/.x"): repo3, base3 = _repo(tmp_path / branch.replace("/","_")); monkeypatch.chdir(repo3); monkeypatch.setenv("PATH",stub_gate_tools(tmp_path)); assert profile_implement_prepare(str(repo3),STORY,SPEC_PATH,branch,base3)["reason"] == "branch.invalid" repo4, base4 = _repo(tmp_path / "baseline"); prepared4 = _prepare(repo4,base4,monkeypatch); prepared4["baseline"] = [{"name":"wrong"}]; (repo4 / "src/one.py").write_text("one\n"); assert _settle(repo4,base4,prepared4)["reason"] == "prepare.mismatch" + +def test_rename_head_base_foreign_trailer_and_unborn_head(tmp_path, monkeypatch): + repo, base = _repo(tmp_path / "mv", [{"id":"u1","paths":["src"],"subject":"feat: one"}]); prepared = _prepare(repo,base,monkeypatch); git(repo,"mv","src/base.py","src/new.py"); assert _settle(repo,base,prepared)["reason"] == "unit.committed" + repo, base = _repo(tmp_path / "head"); prepared = _prepare(repo,"HEAD",monkeypatch); (repo / "src/one.py").write_text("one\n"); assert _settle(repo,"HEAD",prepared)["reason"] == "unit.committed"; assert _prepare(repo,"HEAD",monkeypatch)["reason"] == "branch.protected" + repo, base = _repo(tmp_path / "foreign"); git(repo,"switch","-q","-c",BRANCH); git(repo,"commit","-q","--allow-empty","-m","feat: x","-m",f"Story-Key: {STORY}\nImplementation-Unit: zz"); git(repo,"switch","-q","-"); assert _prepare(repo,base,monkeypatch)["refs"]["completed"] == 0 + repo, base = _repo(tmp_path / "orphan"); prepared = _prepare(repo,base,monkeypatch); git(repo,"switch","-q","--orphan","x"); assert _settle(repo,base,prepared)["reason"] == "branch.moved" # fmt: on