Skip to content
4 changes: 3 additions & 1 deletion core/skills/implement/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ As an unattended worker, follow [the worker role's blocker route](../../../docs/

Before the first code edit, record observable criteria in task Acceptance and
freeze them. Change Acceptance only with a recorded reason in Notes, before
implementing the change. For changes touching guards, auth, permissions,
implementing the change. For an authorized retarget, make `.loopzero/task.md`
and the PR description agree on Acceptance before the next review.
For changes touching guards, auth, permissions,
sessions, secrets or trust boundaries, record a short design pass in Notes
before the first code edit: threats, invariants and chosen approach.
When deduplicating tests, list their distinct assertions before editing,
Expand Down
3 changes: 3 additions & 0 deletions core/skills/resolve-findings/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ Fix valid blocking findings within commissioned scope or hand off bounded repair
and validation through [response handoff](reference.md#response-handoff).
Explain repaired, inapplicable or unsupported findings in-thread with verified
evidence using `loopzero resolve`; never resolve silently. Suggestions are optional.
If a finding cites outdated acceptance, verify the authorized criteria against
the current head and resolve the mistaken premise with that evidence. Use the
existing review budget if the changed head still needs review.
Requester-reserved, irreversible or acceptance/scope/cost changes and external
commitments require direction.

Expand Down
49 changes: 32 additions & 17 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,37 @@ def _ensure_excludes(repo_root: Path) -> None:
return


def _fetch_base(repo_root: Path, base_branch: str) -> str:
remote_ref, tracking = f"refs/heads/{base_branch}", f"refs/remotes/origin/{base_branch}"
try:
valid = run(("git", "check-ref-format", remote_ref), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30)
symbolic = run(("git", "symbolic-ref", "-q", tracking), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30)
modules = repo_root / _git(repo_root, "rev-parse", "--git-path", "modules", preserve_whitespace=True)
if valid.exit_code == 0 and symbolic.exit_code == 1 and not modules.exists():
fetch = ("git", "fetch", "--porcelain", "--verbose", "--no-tags", "--no-prune",
"--no-write-fetch-head", "--refmap=", "origin", f"+{remote_ref}:{tracking}")
result = run(fetch, cwd=repo_root, env_allowlist=GIT_ENV, timeout=120)
if result.exit_code != 129: # Older Git does not accept --porcelain.
row = result.stdout.removesuffix("\n").rsplit(" ", 2)
if result.exit_code or len(row) != 3 or row[-1] != tracking:
raise GitError(fetch, result.stderr or result.stdout or f"origin did not report {remote_ref}")
return row[1]
lookup = ("ls-remote", "--refs", "origin", remote_ref)
base, _, ref = _git(repo_root, *lookup).partition("\t")
if ref != remote_ref:
raise GitError(("git", *lookup), f"origin did not report a unique {remote_ref}")
_git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base)
_git(repo_root, "update-ref", "--no-deref", tracking, base)
return base
except GitError:
if "origin" in _git(repo_root, "remote").splitlines():
raise
raise WorktreeError(
"no Git remote named 'origin'. Add it with `git remote add origin <url>` using the URL for the "
"repository in `[repo] name`, or rename that remote with `git remote rename <name> origin`."
) from None


def start(repo_root: Path, slug: str, base_branch: str) -> Path:
"""Create a task worktree or finish initializing an interrupted start."""
repo_root = Path(repo_root)
Expand All @@ -228,23 +259,7 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path:
raise WorktreeError(refusal)
if not existing and _branch_exists(repo_root, branch):
raise WorktreeError(f"branch already exists: {branch}")
remote_ref = f"refs/heads/{base_branch}"
lookup = ("ls-remote", "--refs", "origin", remote_ref)
try:
advertised = _git(repo_root, *lookup)
base, _, ref = advertised.partition("\t")
if ref != remote_ref:
raise GitError(("git", *lookup), f"origin did not report a unique {remote_ref}")
_git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base)
except GitError:
if "origin" not in _git(repo_root, "remote").splitlines():
raise WorktreeError(
"no Git remote named 'origin'. Add it with `git remote add origin <url>` "
"using the URL for the repository in `[repo] name`, or rename that remote "
"with `git remote rename <name> origin`."
) from None
raise
_git(repo_root, "update-ref", "--no-deref", f"refs/remotes/origin/{base_branch}", base)
base = _fetch_base(repo_root, base_branch)
if existing:
existing_head = _resumable_head(repo_root, wt, branch)
if existing_head is None:
Expand Down
21 changes: 12 additions & 9 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,27 +51,29 @@ def test_branch_reads_valid_names_and_rejects_detached_head(repo: Path, slug: st
worktree.branch(repo)


@pytest.mark.parametrize("branch", [None, "feature/ci+release", "symbolic"])
@pytest.mark.parametrize("branch", [None, "feature/ci+release", "symbolic", "legacy"])
def test_start_creates_branch_worktree_and_task_file(repo: Path, branch: str | None, monkeypatch) -> None:
side = branch or "side"
git(repo, "push", "-q", "origin", f"HEAD:refs/heads/{side}")
upstream = commit_on_origin(repo, "feature.txt")
if branch == "symbolic":
git(repo, "symbolic-ref", "refs/remotes/origin/main", "refs/heads/main")
elif branch:
elif branch and branch != "legacy":
checkout = repo.parent / "single-branch"
origin = (repo.parent / "origin.git").as_uri()
git(repo, "clone", "-q", "--single-branch", "--branch", branch, origin, str(checkout))
assert not git(checkout, "for-each-ref", "refs/heads/main", "refs/remotes/origin/main").strip()
repo = checkout
invoke, local_head = worktree._git, worktree.head(repo)
def interleave(path, *args, **kwargs):
result = invoke(path, *args, **kwargs)
if args[0] == "fetch":
git(path, "fetch", "-q", "origin", f"refs/heads/{side}")
invoke, local_head = worktree.run, worktree.head(repo)
def interleave(argv, **kwargs):
if branch == "legacy" and argv[:3] == ("git", "fetch", "--porcelain"):
return invoke(("git", "fetch", "--loopzero-unsupported"), **kwargs)
result = invoke(argv, **kwargs)
if argv[1] == "fetch" and result.exit_code == 0:
git(kwargs["cwd"], "fetch", "-q", "origin", f"refs/heads/{side}")
return result

monkeypatch.setattr(worktree, "_git", interleave)
monkeypatch.setattr(worktree, "run", interleave)
wt = worktree.start(repo, "my-task", "main")
assert wt == repo / ".worktrees" / "my-task"
assert (wt / "feature.txt").exists(), "fetched origin/main before branching"
Expand Down Expand Up @@ -200,7 +202,8 @@ def test_start_explains_missing_origin(repo: Path, change: tuple[str, ...]) -> N
def test_start_reports_git_failure_with_command(repo: Path) -> None:
with pytest.raises(worktree.GitError) as info:
worktree.start(repo, "nobase", "does-not-exist")
assert info.value.command[:2] == ("git", "ls-remote")
assert info.value.command[0] == "git"
assert info.value.command[1] in {"fetch", "ls-remote"}
assert info.value.tail


Expand Down
Loading