mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
* 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>
178 lines
5.5 KiB
Python
178 lines
5.5 KiB
Python
"""GitService.open_conventions_pr commits the file locally; PR is best-effort."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import subprocess
|
|
from typing import TYPE_CHECKING, Any
|
|
from unittest.mock import AsyncMock
|
|
from uuid import uuid4
|
|
|
|
from roboco.config import settings
|
|
from roboco.db.tables import AgentTable, ProjectTable
|
|
from roboco.models import AgentRole, AgentStatus, Team
|
|
from roboco.services.forge import RepoRef
|
|
from roboco.services.git import _ConventionsPr, get_git_service
|
|
|
|
if TYPE_CHECKING:
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
_SCAFFOLD_BRANCH = "chore/roboco-conventions-scaffold"
|
|
|
|
|
|
def _git(repo: Path, *args: str) -> None:
|
|
subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True)
|
|
|
|
|
|
async def _seed_project(
|
|
db: AsyncSession, workspace_path: str, *, slug: str | None = None
|
|
) -> ProjectTable:
|
|
agent = AgentTable(
|
|
id=uuid4(),
|
|
name="Dev",
|
|
slug=f"be-dev-{uuid4().hex[:8]}",
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
status=AgentStatus.ACTIVE,
|
|
model_config={},
|
|
system_prompt="dev",
|
|
capabilities=[],
|
|
permissions={},
|
|
metrics={},
|
|
)
|
|
db.add(agent)
|
|
await db.flush()
|
|
project = ProjectTable(
|
|
id=uuid4(),
|
|
name="G-Proj",
|
|
slug=slug or f"g-proj-{uuid4().hex[:8]}",
|
|
git_url="https://example.com/r.git",
|
|
default_branch="master",
|
|
assigned_cell=Team.BACKEND,
|
|
created_by=agent.id,
|
|
workspace_path=workspace_path,
|
|
)
|
|
db.add(project)
|
|
await db.flush()
|
|
return project
|
|
|
|
|
|
async def test_open_conventions_pr_commits_locally_without_remote(
|
|
db_session: AsyncSession, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
# open_conventions_pr only accepts a workspace_path under
|
|
# {workspaces_root}/{slug} (the containment guard), so anchor the root at
|
|
# the test dir and place the repo under the project's own slug.
|
|
monkeypatch.setattr(settings, "workspaces_root", str(tmp_path))
|
|
slug = f"g-proj-{uuid4().hex[:8]}"
|
|
repo = tmp_path / slug / "repo"
|
|
repo.mkdir(parents=True)
|
|
_git(repo, "init", "-b", "master")
|
|
_git(repo, "config", "user.email", "t@example.com")
|
|
_git(repo, "config", "user.name", "T")
|
|
_git(repo, "config", "commit.gpgsign", "false")
|
|
(repo / "README.md").write_text("# r\n")
|
|
_git(repo, "add", "README.md")
|
|
_git(repo, "commit", "-m", "init")
|
|
|
|
project = await _seed_project(db_session, str(repo), slug=slug)
|
|
git = get_git_service(db_session)
|
|
result = await git.open_conventions_pr(
|
|
project.slug,
|
|
content="version: 1\n",
|
|
title="scaffold",
|
|
body="b",
|
|
)
|
|
|
|
assert result is not None
|
|
assert result["pr_number"] is None # no git token / remote → PR not opened
|
|
show = subprocess.run(
|
|
["git", "show", f"{_SCAFFOLD_BRANCH}:.roboco/conventions.yml"],
|
|
cwd=repo,
|
|
capture_output=True,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
assert show.returncode == 0
|
|
assert show.stdout == "version: 1\n"
|
|
|
|
|
|
async def test_open_conventions_pr_returns_none_without_workspace(
|
|
db_session: AsyncSession, tmp_path: Path
|
|
) -> None:
|
|
project = await _seed_project(db_session, str(tmp_path / "does-not-exist"))
|
|
git = get_git_service(db_session)
|
|
result = await git.open_conventions_pr(
|
|
project.slug,
|
|
content="version: 1\n",
|
|
title="t",
|
|
body="b",
|
|
)
|
|
assert result is None
|
|
|
|
|
|
async def test_open_conventions_pr_force_pushes_scaffold_branch(
|
|
db_session: AsyncSession, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
# Second call: scaffold branch already on remote (non-fast-forward).
|
|
# Must force-push (force=True) and return a real pr_number, not the
|
|
# unopened {"pr_number": None} dict.
|
|
repo = tmp_path / "repo"
|
|
repo.mkdir()
|
|
_git(repo, "init", "-b", "master")
|
|
_git(repo, "config", "user.email", "t@example.com")
|
|
_git(repo, "config", "user.name", "T")
|
|
_git(repo, "config", "commit.gpgsign", "false")
|
|
(repo / "README.md").write_text("# r\n")
|
|
_git(repo, "add", "README.md")
|
|
_git(repo, "commit", "-m", "init")
|
|
|
|
project = await _seed_project(db_session, str(repo))
|
|
git = get_git_service(db_session)
|
|
|
|
pushed: list[bool] = []
|
|
|
|
async def _fake_push(
|
|
_workspace: Any, force: bool = False, _branch: str | None = None
|
|
) -> tuple[str, int]:
|
|
pushed.append(force)
|
|
return (_SCAFFOLD_BRANCH, 1)
|
|
|
|
async def _fake_token(_slug: str) -> str:
|
|
return "tok"
|
|
|
|
monkeypatch.setattr(git, "_token_for_project", _fake_token)
|
|
monkeypatch.setattr(git, "push", _fake_push)
|
|
monkeypatch.setattr(
|
|
git, "_parse_github_remote", lambda _ws: RepoRef("owner", "repo")
|
|
)
|
|
|
|
_pr_number = 42
|
|
_pr_url = "https://github.com/owner/repo/pull/42"
|
|
|
|
class _Resp:
|
|
is_success = True
|
|
|
|
def json(self) -> dict[str, object]:
|
|
return {"number": _pr_number, "html_url": _pr_url}
|
|
|
|
async def _fake_post_pr(_repo_ref: RepoRef, _token: str, _body: Any) -> _Resp:
|
|
return _Resp()
|
|
|
|
monkeypatch.setattr(git, "_post_pr", _fake_post_pr)
|
|
monkeypatch.setattr(git, "_apply_pr_labels", AsyncMock())
|
|
|
|
spec = _ConventionsPr(
|
|
content="version: 1\n",
|
|
branch=_SCAFFOLD_BRANCH,
|
|
title="scaffold",
|
|
body="b",
|
|
)
|
|
result = await git._push_and_open_conventions_pr(project.slug, repo, "master", spec)
|
|
|
|
assert pushed == [True], "second call must force-push (force=True)"
|
|
assert result["pr_number"] == _pr_number
|
|
assert result["pr_url"] == _pr_url
|