Files
roboco/tests/unit/services/test_git_worktree_routing_gaps.py
T
96401f4c10 feat(forge): Phases 2+2.1+3 — Gitea + GitLab providers, per-call routing, local-merge fallback (#575)
* feat(forge): Phase 2 — Gitea provider, per-call routing, host registry

Gitea support lands behind the Phase-1 seam:

- GiteaProvider (services/forge/gitea.py): Gitea v1 transport addressed
  by instance host (api base from the project's git_url). Where Gitea's
  wire contract diverges from GitHub's, the provider adapts responses
  back into the shapes GitService already classifies (ShapedResponse):
  `token` auth scheme, duplicate-PR 409→422 with the "already exists"
  text GitService keys on, commit statuses reshaped into check_runs /
  workflow_runs envelopes, APPROVE→APPROVED review mapping, Do-keyed
  POST merge, merge-method repo keys, label-color '#' prefix,
  client-side head/base PR filtering. Deliberate postures per the spec:
  zero-workflows fail-open (statuses-free repo → no_ci_configured) and
  merge_branch as a shaped 501 (env-sync cascade lands on missing_ref;
  the shared local-git fallback is Phase-2.1).
- ForgeRouter (services/forge/router.py): GitService._forge now routes
  per call from RepoRef.host — every existing call site unchanged in
  shape. RepoRef gains an optional host; _parse_git_url returns the
  host-stamped ref and it is threaded through GitService/release
  executor instead of being rebuilt from strings (helpers re-signatured
  to take RepoRef).
- Host registry (services/forge/registry.py): in-memory host→provider
  map, self-healing — ProjectService.get/get_by_slug re-register on
  every read; provider_for resolves gitea projects by git_url host.
- Registration validation now accepts git_provider="gitea"; GitLab
  remains recognized-but-rejected. Panel: the read-only Forge badge
  becomes a real picker (Auto-detect / GitHub-GHE / Gitea / GitLab
  disabled).

Plain git (clone/fetch/push) needs no changes — the Basic-auth
extraheader works on Gitea unchanged. Gates: mypy 392 files, xenon A,
full unit suite 6356 green, integration suite 2257 green.

* feat(forge): live-Gitea contract suite + scheme support + slash-safe refs

Hardening from running the provider against a real dockerized Gitea
1.22.6 (the spec's Phase-2 contract suite, now committed as the
env-gated tests/e2e_smoke/test_gitea_live.py — self-seeding: creates its
own repo, pushes real commits, and drives PR open → duplicate reshape →
list/filter → diff → review → labels → commit-status CI reshapes →
squash merge → branch delete → release, plus a live verification of the
x-access-token Basic-auth git-CLI claim).

Two real findings fixed:
- Branch refs weren't URL-encoded — every RoboCo branch carries slashes
  (feature/backend/...), and Gitea's router 404s on the extra path
  segments. list_ci_runs + delete_branch_ref now quote the ref
  (regression-pinned in the unit suite).
- The API base hardcoded https; a LAN instance serving plain http is a
  real deployment shape. GiteaProvider gains a scheme (recorded per host
  by the registry from the project's git_url).

ShapedResponse moves to forge/shaping.py (shared by the upcoming GitLab
transport, which needs its text override for diff reassembly).

* feat(forge): Phase 3 GitLab provider + Phase 2.1 local-merge fallback

GitLabProvider (services/forge/gitlab.py): GitLab v4 transport addressed
by host+scheme, subgroup-safe (the MR project path packs into
RepoRef.owner, URL-encoded per call). Adapters translate MR semantics
into the GitHub shapes GitService classifies: iid→number,
source/target_branch→head/base with a merged bool, per-file diffs
reassembled into unified-diff text (ShapedResponse text override,
3-page cap), approve-vs-note review routing (GitLab has no
request-changes verb), pipelines/statuses reshaped into
workflow_runs/check_runs, merge-method repo-key mapping, duplicate-MR
409→422. Reviewer mirroring is skipped (needs numeric ids RoboCo
doesn't store); provisioning stays Phase 4. gitlab.com now auto-detects
at registration like github.com; self-hosted GitLab sets the provider
explicitly (panel picker enabled).

Phase 2.1: neither Gitea nor GitLab has GitHub's server-side merges
API — their merge_branch returns a shaped 501 and
GitService.sync_env_branch now runs the shared local-git fallback
(_local_merge_branch: throwaway clone → ancestor check → merge → push;
a conflict aborts with the remote untouched; same status vocabulary as
the merges-API path).

Also aligns the whole tree with the full gate's tests/-scoped mypy
(provider-test responder typing, e2e_smoke's stale owner/repo shapes).
Gates: mypy 1229 files clean, xenon A, unit suite 6393 green, forge
suites 85 green, panel typecheck/lint clean.

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-07-19 08:12:34 +02:00

180 lines
6.3 KiB
Python

"""Rebase + conventions validator run in the per-task worktree, not the clone.
F123 gap: Phase B routed ``create_branch`` + ``commit`` to the worktree but
missed two cwd-dependent git ops that still resolved the clone root:
1. ``rebase_onto_base`` (called by ``sync_task_branch`` + ``rebase_pr_for_task``)
does ``git checkout <head>`` + ``git reset --hard origin/<head>`` in the
resolved workspace. Post-F123 the branch is checked out in the linked
worktree, so a ``checkout`` in the clone root is refused ("already checked
out at '<worktree>'") — the behind-base recovery loop + PM wedged-PR rebase
are dead on arrival.
2. ``conventions_check_for_task`` runs the validator with ``--root <clone
root>``; the validator reads ``(root/rel).read_bytes()`` — default-branch
content, not the dev's worktree changes. Newly-added files are absent from
the clone root → false pass; modified files are analyzed at stale content.
Both fix the same way: resolve the worktree via ``_worktree_for_task(clone_root,
task.id)`` + ``_ensure_worktree_for_commit`` and run the op there.
"""
from __future__ import annotations
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
from uuid import UUID, uuid4
import pytest
from roboco.services.forge import RepoRef
from roboco.services.git import GitService
def _service() -> GitService:
svc = GitService.__new__(GitService)
svc.log = MagicMock()
svc.session = MagicMock()
return svc
def _task(*, branch: str, task_id: UUID | None = None) -> MagicMock:
return MagicMock(
id=task_id or uuid4(),
project_id=uuid4(),
branch_name=branch,
assigned_to=uuid4(),
)
# --- rebase: sync_task_branch + rebase_pr_for_task route to the worktree ---
def _stub_rebase_common(svc: GitService, clone: Path) -> dict[str, list[Path]]:
object.__setattr__(
svc, "_project_for_task", AsyncMock(return_value=MagicMock(slug="roboco-api"))
)
object.__setattr__(
svc, "_resolve_workspace_agent_id", MagicMock(return_value=uuid4())
)
object.__setattr__(svc, "get_workspace", AsyncMock(return_value=clone))
object.__setattr__(
svc, "_get_project_token_or_raise", AsyncMock(return_value="tok")
)
object.__setattr__(svc, "_ensure_worktree_for_commit", AsyncMock())
cwds: list[Path] = []
async def _run_git(workspace: Path, args: list[str], **_kw: object) -> object:
cwds.append(Path(workspace))
if args[:1] == ["rev-list"]:
return MagicMock(stdout="0\n", returncode=0)
return MagicMock(stdout="", returncode=0)
object.__setattr__(svc, "_run_git", AsyncMock(side_effect=_run_git))
return {"cwds": cwds}
@pytest.mark.asyncio
async def test_sync_task_branch_rebases_in_worktree_not_clone() -> None:
svc = _service()
task_id = uuid4()
short = str(task_id)[:8]
clone = Path("/tmp/ws")
worktree = clone / ".worktrees" / short
task = _task(branch="feature/backend/abc12345", task_id=task_id)
state = _stub_rebase_common(svc, clone)
await svc.sync_task_branch(task, base_branch="master")
ensure = object.__getattribute__(svc, "_ensure_worktree_for_commit")
ensure.assert_awaited_once()
args = ensure.await_args.args
assert args[0] == clone, "ensure must target the clone root"
assert args[1] == worktree, (
f"ensure must target the worktree {worktree}; got {args[1]}"
)
assert args[2] == "feature/backend/abc12345"
assert state["cwds"], "rebase git ops must run"
assert all(c == worktree for c in state["cwds"]), (
f"all rebase git ops must run in the worktree {worktree}; got {state['cwds']}"
)
@pytest.mark.asyncio
async def test_rebase_pr_for_task_rebases_in_worktree_not_clone() -> None:
svc = _service()
task_id = uuid4()
short = str(task_id)[:8]
clone = Path("/tmp/ws")
worktree = clone / ".worktrees" / short
task = _task(branch="feature/backend/abc12345", task_id=task_id)
state = _stub_rebase_common(svc, clone)
object.__setattr__(
svc, "_parse_github_remote", MagicMock(return_value=RepoRef("owner", "repo"))
)
object.__setattr__(
svc,
"_get_pr_refs",
AsyncMock(return_value=("feature/backend/abc12345", "master")),
)
# rebase_pr_for_task loads the task from the DB by (pr_number, project_id).
session = MagicMock()
result = MagicMock()
result.scalar_one_or_none.return_value = task
session.execute = AsyncMock(return_value=result)
svc.session = session
await svc.rebase_pr_for_task(pr_number=42, project_id=uuid4())
ensure = object.__getattribute__(svc, "_ensure_worktree_for_commit")
ensure.assert_awaited_once()
assert ensure.await_args.args[1] == worktree
assert state["cwds"], "rebase git ops must run"
assert all(c == worktree for c in state["cwds"]), (
f"all rebase git ops must run in the worktree {worktree}; got {state['cwds']}"
)
# --- conventions: validator --root points at the worktree, not the clone ---
@pytest.mark.asyncio
async def test_conventions_check_runs_validator_in_worktree_not_clone() -> None:
svc = _service()
task_id = uuid4()
short = str(task_id)[:8]
clone = Path("/tmp/ws")
worktree = clone / ".worktrees" / short
task = _task(branch="feature/backend/abc12345", task_id=task_id)
object.__setattr__(svc, "_workspace_for_branch", AsyncMock(return_value=clone))
object.__setattr__(
svc, "list_changed_files", AsyncMock(return_value=["src/foo.py"])
)
object.__setattr__(svc, "_ensure_worktree_for_commit", AsyncMock())
captured: list[Path] = []
async def _capture_validator(
workspace: Path, _files: list[str]
) -> dict[str, object]:
captured.append(Path(workspace))
return {"findings": [], "could_not_run": False}
object.__setattr__(
svc, "_run_conventions_validator", AsyncMock(side_effect=_capture_validator)
)
await svc.conventions_check_for_task(actor_agent_id=uuid4(), task=task)
ensure = object.__getattribute__(svc, "_ensure_worktree_for_commit")
ensure.assert_awaited_once()
assert ensure.await_args.args[1] == worktree
assert captured, "validator must run"
assert captured[0] == worktree, (
f"validator --root must be the worktree {worktree}, not the clone root; "
f"got {captured[0]}"
)