Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab4af23afd | ||
|
|
c2330e3929 | ||
|
|
ea471542da |
@@ -7,11 +7,8 @@ project's ``branches/`` directory, never from the stable control checkout.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import subprocess
|
|
||||||
|
|
||||||
BASE_BRANCHES = frozenset({"master", "main", "dev"})
|
BASE_BRANCHES = frozenset({"master", "main", "dev"})
|
||||||
ACTIVE_WORKTREE_ENV = "GITEA_ACTIVE_WORKTREE"
|
|
||||||
AUTHOR_WORKTREE_ENV = "GITEA_AUTHOR_WORKTREE"
|
|
||||||
|
|
||||||
|
|
||||||
def _normalize_path(path: str) -> str:
|
def _normalize_path(path: str) -> str:
|
||||||
@@ -51,130 +48,6 @@ def resolve_mutation_workspace(
|
|||||||
return os.path.realpath(project_root)
|
return os.path.realpath(project_root)
|
||||||
|
|
||||||
|
|
||||||
def _realpath_git_common_dir(workspace_path: str, common_dir: str) -> str:
|
|
||||||
"""Resolve ``git rev-parse --git-common-dir`` relative to *workspace_path*."""
|
|
||||||
raw = (common_dir or "").strip()
|
|
||||||
if not raw:
|
|
||||||
return raw
|
|
||||||
if os.path.isabs(raw):
|
|
||||||
return os.path.realpath(raw)
|
|
||||||
return os.path.realpath(os.path.join(workspace_path, raw))
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_canonical_repo_root(workspace_path: str, fallback_project_root: str) -> str:
|
|
||||||
"""Return the stable repository root for *workspace_path* via git metadata (#460)."""
|
|
||||||
path = (workspace_path or "").strip()
|
|
||||||
fallback = os.path.realpath(fallback_project_root)
|
|
||||||
if not path:
|
|
||||||
return fallback
|
|
||||||
try:
|
|
||||||
res = subprocess.run(
|
|
||||||
["git", "-C", path, "rev-parse", "--git-common-dir"],
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
check=True,
|
|
||||||
)
|
|
||||||
common = _realpath_git_common_dir(path, res.stdout)
|
|
||||||
except Exception:
|
|
||||||
return fallback
|
|
||||||
if common.endswith(f"{os.sep}.git"):
|
|
||||||
return os.path.dirname(common)
|
|
||||||
if os.path.basename(common) == ".git":
|
|
||||||
return os.path.dirname(common)
|
|
||||||
return fallback
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_author_mutation_context(
|
|
||||||
worktree_path: str | None,
|
|
||||||
process_project_root: str,
|
|
||||||
*,
|
|
||||||
active_worktree_env: str | None = None,
|
|
||||||
author_worktree_env: str | None = None,
|
|
||||||
) -> dict:
|
|
||||||
"""Shared workspace resolution for runtime_context and mutation guards (#460)."""
|
|
||||||
workspace = resolve_mutation_workspace(
|
|
||||||
worktree_path,
|
|
||||||
process_project_root,
|
|
||||||
active_worktree_env=active_worktree_env,
|
|
||||||
author_worktree_env=author_worktree_env,
|
|
||||||
)
|
|
||||||
process_root = os.path.realpath(process_project_root)
|
|
||||||
# Canonical repository identity comes from the MCP process checkout (#460),
|
|
||||||
# not from the declared task workspace being validated.
|
|
||||||
canonical_root = resolve_canonical_repo_root(process_root, process_root)
|
|
||||||
return {
|
|
||||||
"workspace_path": workspace,
|
|
||||||
"process_project_root": process_root,
|
|
||||||
"canonical_repo_root": canonical_root,
|
|
||||||
"roots_aligned": canonical_root == process_root,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def assess_workspace_repo_membership(
|
|
||||||
*,
|
|
||||||
workspace_path: str,
|
|
||||||
canonical_repo_root: str,
|
|
||||||
) -> dict:
|
|
||||||
"""Fail closed when *workspace_path* is not a git worktree of *canonical_repo_root*."""
|
|
||||||
workspace = os.path.realpath(workspace_path)
|
|
||||||
root = os.path.realpath(canonical_repo_root)
|
|
||||||
reasons: list[str] = []
|
|
||||||
|
|
||||||
if not os.path.exists(workspace):
|
|
||||||
reasons.append(f"worktree path '{workspace}' does not exist")
|
|
||||||
return _membership_assessment(False, reasons, workspace, root, None)
|
|
||||||
|
|
||||||
if not os.path.isdir(workspace):
|
|
||||||
reasons.append(f"worktree path '{workspace}' is not a directory")
|
|
||||||
return _membership_assessment(False, reasons, workspace, root, None)
|
|
||||||
|
|
||||||
try:
|
|
||||||
res = subprocess.run(
|
|
||||||
["git", "-C", workspace, "rev-parse", "--git-common-dir"],
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
check=True,
|
|
||||||
)
|
|
||||||
common_dir = _realpath_git_common_dir(workspace, res.stdout)
|
|
||||||
except Exception:
|
|
||||||
reasons.append(f"worktree '{workspace}' is not a valid git repository")
|
|
||||||
return _membership_assessment(False, reasons, workspace, root, None)
|
|
||||||
|
|
||||||
expected_dir = os.path.realpath(os.path.join(root, ".git"))
|
|
||||||
if common_dir != expected_dir:
|
|
||||||
reasons.append(
|
|
||||||
f"worktree '{workspace}' does not belong to the target repository '{root}'"
|
|
||||||
)
|
|
||||||
return _membership_assessment(not reasons, reasons, workspace, root, common_dir)
|
|
||||||
|
|
||||||
|
|
||||||
def _membership_assessment(
|
|
||||||
proven: bool,
|
|
||||||
reasons: list[str],
|
|
||||||
workspace: str,
|
|
||||||
root: str,
|
|
||||||
common_dir: str | None,
|
|
||||||
) -> dict:
|
|
||||||
return {
|
|
||||||
"proven": proven,
|
|
||||||
"block": not proven,
|
|
||||||
"reasons": reasons,
|
|
||||||
"workspace_path": workspace,
|
|
||||||
"canonical_repo_root": root,
|
|
||||||
"git_common_dir": common_dir,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def format_workspace_repo_membership_error(assessment: dict) -> str:
|
|
||||||
workspace = assessment.get("workspace_path") or "(unknown)"
|
|
||||||
root = assessment.get("canonical_repo_root") or "(unknown)"
|
|
||||||
reasons = "; ".join(assessment.get("reasons") or ["unknown repository membership violation"])
|
|
||||||
return (
|
|
||||||
f"Branches-only mutation guard (#274): {reasons} (fail closed). "
|
|
||||||
f"canonical repository root: {root}; workspace: {workspace}."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def assess_author_mutation_worktree(
|
def assess_author_mutation_worktree(
|
||||||
*,
|
*,
|
||||||
workspace_path: str,
|
workspace_path: str,
|
||||||
|
|||||||
@@ -274,24 +274,12 @@ is proven abandoned and the takeover is recorded.
|
|||||||
|
|
||||||
Gitea-Tools lease gates: `gitea_lock_issue` (fail-closed before author
|
Gitea-Tools lease gates: `gitea_lock_issue` (fail-closed before author
|
||||||
mutations), `status:in-progress`, and claim comments. `gitea_lock_issue`
|
mutations), `status:in-progress`, and claim comments. `gitea_lock_issue`
|
||||||
records an `author_issue_work` lease in a keyed lock file under
|
records an `author_issue_work` lease in the issue-lock payload with issue
|
||||||
`GITEA_ISSUE_LOCK_DIR` (default `~/.cache/gitea-tools/issue-locks`), one file
|
number, optional PR number, branch, worktree path, claimant identity/profile,
|
||||||
per `remote` + `org` + `repo` + `issue_number`. The current MCP session binds
|
created timestamp, expiry timestamp, and last heartbeat timestamp. An active
|
||||||
its active lock through a per-process pointer so concurrent repos/issues never
|
same-issue/same-operation lease blocks duplicate work. An expired lease still
|
||||||
share one overwrite-prone slot (#443).
|
blocks takeover until a recovery review records why the prior work is abandoned,
|
||||||
|
completed, or unsafe to continue.
|
||||||
Each lock payload includes issue number, optional PR number, branch, worktree
|
|
||||||
path, claimant identity/profile, created timestamp, expiry timestamp, and last
|
|
||||||
heartbeat timestamp. An active same-issue/same-operation lease blocks duplicate
|
|
||||||
work. An expired lease still blocks takeover until a recovery review records why
|
|
||||||
the prior work is abandoned, completed, or unsafe to continue.
|
|
||||||
|
|
||||||
**Do not manually seed `/tmp/gitea_issue_lock.json` or any lock file as a normal
|
|
||||||
recovery path.** That global slot is deprecated and can clobber unrelated live
|
|
||||||
leases (#438). After an MCP restart, call `gitea_lock_issue` again — own-branch
|
|
||||||
adoption rebinds the session when the issue's exact branch already exists (#442).
|
|
||||||
`gitea_create_pr` resolves the durable keyed lock by session pointer or by
|
|
||||||
matching `head` branch without unsafe manual seeding.
|
|
||||||
|
|
||||||
**Issue-lock recovery (#447):** Do not manually seed, restore, or delete
|
**Issue-lock recovery (#447):** Do not manually seed, restore, or delete
|
||||||
`/tmp/gitea_issue_lock.json` as a normal recovery path. That file is global
|
`/tmp/gitea_issue_lock.json` as a normal recovery path. That file is global
|
||||||
|
|||||||
+89
-112
@@ -190,22 +190,14 @@ def _ensure_process_start_porcelain() -> str:
|
|||||||
|
|
||||||
def _resolve_preflight_workspace_path(worktree_path: str | None = None) -> str:
|
def _resolve_preflight_workspace_path(worktree_path: str | None = None) -> str:
|
||||||
"""Resolve the workspace root inspected by pre-flight guards."""
|
"""Resolve the workspace root inspected by pre-flight guards."""
|
||||||
return author_mutation_worktree.resolve_mutation_workspace(
|
path = (worktree_path or "").strip()
|
||||||
worktree_path,
|
if not path:
|
||||||
PROJECT_ROOT,
|
path = (os.environ.get(ACTIVE_WORKTREE_ENV) or "").strip()
|
||||||
active_worktree_env=os.environ.get(ACTIVE_WORKTREE_ENV),
|
if not path:
|
||||||
author_worktree_env=os.environ.get(AUTHOR_WORKTREE_ENV),
|
path = (os.environ.get(AUTHOR_WORKTREE_ENV) or "").strip()
|
||||||
)
|
if not path:
|
||||||
|
path = PROJECT_ROOT
|
||||||
|
return os.path.realpath(os.path.abspath(path))
|
||||||
def _resolve_author_mutation_context(worktree_path: str | None = None) -> dict:
|
|
||||||
"""Canonical workspace + repository root for runtime_context and guards (#460)."""
|
|
||||||
return author_mutation_worktree.resolve_author_mutation_context(
|
|
||||||
worktree_path,
|
|
||||||
PROJECT_ROOT,
|
|
||||||
active_worktree_env=os.environ.get(ACTIVE_WORKTREE_ENV),
|
|
||||||
author_worktree_env=os.environ.get(AUTHOR_WORKTREE_ENV),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_git_root(path: str) -> str | None:
|
def _get_git_root(path: str) -> str | None:
|
||||||
@@ -275,31 +267,21 @@ def _format_preflight_files(files: list[str]) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def _preflight_workspace_details(worktree_path: str | None, dirty_files: list[str]) -> dict:
|
def _preflight_workspace_details(worktree_path: str | None, dirty_files: list[str]) -> dict:
|
||||||
ctx = _resolve_author_mutation_context(worktree_path)
|
workspace = _resolve_preflight_workspace_path(worktree_path)
|
||||||
workspace = ctx["workspace_path"]
|
|
||||||
inspected_root = _get_git_root(workspace)
|
inspected_root = _get_git_root(workspace)
|
||||||
process_root = ctx["process_project_root"]
|
control_root = os.path.realpath(PROJECT_ROOT)
|
||||||
canonical_root = ctx["canonical_repo_root"]
|
|
||||||
active_root = os.path.realpath(inspected_root or workspace)
|
active_root = os.path.realpath(inspected_root or workspace)
|
||||||
if active_root == canonical_root:
|
if active_root == control_root:
|
||||||
dirty_scope = "control checkout"
|
dirty_scope = "control checkout"
|
||||||
else:
|
else:
|
||||||
dirty_scope = "active task workspace"
|
dirty_scope = "active task workspace"
|
||||||
details = {
|
return {
|
||||||
"mcp_server_process_root": process_root,
|
"mcp_server_process_root": control_root,
|
||||||
"canonical_repository_root": canonical_root,
|
|
||||||
"active_task_workspace_root": active_root,
|
"active_task_workspace_root": active_root,
|
||||||
"inspected_git_root": inspected_root,
|
"inspected_git_root": inspected_root,
|
||||||
"dirty_files": list(dirty_files),
|
"dirty_files": list(dirty_files),
|
||||||
"dirty_scope": dirty_scope,
|
"dirty_scope": dirty_scope,
|
||||||
"workspace_roots_aligned": ctx["roots_aligned"],
|
|
||||||
}
|
}
|
||||||
if not ctx["roots_aligned"]:
|
|
||||||
details["workspace_root_mismatch"] = (
|
|
||||||
"runtime_context and mutation guard use canonical repository root "
|
|
||||||
f"'{canonical_root}' instead of MCP process root '{process_root}'"
|
|
||||||
)
|
|
||||||
return details
|
|
||||||
|
|
||||||
|
|
||||||
def _format_preflight_workspace_details(details: dict) -> str:
|
def _format_preflight_workspace_details(details: dict) -> str:
|
||||||
@@ -420,12 +402,16 @@ def _enforce_branches_only_author_mutation(worktree_path: str | None = None) ->
|
|||||||
"""#274: author mutations must run from a branches/ session worktree."""
|
"""#274: author mutations must run from a branches/ session worktree."""
|
||||||
if _preflight_resolved_role == "reviewer":
|
if _preflight_resolved_role == "reviewer":
|
||||||
return
|
return
|
||||||
ctx = _resolve_author_mutation_context(worktree_path)
|
workspace = author_mutation_worktree.resolve_mutation_workspace(
|
||||||
workspace = ctx["workspace_path"]
|
worktree_path,
|
||||||
|
PROJECT_ROOT,
|
||||||
|
active_worktree_env=os.environ.get(ACTIVE_WORKTREE_ENV),
|
||||||
|
author_worktree_env=os.environ.get(AUTHOR_WORKTREE_ENV),
|
||||||
|
)
|
||||||
git_state = issue_lock_worktree.read_worktree_git_state(workspace)
|
git_state = issue_lock_worktree.read_worktree_git_state(workspace)
|
||||||
assessment = author_mutation_worktree.assess_author_mutation_worktree(
|
assessment = author_mutation_worktree.assess_author_mutation_worktree(
|
||||||
workspace_path=workspace,
|
workspace_path=workspace,
|
||||||
project_root=ctx["canonical_repo_root"],
|
project_root=PROJECT_ROOT,
|
||||||
current_branch=git_state.get("current_branch"),
|
current_branch=git_state.get("current_branch"),
|
||||||
)
|
)
|
||||||
if assessment["block"]:
|
if assessment["block"]:
|
||||||
@@ -454,23 +440,43 @@ def verify_preflight_purity(remote: str | None = None, worktree_path: str | None
|
|||||||
"Pre-flight order violation: Task capability (gitea_resolve_task_capability) has not been resolved (fail closed)"
|
"Pre-flight order violation: Task capability (gitea_resolve_task_capability) has not been resolved (fail closed)"
|
||||||
)
|
)
|
||||||
|
|
||||||
ctx = _resolve_author_mutation_context(worktree_path)
|
workspace = author_mutation_worktree.resolve_mutation_workspace(
|
||||||
workspace = ctx["workspace_path"]
|
worktree_path,
|
||||||
canonical_root = ctx["canonical_repo_root"]
|
PROJECT_ROOT,
|
||||||
process_root = ctx["process_project_root"]
|
active_worktree_env=os.environ.get(ACTIVE_WORKTREE_ENV),
|
||||||
|
author_worktree_env=os.environ.get(AUTHOR_WORKTREE_ENV),
|
||||||
|
)
|
||||||
real_workspace = os.path.realpath(workspace)
|
real_workspace = os.path.realpath(workspace)
|
||||||
|
real_root = os.path.realpath(PROJECT_ROOT)
|
||||||
|
|
||||||
if real_workspace != process_root:
|
if real_workspace != real_root:
|
||||||
if not _preflight_in_test_mode():
|
if not _preflight_in_test_mode():
|
||||||
membership = author_mutation_worktree.assess_workspace_repo_membership(
|
if not os.path.exists(real_workspace):
|
||||||
workspace_path=workspace,
|
|
||||||
canonical_repo_root=canonical_root,
|
|
||||||
)
|
|
||||||
if membership["block"]:
|
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
author_mutation_worktree.format_workspace_repo_membership_error(
|
f"Branches-only mutation guard (#274): worktree path '{workspace}' does not exist (fail closed)"
|
||||||
membership
|
)
|
||||||
|
if not os.path.isdir(real_workspace):
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Branches-only mutation guard (#274): worktree path '{workspace}' is not a directory (fail closed)"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
res = subprocess.run(
|
||||||
|
["git", "-C", real_workspace, "rev-parse", "--git-common-dir"],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
common_dir = os.path.realpath(res.stdout.strip())
|
||||||
|
expected_dir = os.path.realpath(os.path.join(real_root, ".git"))
|
||||||
|
if common_dir != expected_dir:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Branches-only mutation guard (#274): worktree '{workspace}' does not belong to the target repository '{PROJECT_ROOT}' (fail closed)"
|
||||||
)
|
)
|
||||||
|
except Exception as e:
|
||||||
|
if isinstance(e, RuntimeError):
|
||||||
|
raise e
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Branches-only mutation guard (#274): worktree '{workspace}' is not a valid git repository (fail closed)"
|
||||||
)
|
)
|
||||||
|
|
||||||
dirty_files = sorted(_parse_porcelain_entries(_get_workspace_porcelain(workspace)))
|
dirty_files = sorted(_parse_porcelain_entries(_get_workspace_porcelain(workspace)))
|
||||||
@@ -533,12 +539,11 @@ import review_proofs # noqa: E402
|
|||||||
import agent_temp_artifacts
|
import agent_temp_artifacts
|
||||||
import issue_lock_worktree # noqa: E402
|
import issue_lock_worktree # noqa: E402
|
||||||
import issue_lock_provenance # noqa: E402
|
import issue_lock_provenance # noqa: E402
|
||||||
import issue_lock_store # noqa: E402
|
|
||||||
import issue_lock_adoption # noqa: E402
|
|
||||||
import already_landed_reconcile # noqa: E402
|
import already_landed_reconcile # noqa: E402
|
||||||
import author_mutation_worktree # noqa: E402
|
import author_mutation_worktree # noqa: E402
|
||||||
import issue_claim_heartbeat # noqa: E402
|
import issue_claim_heartbeat # noqa: E402
|
||||||
import issue_work_duplicate_gate # noqa: E402
|
import issue_work_duplicate_gate # noqa: E402
|
||||||
|
import issue_lock_adoption # noqa: E402
|
||||||
import reviewer_pr_lease # noqa: E402
|
import reviewer_pr_lease # noqa: E402
|
||||||
import merged_cleanup_reconcile # noqa: E402
|
import merged_cleanup_reconcile # noqa: E402
|
||||||
import reconciler_profile # noqa: E402
|
import reconciler_profile # noqa: E402
|
||||||
@@ -547,9 +552,8 @@ import review_merge_state_machine # noqa: E402
|
|||||||
import native_mcp_preference # noqa: E402
|
import native_mcp_preference # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
# Keyed issue-lock storage (#443): per remote/org/repo/issue files under
|
# Fail-closed exact-issue-lock file (#204): written by gitea_lock_issue,
|
||||||
# GITEA_ISSUE_LOCK_DIR, bound to the current MCP session via a per-PID pointer.
|
# consumed by gitea_create_pr and scripts/worktree-start.
|
||||||
# Legacy global path retained only for test/doc references — do not seed manually.
|
|
||||||
ISSUE_LOCK_FILE = "/tmp/gitea_issue_lock.json"
|
ISSUE_LOCK_FILE = "/tmp/gitea_issue_lock.json"
|
||||||
WORK_LEASE_TTL_HOURS = 4
|
WORK_LEASE_TTL_HOURS = 4
|
||||||
AUTHOR_ISSUE_WORK_LEASE = "author_issue_work"
|
AUTHOR_ISSUE_WORK_LEASE = "author_issue_work"
|
||||||
@@ -581,59 +585,15 @@ def _parse_work_lease_timestamp(value: str | None) -> datetime | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _load_existing_issue_lock(
|
def _load_existing_issue_lock() -> dict | None:
|
||||||
*,
|
if not os.path.exists(ISSUE_LOCK_FILE):
|
||||||
remote: str | None = None,
|
return None
|
||||||
org: str | None = None,
|
|
||||||
repo: str | None = None,
|
|
||||||
issue_number: int | None = None,
|
|
||||||
) -> dict | None:
|
|
||||||
if remote and org and repo and issue_number is not None:
|
|
||||||
return issue_lock_store.load_issue_lock(
|
|
||||||
remote=remote,
|
|
||||||
org=org,
|
|
||||||
repo=repo,
|
|
||||||
issue_number=issue_number,
|
|
||||||
)
|
|
||||||
return issue_lock_store.read_session_issue_lock()
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve_issue_lock_for_pr(
|
|
||||||
*,
|
|
||||||
remote: str,
|
|
||||||
org: str,
|
|
||||||
repo: str,
|
|
||||||
head: str,
|
|
||||||
) -> dict:
|
|
||||||
lock_data = issue_lock_store.read_session_issue_lock()
|
|
||||||
if not lock_data:
|
|
||||||
lock_data = issue_lock_store.find_lock_for_branch(
|
|
||||||
remote=remote,
|
|
||||||
org=org,
|
|
||||||
repo=repo,
|
|
||||||
branch_name=head,
|
|
||||||
)
|
|
||||||
if not lock_data:
|
|
||||||
raise RuntimeError(
|
|
||||||
"Issue lock is missing (fail closed). Call gitea_lock_issue first."
|
|
||||||
)
|
|
||||||
return lock_data
|
|
||||||
|
|
||||||
|
|
||||||
def _save_issue_lock(data: dict) -> str:
|
|
||||||
existing = issue_lock_store.load_issue_lock(
|
|
||||||
remote=str(data.get("remote") or ""),
|
|
||||||
org=str(data.get("org") or ""),
|
|
||||||
repo=str(data.get("repo") or ""),
|
|
||||||
issue_number=int(data.get("issue_number") or 0),
|
|
||||||
)
|
|
||||||
overwrite_block = issue_lock_store.assess_foreign_lock_overwrite(existing, data)
|
|
||||||
if overwrite_block:
|
|
||||||
raise RuntimeError(overwrite_block)
|
|
||||||
try:
|
try:
|
||||||
return issue_lock_store.bind_session_lock(data)
|
with open(ISSUE_LOCK_FILE, "r", encoding="utf-8") as f:
|
||||||
except Exception as e:
|
data = json.load(f)
|
||||||
raise RuntimeError(f"Could not write issue lock file: {e}") from e
|
return data if isinstance(data, dict) else None
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _work_lease_claimant(host: str | None) -> dict:
|
def _work_lease_claimant(host: str | None) -> dict:
|
||||||
@@ -1296,9 +1256,8 @@ def gitea_lock_issue(
|
|||||||
resolved_worktree = issue_lock_worktree.resolve_author_worktree_path(
|
resolved_worktree = issue_lock_worktree.resolve_author_worktree_path(
|
||||||
worktree_path, PROJECT_ROOT
|
worktree_path, PROJECT_ROOT
|
||||||
)
|
)
|
||||||
h, o, r = _resolve(remote, host, org, repo)
|
active_lease_block = _active_work_lease_block(
|
||||||
active_lease_block = issue_lock_store.assess_same_issue_lease_conflict(
|
_load_existing_issue_lock(),
|
||||||
_load_existing_issue_lock(remote=remote, org=o, repo=r, issue_number=issue_number),
|
|
||||||
issue_number=issue_number,
|
issue_number=issue_number,
|
||||||
branch_name=branch_name,
|
branch_name=branch_name,
|
||||||
worktree_path=resolved_worktree,
|
worktree_path=resolved_worktree,
|
||||||
@@ -1322,6 +1281,7 @@ def gitea_lock_issue(
|
|||||||
issue_lock_worktree.format_issue_lock_worktree_error(lock_assessment)
|
issue_lock_worktree.format_issue_lock_worktree_error(lock_assessment)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
h, o, r = _resolve(remote, host, org, repo)
|
||||||
auth = _auth(h)
|
auth = _auth(h)
|
||||||
duplicate_gate = _assess_issue_duplicate_gate(
|
duplicate_gate = _assess_issue_duplicate_gate(
|
||||||
issue_number,
|
issue_number,
|
||||||
@@ -1381,7 +1341,11 @@ def gitea_lock_issue(
|
|||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
lock_file_path = _save_issue_lock(data)
|
try:
|
||||||
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(data, f)
|
||||||
|
except Exception as e:
|
||||||
|
raise RuntimeError(f"Could not write issue lock file: {e}")
|
||||||
|
|
||||||
agent_artifacts = agent_temp_artifacts.find_agent_temp_artifacts_from_porcelain(
|
agent_artifacts = agent_temp_artifacts.find_agent_temp_artifacts_from_porcelain(
|
||||||
git_state.get("porcelain_status") or ""
|
git_state.get("porcelain_status") or ""
|
||||||
@@ -1396,16 +1360,16 @@ def gitea_lock_issue(
|
|||||||
"branch_name": branch_name,
|
"branch_name": branch_name,
|
||||||
"worktree_path": resolved_worktree,
|
"worktree_path": resolved_worktree,
|
||||||
"work_lease": work_lease,
|
"work_lease": work_lease,
|
||||||
"lock_file_path": lock_file_path,
|
|
||||||
}
|
}
|
||||||
if adoption["adopt"]:
|
if adoption["adopt"]:
|
||||||
|
# #442: recovery lock over the issue's own already-pushed branch.
|
||||||
result["adoption"] = issue_lock_adoption.build_adoption_proof(
|
result["adoption"] = issue_lock_adoption.build_adoption_proof(
|
||||||
issue_number=issue_number,
|
issue_number=issue_number,
|
||||||
branch_name=branch_name,
|
branch_name=branch_name,
|
||||||
assessment=adoption,
|
assessment=adoption,
|
||||||
open_pr_checked=True,
|
open_pr_checked=True,
|
||||||
competing_lock_checked=True,
|
competing_lock_checked=True,
|
||||||
lock_file_path=lock_file_path,
|
lock_file_path=ISSUE_LOCK_FILE,
|
||||||
lock_file_status="written",
|
lock_file_status="written",
|
||||||
)
|
)
|
||||||
result["message"] = (
|
result["message"] = (
|
||||||
@@ -1503,8 +1467,15 @@ def gitea_create_pr(
|
|||||||
verify_preflight_purity(remote, worktree_path=worktree_path)
|
verify_preflight_purity(remote, worktree_path=worktree_path)
|
||||||
h, o, r = _resolve(remote, host, org, repo)
|
h, o, r = _resolve(remote, host, org, repo)
|
||||||
|
|
||||||
# ── Issue Lock Validation (Issue #194 / #196 / #443) ──
|
# ── Issue Lock Validation (Issue #194 / #196) ──
|
||||||
lock_data = _resolve_issue_lock_for_pr(remote=remote, org=o, repo=r, head=head)
|
if not os.path.exists(ISSUE_LOCK_FILE):
|
||||||
|
raise RuntimeError("Issue lock is missing (fail closed). Call gitea_lock_issue first.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(ISSUE_LOCK_FILE, "r", encoding="utf-8") as f:
|
||||||
|
lock_data = json.load(f)
|
||||||
|
except Exception as e:
|
||||||
|
raise RuntimeError(f"Could not read issue lock file: {e} (fail closed)")
|
||||||
|
|
||||||
lock_provenance_check = issue_lock_provenance.assess_lock_file_for_create_pr(
|
lock_provenance_check = issue_lock_provenance.assess_lock_file_for_create_pr(
|
||||||
lock_data
|
lock_data
|
||||||
@@ -3038,7 +3009,13 @@ def _prepare_commit_payload_files(files: list[dict]) -> tuple[list[dict], list[d
|
|||||||
processed_files = []
|
processed_files = []
|
||||||
source_proofs = []
|
source_proofs = []
|
||||||
|
|
||||||
lock_data = issue_lock_store.read_session_issue_lock() or {}
|
lock_data = {}
|
||||||
|
if os.path.exists(ISSUE_LOCK_FILE):
|
||||||
|
try:
|
||||||
|
with open(ISSUE_LOCK_FILE, "r", encoding="utf-8") as f:
|
||||||
|
lock_data = json.load(f)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
locked_worktree = lock_data.get("worktree_path")
|
locked_worktree = lock_data.get("worktree_path")
|
||||||
if locked_worktree:
|
if locked_worktree:
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Own-branch lock adoption / recovery for ``gitea_lock_issue`` (#442 / #443).
|
"""Own-branch lock adoption / recovery for ``gitea_lock_issue`` (#442).
|
||||||
|
|
||||||
When an issue's own already-pushed branch exists, lock reacquisition must be
|
When an issue's own already-pushed branch exists, lock reacquisition must be
|
||||||
allowed (adoption) instead of being treated as #400 duplicate competing work.
|
allowed (adoption) instead of being treated as #400 duplicate competing work.
|
||||||
@@ -153,4 +153,4 @@ def build_adoption_proof(
|
|||||||
"no_competing_live_lock_proof": bool(competing_lock_checked),
|
"no_competing_live_lock_proof": bool(competing_lock_checked),
|
||||||
"lock_file_path": lock_file_path,
|
"lock_file_path": lock_file_path,
|
||||||
"lock_file_status": lock_file_status,
|
"lock_file_status": lock_file_status,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,385 +0,0 @@
|
|||||||
"""Keyed, persistent issue-lock storage (#443).
|
|
||||||
|
|
||||||
Replaces the single global ``/tmp/gitea_issue_lock.json`` slot with per-issue
|
|
||||||
lock files under ``GITEA_ISSUE_LOCK_DIR`` (default
|
|
||||||
``~/.cache/gitea-tools/issue-locks``). Each MCP session binds its active lock
|
|
||||||
via a per-process pointer file so concurrent repos/issues never clobber each
|
|
||||||
other.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import tempfile
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
LOCK_DIR_ENV = "GITEA_ISSUE_LOCK_DIR"
|
|
||||||
DEFAULT_LOCK_DIR = os.path.expanduser("~/.cache/gitea-tools/issue-locks")
|
|
||||||
WORK_LEASE_TTL_HOURS = 4
|
|
||||||
AUTHOR_ISSUE_WORK_LEASE = "author_issue_work"
|
|
||||||
|
|
||||||
_SAFE_SEGMENT_RE = re.compile(r"[^A-Za-z0-9._+-]+")
|
|
||||||
|
|
||||||
|
|
||||||
def default_lock_dir() -> str:
|
|
||||||
raw = (os.environ.get(LOCK_DIR_ENV) or DEFAULT_LOCK_DIR).strip()
|
|
||||||
return raw or DEFAULT_LOCK_DIR
|
|
||||||
|
|
||||||
|
|
||||||
def _sanitize_segment(value: str) -> str:
|
|
||||||
text = (value or "").strip()
|
|
||||||
if not text:
|
|
||||||
return "_"
|
|
||||||
return _SAFE_SEGMENT_RE.sub("_", text)
|
|
||||||
|
|
||||||
|
|
||||||
def lock_key(
|
|
||||||
*,
|
|
||||||
remote: str,
|
|
||||||
org: str,
|
|
||||||
repo: str,
|
|
||||||
issue_number: int,
|
|
||||||
) -> str:
|
|
||||||
return "-".join(
|
|
||||||
_sanitize_segment(part)
|
|
||||||
for part in (remote, org, repo, str(issue_number))
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def lock_file_path(
|
|
||||||
*,
|
|
||||||
remote: str,
|
|
||||||
org: str,
|
|
||||||
repo: str,
|
|
||||||
issue_number: int,
|
|
||||||
lock_dir: str | None = None,
|
|
||||||
) -> str:
|
|
||||||
root = (lock_dir or default_lock_dir()).strip()
|
|
||||||
return os.path.join(root, f"{lock_key(remote=remote, org=org, repo=repo, issue_number=issue_number)}.json")
|
|
||||||
|
|
||||||
|
|
||||||
def session_pointer_path(lock_dir: str | None = None) -> str:
|
|
||||||
root = (lock_dir or default_lock_dir()).strip()
|
|
||||||
return os.path.join(root, f"session-{os.getpid()}.json")
|
|
||||||
|
|
||||||
|
|
||||||
def _ensure_lock_dir(lock_dir: str | None = None) -> str:
|
|
||||||
root = (lock_dir or default_lock_dir()).strip()
|
|
||||||
os.makedirs(root, mode=0o700, exist_ok=True)
|
|
||||||
return root
|
|
||||||
|
|
||||||
|
|
||||||
def read_lock_file(path: str) -> dict[str, Any] | None:
|
|
||||||
lock_path = (path or "").strip()
|
|
||||||
if not lock_path or not os.path.exists(lock_path):
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
with open(lock_path, encoding="utf-8") as handle:
|
|
||||||
data = json.load(handle)
|
|
||||||
except (OSError, json.JSONDecodeError):
|
|
||||||
return None
|
|
||||||
return data if isinstance(data, dict) else None
|
|
||||||
|
|
||||||
|
|
||||||
def save_lock_file(path: str, data: dict[str, Any]) -> None:
|
|
||||||
lock_path = (path or "").strip()
|
|
||||||
if not lock_path:
|
|
||||||
raise ValueError("lock path is required (fail closed)")
|
|
||||||
parent = os.path.dirname(lock_path) or "."
|
|
||||||
os.makedirs(parent, mode=0o700, exist_ok=True)
|
|
||||||
payload = json.dumps(data, indent=2, sort_keys=True) + "\n"
|
|
||||||
fd, temp_path = tempfile.mkstemp(prefix=".lock-", suffix=".json", dir=parent)
|
|
||||||
try:
|
|
||||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
||||||
handle.write(payload)
|
|
||||||
handle.flush()
|
|
||||||
os.fsync(handle.fileno())
|
|
||||||
os.replace(temp_path, lock_path)
|
|
||||||
finally:
|
|
||||||
if os.path.exists(temp_path):
|
|
||||||
try:
|
|
||||||
os.remove(temp_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def bind_session_lock(lock_data: dict[str, Any], lock_dir: str | None = None) -> str:
|
|
||||||
"""Persist a keyed lock and bind it to the current process session."""
|
|
||||||
remote = str(lock_data.get("remote") or "")
|
|
||||||
org = str(lock_data.get("org") or "")
|
|
||||||
repo = str(lock_data.get("repo") or "")
|
|
||||||
issue_number = int(lock_data.get("issue_number") or 0)
|
|
||||||
if not remote or not org or not repo or issue_number <= 0:
|
|
||||||
raise ValueError("lock record must include remote, org, repo, and issue_number")
|
|
||||||
|
|
||||||
root = _ensure_lock_dir(lock_dir)
|
|
||||||
path = lock_file_path(
|
|
||||||
remote=remote,
|
|
||||||
org=org,
|
|
||||||
repo=repo,
|
|
||||||
issue_number=issue_number,
|
|
||||||
lock_dir=root,
|
|
||||||
)
|
|
||||||
record = dict(lock_data)
|
|
||||||
record["lock_file_path"] = path
|
|
||||||
record["session_pid"] = os.getpid()
|
|
||||||
save_lock_file(path, record)
|
|
||||||
|
|
||||||
pointer = {
|
|
||||||
"pid": os.getpid(),
|
|
||||||
"lock_file_path": path,
|
|
||||||
"issue_number": issue_number,
|
|
||||||
"branch_name": record.get("branch_name"),
|
|
||||||
"remote": remote,
|
|
||||||
"org": org,
|
|
||||||
"repo": repo,
|
|
||||||
}
|
|
||||||
save_lock_file(session_pointer_path(root), pointer)
|
|
||||||
return path
|
|
||||||
|
|
||||||
|
|
||||||
def read_session_issue_lock(lock_dir: str | None = None) -> dict[str, Any] | None:
|
|
||||||
root = (lock_dir or default_lock_dir()).strip()
|
|
||||||
pointer = read_lock_file(session_pointer_path(root))
|
|
||||||
if not pointer:
|
|
||||||
return None
|
|
||||||
lock_path = str(pointer.get("lock_file_path") or "").strip()
|
|
||||||
if not lock_path:
|
|
||||||
return None
|
|
||||||
return read_lock_file(lock_path)
|
|
||||||
|
|
||||||
|
|
||||||
def load_issue_lock(
|
|
||||||
*,
|
|
||||||
remote: str,
|
|
||||||
org: str,
|
|
||||||
repo: str,
|
|
||||||
issue_number: int,
|
|
||||||
lock_dir: str | None = None,
|
|
||||||
) -> dict[str, Any] | None:
|
|
||||||
return read_lock_file(
|
|
||||||
lock_file_path(
|
|
||||||
remote=remote,
|
|
||||||
org=org,
|
|
||||||
repo=repo,
|
|
||||||
issue_number=issue_number,
|
|
||||||
lock_dir=lock_dir,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def iter_lock_files(lock_dir: str | None = None) -> list[str]:
|
|
||||||
root = (lock_dir or default_lock_dir()).strip()
|
|
||||||
if not os.path.isdir(root):
|
|
||||||
return []
|
|
||||||
paths: list[str] = []
|
|
||||||
for name in os.listdir(root):
|
|
||||||
if not name.endswith(".json") or name.startswith("session-"):
|
|
||||||
continue
|
|
||||||
paths.append(os.path.join(root, name))
|
|
||||||
return sorted(paths)
|
|
||||||
|
|
||||||
|
|
||||||
def find_lock_for_branch(
|
|
||||||
*,
|
|
||||||
remote: str,
|
|
||||||
org: str,
|
|
||||||
repo: str,
|
|
||||||
branch_name: str,
|
|
||||||
lock_dir: str | None = None,
|
|
||||||
) -> dict[str, Any] | None:
|
|
||||||
target = (branch_name or "").strip()
|
|
||||||
if not target:
|
|
||||||
return None
|
|
||||||
for path in iter_lock_files(lock_dir):
|
|
||||||
lock = read_lock_file(path)
|
|
||||||
if not lock:
|
|
||||||
continue
|
|
||||||
if (
|
|
||||||
str(lock.get("remote") or "") == remote
|
|
||||||
and str(lock.get("org") or "") == org
|
|
||||||
and str(lock.get("repo") or "") == repo
|
|
||||||
and str(lock.get("branch_name") or "").strip() == target
|
|
||||||
):
|
|
||||||
lock = dict(lock)
|
|
||||||
lock.setdefault("lock_file_path", path)
|
|
||||||
return lock
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _lease_now(now: datetime | None = None) -> datetime:
|
|
||||||
return now or datetime.now(timezone.utc)
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_lease_timestamp(value: str | None) -> datetime | None:
|
|
||||||
text = (value or "").strip()
|
|
||||||
if not text:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
return datetime.fromisoformat(text.replace("Z", "+00:00")).astimezone(timezone.utc)
|
|
||||||
except ValueError:
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def lease_expires_at(lock: dict[str, Any] | None) -> datetime | None:
|
|
||||||
if not lock:
|
|
||||||
return None
|
|
||||||
lease = lock.get("work_lease")
|
|
||||||
if not isinstance(lease, dict):
|
|
||||||
return None
|
|
||||||
return _parse_lease_timestamp(lease.get("expires_at"))
|
|
||||||
|
|
||||||
|
|
||||||
def is_lease_expired(lock: dict[str, Any] | None, *, now: datetime | None = None) -> bool:
|
|
||||||
expires = lease_expires_at(lock)
|
|
||||||
if expires is None:
|
|
||||||
return False
|
|
||||||
return expires <= _lease_now(now)
|
|
||||||
|
|
||||||
|
|
||||||
def is_lease_live(lock: dict[str, Any] | None, *, now: datetime | None = None) -> bool:
|
|
||||||
if not lock:
|
|
||||||
return False
|
|
||||||
lease = lock.get("work_lease")
|
|
||||||
if not isinstance(lease, dict):
|
|
||||||
return True
|
|
||||||
expires = _parse_lease_timestamp(lease.get("expires_at"))
|
|
||||||
if expires is None:
|
|
||||||
return True
|
|
||||||
return expires > _lease_now(now)
|
|
||||||
|
|
||||||
|
|
||||||
def _same_realpath(left: str | None, right: str | None) -> bool:
|
|
||||||
if not left or not right:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
return os.path.realpath(left) == os.path.realpath(right)
|
|
||||||
except OSError:
|
|
||||||
return left == right
|
|
||||||
|
|
||||||
|
|
||||||
def assess_same_issue_lease_conflict(
|
|
||||||
existing_lock: dict[str, Any] | None,
|
|
||||||
*,
|
|
||||||
issue_number: int,
|
|
||||||
branch_name: str,
|
|
||||||
worktree_path: str,
|
|
||||||
operation_type: str = AUTHOR_ISSUE_WORK_LEASE,
|
|
||||||
now: datetime | None = None,
|
|
||||||
) -> str | None:
|
|
||||||
"""Return a fail-closed error when a competing live lease blocks acquisition."""
|
|
||||||
if not existing_lock:
|
|
||||||
return None
|
|
||||||
|
|
||||||
existing_issue = existing_lock.get("issue_number")
|
|
||||||
lease = existing_lock.get("work_lease")
|
|
||||||
existing_operation = (
|
|
||||||
lease.get("operation_type")
|
|
||||||
if isinstance(lease, dict)
|
|
||||||
else AUTHOR_ISSUE_WORK_LEASE
|
|
||||||
)
|
|
||||||
if existing_issue != issue_number or existing_operation != operation_type:
|
|
||||||
return None
|
|
||||||
|
|
||||||
existing_branch = existing_lock.get("branch_name")
|
|
||||||
existing_worktree = existing_lock.get("worktree_path")
|
|
||||||
same_owner = (
|
|
||||||
existing_branch == branch_name
|
|
||||||
and _same_realpath(str(existing_worktree or ""), worktree_path)
|
|
||||||
)
|
|
||||||
if is_lease_expired(existing_lock, now=now):
|
|
||||||
return (
|
|
||||||
f"Issue #{issue_number} has an expired {operation_type} lease on "
|
|
||||||
f"branch '{existing_branch}' from worktree '{existing_worktree}'. "
|
|
||||||
"Recovery review is required before takeover (fail closed)"
|
|
||||||
)
|
|
||||||
if same_owner:
|
|
||||||
return None
|
|
||||||
return (
|
|
||||||
f"Issue #{issue_number} already has an active {operation_type} lease on "
|
|
||||||
f"branch '{existing_branch}' from worktree '{existing_worktree}' "
|
|
||||||
"(fail closed)"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def assess_foreign_lock_overwrite(
|
|
||||||
existing_lock: dict[str, Any] | None,
|
|
||||||
incoming_lock: dict[str, Any],
|
|
||||||
*,
|
|
||||||
now: datetime | None = None,
|
|
||||||
) -> str | None:
|
|
||||||
"""Block writes that would clobber an unrelated live lease on the same key."""
|
|
||||||
if not existing_lock:
|
|
||||||
return None
|
|
||||||
|
|
||||||
same_issue = existing_lock.get("issue_number") == incoming_lock.get("issue_number")
|
|
||||||
same_branch = existing_lock.get("branch_name") == incoming_lock.get("branch_name")
|
|
||||||
same_worktree = _same_realpath(
|
|
||||||
str(existing_lock.get("worktree_path") or ""),
|
|
||||||
str(incoming_lock.get("worktree_path") or ""),
|
|
||||||
)
|
|
||||||
if same_issue and same_branch and same_worktree:
|
|
||||||
return None
|
|
||||||
if not is_lease_live(existing_lock, now=now):
|
|
||||||
return None
|
|
||||||
return (
|
|
||||||
"Refusing to overwrite a live foreign issue lock "
|
|
||||||
f"(issue #{existing_lock.get('issue_number')}, "
|
|
||||||
f"branch '{existing_lock.get('branch_name')}', "
|
|
||||||
f"worktree '{existing_lock.get('worktree_path')}') (fail closed)"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def find_live_lock_for_branch(
|
|
||||||
branch_name: str,
|
|
||||||
lock_dir: str | None = None,
|
|
||||||
) -> dict[str, Any] | None:
|
|
||||||
target = (branch_name or "").strip()
|
|
||||||
if not target:
|
|
||||||
return None
|
|
||||||
for path in iter_lock_files(lock_dir):
|
|
||||||
lock = read_lock_file(path)
|
|
||||||
if not lock:
|
|
||||||
continue
|
|
||||||
if str(lock.get("branch_name") or "").strip() != target:
|
|
||||||
continue
|
|
||||||
if not is_lease_live(lock):
|
|
||||||
continue
|
|
||||||
record = dict(lock)
|
|
||||||
record.setdefault("lock_file_path", path)
|
|
||||||
return record
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_locked_branch_for_session(
|
|
||||||
branch_name: str | None = None,
|
|
||||||
lock_dir: str | None = None,
|
|
||||||
) -> str:
|
|
||||||
if branch_name:
|
|
||||||
lock = find_live_lock_for_branch(branch_name, lock_dir)
|
|
||||||
if lock:
|
|
||||||
return str(lock.get("branch_name") or "")
|
|
||||||
lock = read_session_issue_lock(lock_dir)
|
|
||||||
return str((lock or {}).get("branch_name") or "")
|
|
||||||
|
|
||||||
|
|
||||||
def has_active_issue_lock(
|
|
||||||
branch: str,
|
|
||||||
*,
|
|
||||||
lock_dir: str | None = None,
|
|
||||||
) -> bool:
|
|
||||||
target = (branch or "").strip()
|
|
||||||
if not target:
|
|
||||||
return False
|
|
||||||
for path in iter_lock_files(lock_dir):
|
|
||||||
lock = read_lock_file(path)
|
|
||||||
if not lock:
|
|
||||||
continue
|
|
||||||
if str(lock.get("branch_name") or "").strip() != target:
|
|
||||||
continue
|
|
||||||
if is_lease_live(lock):
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
+14
-10
@@ -13,9 +13,9 @@ import subprocess
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from reviewer_worktree import parse_dirty_tracked_files
|
from reviewer_worktree import parse_dirty_tracked_files
|
||||||
import issue_lock_store
|
|
||||||
|
|
||||||
PROTECTED_BRANCHES = frozenset({"master", "main", "dev"})
|
PROTECTED_BRANCHES = frozenset({"master", "main", "dev"})
|
||||||
|
ISSUE_LOCK_FILE = os.environ.get("GITEA_ISSUE_LOCK_FILE", "/tmp/gitea_issue_lock.json")
|
||||||
CLOSES_FIXES_RE = re.compile(r"\b(?:closes|fixes)\s+#(\d+)\b", re.IGNORECASE)
|
CLOSES_FIXES_RE = re.compile(r"\b(?:closes|fixes)\s+#(\d+)\b", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
@@ -37,18 +37,22 @@ def resolve_worktree_path(project_root: str, branch: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def read_issue_lock(path: str | None = None) -> dict[str, Any] | None:
|
def read_issue_lock(path: str | None = None) -> dict[str, Any] | None:
|
||||||
if path:
|
lock_path = (path or ISSUE_LOCK_FILE).strip()
|
||||||
return issue_lock_store.read_lock_file(path.strip())
|
if not lock_path or not os.path.exists(lock_path):
|
||||||
return issue_lock_store.read_session_issue_lock()
|
return None
|
||||||
|
try:
|
||||||
|
with open(lock_path, encoding="utf-8") as handle:
|
||||||
|
data = json.load(handle)
|
||||||
|
except (OSError, json.JSONDecodeError):
|
||||||
|
return None
|
||||||
|
return data if isinstance(data, dict) else None
|
||||||
|
|
||||||
|
|
||||||
def has_active_issue_lock(branch: str, lock_path: str | None = None) -> bool:
|
def has_active_issue_lock(branch: str, lock_path: str | None = None) -> bool:
|
||||||
if lock_path:
|
lock = read_issue_lock(lock_path)
|
||||||
lock = issue_lock_store.read_lock_file(lock_path.strip())
|
if not lock:
|
||||||
if not lock:
|
return False
|
||||||
return False
|
return (lock.get("branch_name") or "").strip() == (branch or "").strip()
|
||||||
return (lock.get("branch_name") or "").strip() == (branch or "").strip()
|
|
||||||
return issue_lock_store.has_active_issue_lock(branch)
|
|
||||||
|
|
||||||
|
|
||||||
def collect_open_pr_heads(open_prs: list[dict[str, Any]]) -> set[str]:
|
def collect_open_pr_heads(open_prs: list[dict[str, Any]]) -> set[str]:
|
||||||
|
|||||||
+5
-11
@@ -38,21 +38,13 @@ fi
|
|||||||
branch="$1"
|
branch="$1"
|
||||||
start_ref="${2:-prgs/master}"
|
start_ref="${2:-prgs/master}"
|
||||||
|
|
||||||
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
repo_root="$(cd "$script_dir/.." && pwd)"
|
|
||||||
|
|
||||||
# Enforce issue-linked, traceable branch names (issue → branch → worktree → PR).
|
# Enforce issue-linked, traceable branch names (issue → branch → worktree → PR).
|
||||||
if [[ "$allow_unlinked" -eq 0 ]]; then
|
if [[ "$allow_unlinked" -eq 0 ]]; then
|
||||||
locked_branch=$(python3 -c "
|
if [[ ! -f "/tmp/gitea_issue_lock.json" ]]; then
|
||||||
import sys
|
echo "Error: Issue lock file '/tmp/gitea_issue_lock.json' is missing. You must lock exactly one issue before branch creation (fail closed)." >&2
|
||||||
sys.path.insert(0, '$repo_root')
|
|
||||||
import issue_lock_store
|
|
||||||
print(issue_lock_store.resolve_locked_branch_for_session('$branch'))
|
|
||||||
")
|
|
||||||
if [[ -z "$locked_branch" ]]; then
|
|
||||||
echo "Error: No session issue lock is bound. Call gitea_lock_issue before branch creation (fail closed)." >&2
|
|
||||||
exit 2
|
exit 2
|
||||||
fi
|
fi
|
||||||
|
locked_branch=$(python3 -c "import json; print(json.load(open('/tmp/gitea_issue_lock.json')).get('branch_name', ''))")
|
||||||
if [[ "$branch" != "$locked_branch" ]]; then
|
if [[ "$branch" != "$locked_branch" ]]; then
|
||||||
echo "Error: Requested branch '$branch' does not match locked branch '$locked_branch' (fail closed)." >&2
|
echo "Error: Requested branch '$branch' does not match locked branch '$locked_branch' (fail closed)." >&2
|
||||||
exit 2
|
exit 2
|
||||||
@@ -76,6 +68,8 @@ EOF
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
repo_root="$(cd "$script_dir/.." && pwd)"
|
||||||
worktree_name="${branch//\//-}"
|
worktree_name="${branch//\//-}"
|
||||||
worktree_path="$repo_root/branches/$worktree_name"
|
worktree_path="$repo_root/branches/$worktree_name"
|
||||||
|
|
||||||
|
|||||||
@@ -74,14 +74,11 @@ ISSUE_WRITE_ENV = {
|
|||||||
|
|
||||||
class TestIssueLockArtifactWarning(unittest.TestCase):
|
class TestIssueLockArtifactWarning(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self._lock_dir = tempfile.TemporaryDirectory()
|
self._env_patcher = patch.dict(os.environ, ISSUE_WRITE_ENV, clear=True)
|
||||||
env = {**ISSUE_WRITE_ENV, "GITEA_ISSUE_LOCK_DIR": self._lock_dir.name}
|
|
||||||
self._env_patcher = patch.dict(os.environ, env, clear=True)
|
|
||||||
self._env_patcher.start()
|
self._env_patcher.start()
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
self._env_patcher.stop()
|
self._env_patcher.stop()
|
||||||
self._lock_dir.cleanup()
|
|
||||||
|
|
||||||
@patch(
|
@patch(
|
||||||
"mcp_server.issue_duplicate_context_fetcher",
|
"mcp_server.issue_duplicate_context_fetcher",
|
||||||
@@ -90,8 +87,9 @@ class TestIssueLockArtifactWarning(unittest.TestCase):
|
|||||||
@patch("mcp_server.api_get_all", return_value=[])
|
@patch("mcp_server.api_get_all", return_value=[])
|
||||||
@patch("mcp_server._auth", return_value="token x")
|
@patch("mcp_server._auth", return_value="token x")
|
||||||
@patch("mcp_server._resolve", return_value=("h", "o", "r"))
|
@patch("mcp_server._resolve", return_value=("h", "o", "r"))
|
||||||
|
@patch("mcp_server.ISSUE_LOCK_FILE", new_callable=lambda: tempfile.mktemp())
|
||||||
@patch("issue_lock_worktree.read_worktree_git_state")
|
@patch("issue_lock_worktree.read_worktree_git_state")
|
||||||
def test_lock_success_includes_artifact_warning(self, mock_state, *_mocks):
|
def test_lock_success_includes_artifact_warning(self, mock_state, _lock_file, *_mocks):
|
||||||
mock_state.return_value = {
|
mock_state.return_value = {
|
||||||
"current_branch": "master",
|
"current_branch": "master",
|
||||||
"porcelain_status": "?? _emit_payload.py\n",
|
"porcelain_status": "?? _emit_payload.py\n",
|
||||||
|
|||||||
@@ -66,12 +66,9 @@ class TestCommitPayloads(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.locked_worktree_path = os.path.realpath(self.locked_worktree_dir.name)
|
self.locked_worktree_path = os.path.realpath(self.locked_worktree_dir.name)
|
||||||
|
|
||||||
import issue_lock_store
|
self.lock_file_path = "/tmp/gitea_issue_lock.json"
|
||||||
import issue_lock_provenance
|
import issue_lock_provenance
|
||||||
|
|
||||||
self._lock_dir = tempfile.TemporaryDirectory()
|
|
||||||
os.environ["GITEA_ISSUE_LOCK_DIR"] = self._lock_dir.name
|
|
||||||
|
|
||||||
work_lease = {
|
work_lease = {
|
||||||
"operation_type": "author_issue_work",
|
"operation_type": "author_issue_work",
|
||||||
"issue_number": 263,
|
"issue_number": 263,
|
||||||
@@ -92,7 +89,8 @@ class TestCommitPayloads(unittest.TestCase):
|
|||||||
claimant=work_lease.get("claimant"),
|
claimant=work_lease.get("claimant"),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
self.lock_file_path = issue_lock_store.bind_session_lock(self.lock_data)
|
with open(self.lock_file_path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(json.dumps(self.lock_data))
|
||||||
|
|
||||||
# Reset preflight status to bypass/pass verification in tests
|
# Reset preflight status to bypass/pass verification in tests
|
||||||
self.orig_whoami_called = mcp_server._preflight_whoami_called
|
self.orig_whoami_called = mcp_server._preflight_whoami_called
|
||||||
@@ -116,7 +114,8 @@ class TestCommitPayloads(unittest.TestCase):
|
|||||||
|
|
||||||
self._dir.cleanup()
|
self._dir.cleanup()
|
||||||
self.locked_worktree_dir.cleanup()
|
self.locked_worktree_dir.cleanup()
|
||||||
self._lock_dir.cleanup()
|
if os.path.exists(self.lock_file_path):
|
||||||
|
os.remove(self.lock_file_path)
|
||||||
|
|
||||||
def _env(self, profile: str) -> dict:
|
def _env(self, profile: str) -> dict:
|
||||||
return {
|
return {
|
||||||
@@ -125,7 +124,6 @@ class TestCommitPayloads(unittest.TestCase):
|
|||||||
"GITEA_TOKEN_AUTHOR": "author-pass",
|
"GITEA_TOKEN_AUTHOR": "author-pass",
|
||||||
"GITEA_TEST_PORCELAIN": "",
|
"GITEA_TEST_PORCELAIN": "",
|
||||||
"GITEA_AUTHOR_WORKTREE": self.locked_worktree_path,
|
"GITEA_AUTHOR_WORKTREE": self.locked_worktree_path,
|
||||||
"GITEA_ISSUE_LOCK_DIR": self._lock_dir.name,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@patch("mcp_server.api_request")
|
@patch("mcp_server.api_request")
|
||||||
|
|||||||
@@ -106,32 +106,20 @@ class TestCreateIssueWorkspaceGuard(unittest.TestCase):
|
|||||||
@patch("gitea_mcp_server.issue_lock_worktree.read_worktree_git_state", return_value={"current_branch": "feat/issue-1"})
|
@patch("gitea_mcp_server.issue_lock_worktree.read_worktree_git_state", return_value={"current_branch": "feat/issue-1"})
|
||||||
@patch("os.path.exists", return_value=True)
|
@patch("os.path.exists", return_value=True)
|
||||||
@patch("os.path.isdir", return_value=True)
|
@patch("os.path.isdir", return_value=True)
|
||||||
@patch("author_mutation_worktree.subprocess.run")
|
|
||||||
@patch("subprocess.run")
|
@patch("subprocess.run")
|
||||||
def test_create_issue_wrong_repo_fails_closed(self, mock_run, mock_amw_run, mock_isdir, mock_exists, _git, _get_all, mock_api, _role, _ns, _prof, _auth):
|
def test_create_issue_wrong_repo_fails_closed(self, mock_run, mock_isdir, mock_exists, _git, _get_all, mock_api, _role, _ns, _prof, _auth):
|
||||||
|
# Mock subprocess.run for git --git-common-dir to return a different path
|
||||||
|
mock_res = MagicMock()
|
||||||
|
mock_res.stdout = "/Users/jasonwalker/Development/some-other-repo/.git\n"
|
||||||
|
mock_run.return_value = mock_res
|
||||||
|
|
||||||
wrong_repo_path = os.path.join(CONTROL_CHECKOUT_ROOT, "branches", "feat-issue-1")
|
wrong_repo_path = os.path.join(CONTROL_CHECKOUT_ROOT, "branches", "feat-issue-1")
|
||||||
|
|
||||||
def _subprocess_side_effect(cmd, *args, **kwargs):
|
|
||||||
mock_res = MagicMock(returncode=0)
|
|
||||||
if "--git-common-dir" in cmd:
|
|
||||||
cwd = cmd[cmd.index("-C") + 1] if "-C" in cmd else ""
|
|
||||||
if cwd == wrong_repo_path:
|
|
||||||
mock_res.stdout = "/Users/jasonwalker/Development/some-other-repo/.git\n"
|
|
||||||
else:
|
|
||||||
mock_res.stdout = f"{CONTROL_CHECKOUT_ROOT}/.git\n"
|
|
||||||
else:
|
|
||||||
mock_res.stdout = ""
|
|
||||||
return mock_res
|
|
||||||
|
|
||||||
mock_run.side_effect = _subprocess_side_effect
|
|
||||||
mock_amw_run.side_effect = _subprocess_side_effect
|
|
||||||
|
|
||||||
with patch.object(srv, "PROJECT_ROOT", CONTROL_CHECKOUT_ROOT):
|
with patch.object(srv, "PROJECT_ROOT", CONTROL_CHECKOUT_ROOT):
|
||||||
with patch("gitea_mcp_server._get_workspace_porcelain", return_value=""):
|
with self.assertRaises(RuntimeError) as ctx:
|
||||||
with self.assertRaises(RuntimeError) as ctx:
|
srv.gitea_create_issue(
|
||||||
srv.gitea_create_issue(
|
title="Test issue", body="body", worktree_path=wrong_repo_path
|
||||||
title="Test issue", body="body", worktree_path=wrong_repo_path
|
)
|
||||||
)
|
|
||||||
self.assertIn("does not belong to the target repository", str(ctx.exception))
|
self.assertIn("does not belong to the target repository", str(ctx.exception))
|
||||||
|
|
||||||
@patch("gitea_mcp_server._auth", return_value=FAKE_AUTH)
|
@patch("gitea_mcp_server._auth", return_value=FAKE_AUTH)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Unit tests for own-branch lock adoption decision (#442 / #443)."""
|
"""Unit tests for own-branch lock adoption decision (#442)."""
|
||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -115,7 +115,7 @@ class TestBuildAdoptionProof(unittest.TestCase):
|
|||||||
assessment=assessment,
|
assessment=assessment,
|
||||||
open_pr_checked=True,
|
open_pr_checked=True,
|
||||||
competing_lock_checked=True,
|
competing_lock_checked=True,
|
||||||
lock_file_path="/tmp/example-lock.json",
|
lock_file_path="/tmp/gitea_issue_lock.json",
|
||||||
lock_file_status="written",
|
lock_file_status="written",
|
||||||
)
|
)
|
||||||
for key in (
|
for key in (
|
||||||
@@ -135,4 +135,4 @@ class TestBuildAdoptionProof(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -1,181 +0,0 @@
|
|||||||
"""Unit tests for keyed issue-lock storage (#443)."""
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
from pathlib import Path
|
|
||||||
from unittest import mock
|
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
||||||
|
|
||||||
import issue_lock_store as ils # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _lease(expires_at: str) -> dict:
|
|
||||||
return {
|
|
||||||
"operation_type": ils.AUTHOR_ISSUE_WORK_LEASE,
|
|
||||||
"expires_at": expires_at,
|
|
||||||
"created_at": "2026-01-01T00:00:00Z",
|
|
||||||
"last_heartbeat_at": "2026-01-01T00:00:00Z",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _lock_record(**overrides) -> dict:
|
|
||||||
record = {
|
|
||||||
"issue_number": 420,
|
|
||||||
"branch_name": "feat/issue-420-server-code-parity",
|
|
||||||
"remote": "prgs",
|
|
||||||
"org": "Scaled-Tech-Consulting",
|
|
||||||
"repo": "Gitea-Tools",
|
|
||||||
"worktree_path": "/tmp/wt-420",
|
|
||||||
"work_lease": _lease("2999-01-01T00:00:00Z"),
|
|
||||||
}
|
|
||||||
record.update(overrides)
|
|
||||||
return record
|
|
||||||
|
|
||||||
|
|
||||||
class TestIssueLockStore(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
self._dir = tempfile.TemporaryDirectory()
|
|
||||||
self.lock_dir = self._dir.name
|
|
||||||
self._env = mock.patch.dict(os.environ, {"GITEA_ISSUE_LOCK_DIR": self.lock_dir})
|
|
||||||
self._env.start()
|
|
||||||
|
|
||||||
def tearDown(self):
|
|
||||||
self._env.stop()
|
|
||||||
self._dir.cleanup()
|
|
||||||
|
|
||||||
def test_concurrent_repo_locks_do_not_overwrite(self):
|
|
||||||
lock_a = _lock_record(
|
|
||||||
issue_number=108,
|
|
||||||
branch_name="feat/issue-108-root-menu",
|
|
||||||
repo="mcp-control-plane",
|
|
||||||
worktree_path="/tmp/wt-108",
|
|
||||||
)
|
|
||||||
lock_b = _lock_record(
|
|
||||||
issue_number=420,
|
|
||||||
branch_name="feat/issue-420-server-code-parity",
|
|
||||||
repo="Gitea-Tools",
|
|
||||||
worktree_path="/tmp/wt-420",
|
|
||||||
)
|
|
||||||
path_a = ils.bind_session_lock(lock_a)
|
|
||||||
with mock.patch("os.getpid", return_value=9999):
|
|
||||||
path_b = ils.bind_session_lock(lock_b)
|
|
||||||
|
|
||||||
self.assertNotEqual(path_a, path_b)
|
|
||||||
self.assertTrue(os.path.exists(path_a))
|
|
||||||
self.assertTrue(os.path.exists(path_b))
|
|
||||||
stored_a = ils.read_lock_file(path_a)
|
|
||||||
stored_b = ils.read_lock_file(path_b)
|
|
||||||
self.assertEqual(stored_a["issue_number"], 108)
|
|
||||||
self.assertEqual(stored_b["issue_number"], 420)
|
|
||||||
|
|
||||||
def test_concurrent_issue_locks_same_repo_do_not_overwrite(self):
|
|
||||||
lock_a = _lock_record(issue_number=427, branch_name="feat/issue-427-a")
|
|
||||||
lock_b = _lock_record(issue_number=428, branch_name="feat/issue-428-b")
|
|
||||||
path_a = ils.bind_session_lock(lock_a)
|
|
||||||
with mock.patch("os.getpid", return_value=4242):
|
|
||||||
path_b = ils.bind_session_lock(lock_b)
|
|
||||||
|
|
||||||
self.assertNotEqual(path_a, path_b)
|
|
||||||
self.assertEqual(ils.read_lock_file(path_a)["issue_number"], 427)
|
|
||||||
self.assertEqual(ils.read_lock_file(path_b)["issue_number"], 428)
|
|
||||||
|
|
||||||
def test_foreign_live_lease_blocks_overwrite(self):
|
|
||||||
existing = _lock_record(
|
|
||||||
branch_name="feat/issue-420-other",
|
|
||||||
worktree_path="/tmp/other",
|
|
||||||
work_lease=_lease("2999-01-01T00:00:00Z"),
|
|
||||||
)
|
|
||||||
path = ils.lock_file_path(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo="Gitea-Tools",
|
|
||||||
issue_number=420,
|
|
||||||
)
|
|
||||||
ils.save_lock_file(path, existing)
|
|
||||||
|
|
||||||
incoming = _lock_record(worktree_path="/tmp/mine")
|
|
||||||
block = ils.assess_foreign_lock_overwrite(existing, incoming)
|
|
||||||
self.assertIn("live foreign issue lock", block or "")
|
|
||||||
|
|
||||||
def test_expired_lease_allows_takeover_with_conflict_check(self):
|
|
||||||
existing = _lock_record(
|
|
||||||
branch_name="feat/issue-420-other",
|
|
||||||
worktree_path="/tmp/other",
|
|
||||||
work_lease=_lease("2000-01-01T00:00:00Z"),
|
|
||||||
)
|
|
||||||
incoming = _lock_record(worktree_path="/tmp/mine")
|
|
||||||
self.assertIsNone(ils.assess_foreign_lock_overwrite(existing, incoming))
|
|
||||||
block = ils.assess_same_issue_lease_conflict(
|
|
||||||
existing,
|
|
||||||
issue_number=420,
|
|
||||||
branch_name="feat/issue-420-server-code-parity",
|
|
||||||
worktree_path="/tmp/mine",
|
|
||||||
)
|
|
||||||
self.assertIn("Recovery review is required", block or "")
|
|
||||||
|
|
||||||
def test_same_owner_lease_conflict_allows_refresh(self):
|
|
||||||
worktree = "/tmp/wt-420"
|
|
||||||
existing = _lock_record(worktree_path=worktree)
|
|
||||||
block = ils.assess_same_issue_lease_conflict(
|
|
||||||
existing,
|
|
||||||
issue_number=420,
|
|
||||||
branch_name="feat/issue-420-server-code-parity",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
self.assertIsNone(block)
|
|
||||||
|
|
||||||
def test_find_lock_for_branch_after_restart(self):
|
|
||||||
record = _lock_record()
|
|
||||||
path = ils.lock_file_path(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo="Gitea-Tools",
|
|
||||||
issue_number=420,
|
|
||||||
)
|
|
||||||
ils.save_lock_file(path, record)
|
|
||||||
|
|
||||||
with mock.patch("os.getpid", return_value=5555):
|
|
||||||
self.assertIsNone(ils.read_session_issue_lock())
|
|
||||||
|
|
||||||
found = ils.find_lock_for_branch(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo="Gitea-Tools",
|
|
||||||
branch_name="feat/issue-420-server-code-parity",
|
|
||||||
)
|
|
||||||
self.assertEqual(found["issue_number"], 420)
|
|
||||||
|
|
||||||
def test_has_active_issue_lock_scans_keyed_store(self):
|
|
||||||
ils.bind_session_lock(_lock_record())
|
|
||||||
self.assertTrue(
|
|
||||||
ils.has_active_issue_lock("feat/issue-420-server-code-parity")
|
|
||||||
)
|
|
||||||
self.assertFalse(ils.has_active_issue_lock("feat/issue-999-other"))
|
|
||||||
|
|
||||||
def test_atomic_write_preserves_unrelated_lock(self):
|
|
||||||
path_a = ils.lock_file_path(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo="Gitea-Tools",
|
|
||||||
issue_number=108,
|
|
||||||
)
|
|
||||||
ils.save_lock_file(path_a, _lock_record(issue_number=108, repo="mcp-control-plane"))
|
|
||||||
path_b = ils.lock_file_path(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo="Gitea-Tools",
|
|
||||||
issue_number=420,
|
|
||||||
)
|
|
||||||
ils.save_lock_file(path_b, _lock_record())
|
|
||||||
|
|
||||||
self.assertTrue(os.path.exists(path_a))
|
|
||||||
self.assertTrue(os.path.exists(path_b))
|
|
||||||
self.assertEqual(ils.read_lock_file(path_a)["issue_number"], 108)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
"""Tests for early duplicate-work detection (#400)."""
|
"""Tests for early duplicate-work detection (#400)."""
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
@@ -9,7 +10,6 @@ from unittest.mock import patch
|
|||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
import issue_lock_provenance
|
import issue_lock_provenance
|
||||||
import issue_lock_store
|
|
||||||
import issue_work_duplicate_gate as dup_gate
|
import issue_work_duplicate_gate as dup_gate
|
||||||
import mcp_server
|
import mcp_server
|
||||||
from issue_work_duplicate_gate import (
|
from issue_work_duplicate_gate import (
|
||||||
@@ -142,29 +142,26 @@ class TestInjectableDuplicateFetcher(unittest.TestCase):
|
|||||||
"porcelain_status": "",
|
"porcelain_status": "",
|
||||||
"base_equivalent": True,
|
"base_equivalent": True,
|
||||||
},
|
},
|
||||||
):
|
), patch.dict(os.environ, {
|
||||||
with tempfile.TemporaryDirectory() as lock_dir:
|
"GITEA_ALLOWED_OPERATIONS": "gitea.issue.comment",
|
||||||
with patch.dict(os.environ, {
|
}, clear=True):
|
||||||
"GITEA_ALLOWED_OPERATIONS": "gitea.issue.comment",
|
with patch.object(mcp_server, "ISSUE_LOCK_FILE", tempfile.mktemp()):
|
||||||
"GITEA_ISSUE_LOCK_DIR": lock_dir,
|
mcp_server.gitea_lock_issue(
|
||||||
}, clear=True):
|
issue_number=400,
|
||||||
mcp_server.gitea_lock_issue(
|
branch_name="feat/issue-400-duplicate-work-preflight",
|
||||||
issue_number=400,
|
remote="prgs",
|
||||||
branch_name="feat/issue-400-duplicate-work-preflight",
|
)
|
||||||
remote="prgs",
|
|
||||||
)
|
|
||||||
self.assertEqual(seen["issue_number"], 400)
|
self.assertEqual(seen["issue_number"], 400)
|
||||||
|
|
||||||
|
|
||||||
class TestMcpDuplicateRecheck(unittest.TestCase):
|
class TestMcpDuplicateRecheck(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self._dir = tempfile.TemporaryDirectory()
|
self._dir = tempfile.TemporaryDirectory()
|
||||||
self._env_patch = patch.dict(
|
self.lock_path = os.path.join(self._dir.name, "gitea_issue_lock.json")
|
||||||
os.environ,
|
self._lock_patch = patch.object(
|
||||||
{"GITEA_ISSUE_LOCK_DIR": self._dir.name},
|
mcp_server, "ISSUE_LOCK_FILE", self.lock_path
|
||||||
clear=False,
|
|
||||||
)
|
)
|
||||||
self._env_patch.start()
|
self._lock_patch.start()
|
||||||
self._remotes = patch.dict(mcp_server.REMOTES, {
|
self._remotes = patch.dict(mcp_server.REMOTES, {
|
||||||
"prgs": {"host": "gitea.example.com", "org": "Example-Org",
|
"prgs": {"host": "gitea.example.com", "org": "Example-Org",
|
||||||
"repo": "Example-Repo"},
|
"repo": "Example-Repo"},
|
||||||
@@ -177,7 +174,6 @@ class TestMcpDuplicateRecheck(unittest.TestCase):
|
|||||||
self._dir.cleanup()
|
self._dir.cleanup()
|
||||||
|
|
||||||
def _write_lock(self, issue_number=400, branch="feat/issue-400-x"):
|
def _write_lock(self, issue_number=400, branch="feat/issue-400-x"):
|
||||||
worktree_path = os.path.realpath(os.getcwd())
|
|
||||||
work_lease = {
|
work_lease = {
|
||||||
"operation_type": "author_issue_work",
|
"operation_type": "author_issue_work",
|
||||||
"issue_number": issue_number,
|
"issue_number": issue_number,
|
||||||
@@ -185,19 +181,17 @@ class TestMcpDuplicateRecheck(unittest.TestCase):
|
|||||||
"claimant": {"username": "test-user", "profile": "test-author"},
|
"claimant": {"username": "test-user", "profile": "test-author"},
|
||||||
"expires_at": "2999-01-01T00:00:00Z",
|
"expires_at": "2999-01-01T00:00:00Z",
|
||||||
}
|
}
|
||||||
issue_lock_store.bind_session_lock({
|
with open(self.lock_path, "w", encoding="utf-8") as fh:
|
||||||
"issue_number": issue_number,
|
json.dump({
|
||||||
"branch_name": branch,
|
"issue_number": issue_number,
|
||||||
"remote": "prgs",
|
"branch_name": branch,
|
||||||
"org": "Example-Org",
|
"remote": "prgs",
|
||||||
"repo": "Example-Repo",
|
"work_lease": work_lease,
|
||||||
"worktree_path": worktree_path,
|
"lock_provenance": issue_lock_provenance.build_sanctioned_lock_provenance(
|
||||||
"work_lease": work_lease,
|
tool="gitea_lock_issue",
|
||||||
"lock_provenance": issue_lock_provenance.build_sanctioned_lock_provenance(
|
claimant=work_lease.get("claimant"),
|
||||||
tool="gitea_lock_issue",
|
),
|
||||||
claimant=work_lease.get("claimant"),
|
}, fh)
|
||||||
),
|
|
||||||
})
|
|
||||||
|
|
||||||
@patch("mcp_server._assess_issue_duplicate_gate")
|
@patch("mcp_server._assess_issue_duplicate_gate")
|
||||||
@patch("mcp_server.get_profile", return_value={
|
@patch("mcp_server.get_profile", return_value={
|
||||||
@@ -261,7 +255,6 @@ class TestMcpDuplicateRecheck(unittest.TestCase):
|
|||||||
base="master",
|
base="master",
|
||||||
body="Closes #400",
|
body="Closes #400",
|
||||||
remote="prgs",
|
remote="prgs",
|
||||||
worktree_path=os.path.realpath(os.getcwd()),
|
|
||||||
)
|
)
|
||||||
self.assertFalse(result["success"])
|
self.assertFalse(result["success"])
|
||||||
self.assertIsNone(result.get("number"))
|
self.assertIsNone(result.get("number"))
|
||||||
|
|||||||
+162
-184
@@ -6,7 +6,6 @@ the MCP protocol) with mocked API responses.
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import patch, MagicMock
|
from unittest.mock import patch, MagicMock
|
||||||
|
|
||||||
@@ -46,7 +45,6 @@ from gitea_auth import get_profile # noqa: E402
|
|||||||
import gitea_config # noqa: E402
|
import gitea_config # noqa: E402
|
||||||
|
|
||||||
import mcp_server
|
import mcp_server
|
||||||
import issue_lock_store
|
|
||||||
|
|
||||||
FAKE_AUTH = "Basic dGVzdDp0ZXN0"
|
FAKE_AUTH = "Basic dGVzdDp0ZXN0"
|
||||||
|
|
||||||
@@ -176,7 +174,6 @@ def _sample_issue_lock(issue_number=123, branch_name="feat/x", **overrides):
|
|||||||
"remote": "dadeschools",
|
"remote": "dadeschools",
|
||||||
"org": "Scaled-Tech-Consulting",
|
"org": "Scaled-Tech-Consulting",
|
||||||
"repo": "Gitea-Tools",
|
"repo": "Gitea-Tools",
|
||||||
"worktree_path": "/tmp/test-worktree",
|
|
||||||
"work_lease": work_lease,
|
"work_lease": work_lease,
|
||||||
"lock_provenance": issue_lock_provenance.build_sanctioned_lock_provenance(
|
"lock_provenance": issue_lock_provenance.build_sanctioned_lock_provenance(
|
||||||
tool="gitea_lock_issue",
|
tool="gitea_lock_issue",
|
||||||
@@ -192,17 +189,6 @@ def _clear_duplicate_context_fetcher(*_args, **_kwargs):
|
|||||||
return [], [], {"status": "not_claimed"}
|
return [], [], {"status": "not_claimed"}
|
||||||
|
|
||||||
|
|
||||||
def _bind_test_lock(**overrides) -> str:
|
|
||||||
remote = overrides.get("remote", "dadeschools")
|
|
||||||
record = _sample_issue_lock(**overrides)
|
|
||||||
if remote in mcp_server.REMOTES:
|
|
||||||
profile = mcp_server.REMOTES[remote]
|
|
||||||
record.setdefault("org", profile["org"])
|
|
||||||
record.setdefault("repo", profile["repo"])
|
|
||||||
record["remote"] = remote
|
|
||||||
return issue_lock_store.bind_session_lock(record)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Create Issue
|
# Create Issue
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -265,21 +251,18 @@ class TestCreatePR(unittest.TestCase):
|
|||||||
return_value=(True, []))
|
return_value=(True, []))
|
||||||
@patch("mcp_server.api_request")
|
@patch("mcp_server.api_request")
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_creates_pr(self, _auth, mock_api, _role, _dup_fetcher):
|
@patch("os.path.exists", return_value=True)
|
||||||
worktree = os.path.realpath(os.getcwd())
|
@patch("builtins.open")
|
||||||
|
def test_creates_pr(self, mock_open, mock_exists, _auth, mock_api, _role, _dup_fetcher):
|
||||||
|
lock_json = json.dumps(_sample_issue_lock(issue_number=123, branch_name="feat/x"))
|
||||||
|
mock_open.return_value.__enter__.return_value.read.return_value = lock_json
|
||||||
mock_api.return_value = {"number": 3, "html_url": "https://example.com/pulls/3"}
|
mock_api.return_value = {"number": 3, "html_url": "https://example.com/pulls/3"}
|
||||||
with tempfile.TemporaryDirectory() as lock_dir:
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
env = {**CREATE_PR_ENV, "GITEA_ISSUE_LOCK_DIR": lock_dir}
|
result = gitea_create_pr(title="feat: X Closes #123", head="feat/x", base="main")
|
||||||
with patch.dict(os.environ, env, clear=True):
|
|
||||||
_bind_test_lock(issue_number=123, branch_name="feat/x", worktree_path=worktree)
|
|
||||||
result = gitea_create_pr(
|
|
||||||
title="feat: X Closes #123",
|
|
||||||
head="feat/x",
|
|
||||||
base="main",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
self.assertEqual(result["number"], 3)
|
self.assertEqual(result["number"], 3)
|
||||||
self.assertNotIn("url", result)
|
self.assertNotIn("url", result)
|
||||||
|
mock_exists.assert_called_with(ISSUE_LOCK_FILE)
|
||||||
|
mock_open.assert_called_with(ISSUE_LOCK_FILE, "r", encoding="utf-8")
|
||||||
payload = mock_api.call_args[0][3]
|
payload = mock_api.call_args[0][3]
|
||||||
self.assertEqual(payload["head"], "feat/x")
|
self.assertEqual(payload["head"], "feat/x")
|
||||||
self.assertEqual(payload["base"], "main")
|
self.assertEqual(payload["base"], "main")
|
||||||
@@ -293,42 +276,30 @@ class TestCreatePR(unittest.TestCase):
|
|||||||
return_value=(True, []))
|
return_value=(True, []))
|
||||||
@patch("mcp_server.api_request")
|
@patch("mcp_server.api_request")
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_create_pr_reveal_opt_in_includes_url(self, _auth, mock_api, _role, _dup_fetcher):
|
@patch("os.path.exists", return_value=True)
|
||||||
worktree = os.path.realpath(os.getcwd())
|
@patch("builtins.open")
|
||||||
|
def test_create_pr_reveal_opt_in_includes_url(self, mock_open, mock_exists, _auth, mock_api, _role, _dup_fetcher):
|
||||||
|
lock_json = json.dumps(_sample_issue_lock(issue_number=123, branch_name="feat/x"))
|
||||||
|
mock_open.return_value.__enter__.return_value.read.return_value = lock_json
|
||||||
mock_api.return_value = {"number": 3, "html_url": "https://example.com/pulls/3"}
|
mock_api.return_value = {"number": 3, "html_url": "https://example.com/pulls/3"}
|
||||||
with tempfile.TemporaryDirectory() as lock_dir:
|
env = {**CREATE_PR_ENV, "GITEA_MCP_REVEAL_ENDPOINTS": "1"}
|
||||||
env = {**CREATE_PR_ENV, "GITEA_ISSUE_LOCK_DIR": lock_dir, "GITEA_MCP_REVEAL_ENDPOINTS": "1"}
|
with patch.dict(os.environ, env, clear=True):
|
||||||
with patch.dict(os.environ, env, clear=True):
|
result = gitea_create_pr(title="feat: X Closes #123", head="feat/x", base="main")
|
||||||
_bind_test_lock(issue_number=123, branch_name="feat/x", worktree_path=worktree)
|
|
||||||
result = gitea_create_pr(
|
|
||||||
title="feat: X Closes #123",
|
|
||||||
head="feat/x",
|
|
||||||
base="main",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
self.assertIn("pulls/3", result["url"])
|
self.assertIn("pulls/3", result["url"])
|
||||||
|
|
||||||
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
||||||
return_value=(True, []))
|
return_value=(True, []))
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_create_pr_locked_issue_mismatch_fails(self, _auth, _role):
|
@patch("os.path.exists", return_value=True)
|
||||||
worktree = os.path.realpath(os.getcwd())
|
@patch("builtins.open")
|
||||||
with tempfile.TemporaryDirectory() as lock_dir:
|
def test_create_pr_locked_issue_mismatch_fails(self, mock_open, mock_exists, _auth, _role):
|
||||||
env = {**CREATE_PR_ENV, "GITEA_ISSUE_LOCK_DIR": lock_dir}
|
lock_json = json.dumps(_sample_issue_lock(issue_number=123, branch_name="feat/x"))
|
||||||
with patch.dict(os.environ, env, clear=True):
|
mock_open.return_value.__enter__.return_value.read.return_value = lock_json
|
||||||
_bind_test_lock(
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
issue_number=123,
|
with self.assertRaises(ValueError) as ctx:
|
||||||
branch_name="feat/x",
|
gitea_create_pr(title="feat: X Closes #999", head="feat/x", base="main")
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
with self.assertRaises(ValueError) as ctx:
|
|
||||||
gitea_create_pr(
|
|
||||||
title="feat: X Closes #999",
|
|
||||||
head="feat/x",
|
|
||||||
base="main",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
self.assertIn("Closes #123", str(ctx.exception))
|
self.assertIn("Closes #123", str(ctx.exception))
|
||||||
|
mock_open.assert_called_with(ISSUE_LOCK_FILE, "r", encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -3213,12 +3184,7 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
"""Test issue locking and PR gating constraints."""
|
"""Test issue locking and PR gating constraints."""
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self._lock_dir = tempfile.TemporaryDirectory()
|
self._env_patcher = patch.dict(os.environ, ISSUE_WRITE_ENV, clear=True)
|
||||||
env = {
|
|
||||||
**ISSUE_WRITE_ENV,
|
|
||||||
"GITEA_ISSUE_LOCK_DIR": self._lock_dir.name,
|
|
||||||
}
|
|
||||||
self._env_patcher = patch.dict(os.environ, env, clear=True)
|
|
||||||
self._env_patcher.start()
|
self._env_patcher.start()
|
||||||
self._dup_fetcher_patcher = patch(
|
self._dup_fetcher_patcher = patch(
|
||||||
"mcp_server.issue_duplicate_context_fetcher",
|
"mcp_server.issue_duplicate_context_fetcher",
|
||||||
@@ -3229,13 +3195,8 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
self._dup_fetcher_patcher.stop()
|
self._dup_fetcher_patcher.stop()
|
||||||
self._env_patcher.stop()
|
self._env_patcher.stop()
|
||||||
self._lock_dir.cleanup()
|
if os.path.exists(ISSUE_LOCK_FILE):
|
||||||
|
os.remove(ISSUE_LOCK_FILE)
|
||||||
def _create_pr_env(self) -> dict:
|
|
||||||
return {
|
|
||||||
**CREATE_PR_ENV,
|
|
||||||
"GITEA_ISSUE_LOCK_DIR": self._lock_dir.name,
|
|
||||||
}
|
|
||||||
|
|
||||||
@patch(
|
@patch(
|
||||||
"mcp_server.issue_lock_worktree.read_worktree_git_state",
|
"mcp_server.issue_lock_worktree.read_worktree_git_state",
|
||||||
@@ -3253,8 +3214,9 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
self.assertIn("expires_at", res["work_lease"])
|
self.assertIn("expires_at", res["work_lease"])
|
||||||
self.assertIn("last_heartbeat_at", res["work_lease"])
|
self.assertIn("last_heartbeat_at", res["work_lease"])
|
||||||
self.assertEqual(res["work_lease"]["claimant"]["profile"], "gitea-default")
|
self.assertEqual(res["work_lease"]["claimant"]["profile"], "gitea-default")
|
||||||
self.assertIn("lock_file_path", res)
|
self.assertTrue(os.path.exists(ISSUE_LOCK_FILE))
|
||||||
lock = issue_lock_store.read_lock_file(res["lock_file_path"])
|
with open(ISSUE_LOCK_FILE, encoding="utf-8") as f:
|
||||||
|
lock = json.load(f)
|
||||||
self.assertIn("worktree_path", lock)
|
self.assertIn("worktree_path", lock)
|
||||||
self.assertIn("work_lease", lock)
|
self.assertIn("work_lease", lock)
|
||||||
|
|
||||||
@@ -3316,14 +3278,90 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
@patch("mcp_server.api_get_all")
|
@patch("mcp_server.api_get_all")
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_lock_issue_adopts_exact_own_branch(self, _auth, mock_api, _git_state):
|
def test_lock_issue_adopts_own_existing_branch(self, _auth, mock_api, _git_state):
|
||||||
branch = "feat/issue-196-mutations"
|
# #442: the issue's own already-pushed branch is adoptable for recovery.
|
||||||
self.mock_dup_fetcher.return_value = ([], [branch], {"status": "not_claimed"})
|
sha = "934688a71dd19d9b46369e73fb3ac356ee0cc211"
|
||||||
mock_api.return_value = [{"name": branch, "commit": {"id": "abc123"}}]
|
|
||||||
res = gitea_lock_issue(issue_number=196, branch_name=branch, remote="prgs")
|
def _api(url, *a, **k):
|
||||||
|
if "/pulls" in url:
|
||||||
|
return []
|
||||||
|
if "/branches" in url:
|
||||||
|
return [{"name": "feat/issue-196-mutations", "commit": {"id": sha}}]
|
||||||
|
return []
|
||||||
|
|
||||||
|
mock_api.side_effect = _api
|
||||||
|
res = gitea_lock_issue(
|
||||||
|
issue_number=196, branch_name="feat/issue-196-mutations", remote="prgs"
|
||||||
|
)
|
||||||
self.assertTrue(res["success"])
|
self.assertTrue(res["success"])
|
||||||
self.assertIn("adoption", res)
|
self.assertIn("adoption", res)
|
||||||
self.assertEqual(res["adoption"]["branch_head_commit"], "abc123")
|
proof = res["adoption"]
|
||||||
|
self.assertEqual(proof["issue_number"], 196)
|
||||||
|
self.assertEqual(proof["branch_name"], "feat/issue-196-mutations")
|
||||||
|
self.assertEqual(proof["branch_head_commit"], sha)
|
||||||
|
self.assertTrue(proof["no_existing_pr_proof"])
|
||||||
|
self.assertTrue(proof["no_competing_live_lock_proof"])
|
||||||
|
self.assertEqual(proof["lock_file_path"], ISSUE_LOCK_FILE)
|
||||||
|
self.assertIn("adopt", proof["adoption_reason"].lower())
|
||||||
|
self.assertTrue(os.path.exists(ISSUE_LOCK_FILE))
|
||||||
|
|
||||||
|
@patch(
|
||||||
|
"mcp_server.issue_lock_worktree.read_worktree_git_state",
|
||||||
|
return_value=_clean_master_git_state_for_lock(),
|
||||||
|
)
|
||||||
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
|
def test_lock_issue_open_pr_blocks_adoption(self, _auth, _git_state):
|
||||||
|
# Even with the exact own branch present, an open PR blocks adoption.
|
||||||
|
self.mock_dup_fetcher.return_value = ([{
|
||||||
|
"number": 200,
|
||||||
|
"head": {"ref": "feat/issue-196-mutations"},
|
||||||
|
"title": "WIP",
|
||||||
|
"body": "",
|
||||||
|
}], ["feat/issue-196-mutations"], {"status": "not_claimed"})
|
||||||
|
with self.assertRaises(ValueError) as ctx:
|
||||||
|
gitea_lock_issue(
|
||||||
|
issue_number=196, branch_name="feat/issue-196-mutations", remote="prgs"
|
||||||
|
)
|
||||||
|
self.assertIn("open PR #200 already covers issue", str(ctx.exception))
|
||||||
|
self.assertFalse(os.path.exists(ISSUE_LOCK_FILE))
|
||||||
|
|
||||||
|
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
||||||
|
return_value=(True, []))
|
||||||
|
@patch(
|
||||||
|
"mcp_server.issue_lock_worktree.read_worktree_git_state",
|
||||||
|
return_value=_clean_master_git_state_for_lock(),
|
||||||
|
)
|
||||||
|
@patch("mcp_server.api_request")
|
||||||
|
@patch("mcp_server.api_get_all")
|
||||||
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
|
def test_create_pr_proceeds_after_adopted_lock(
|
||||||
|
self, _auth, mock_api, mock_req, _git_state, _role
|
||||||
|
):
|
||||||
|
# #442 recovery goal: after adopting the own branch, create_pr proceeds.
|
||||||
|
sha = "934688a71dd19d9b46369e73fb3ac356ee0cc211"
|
||||||
|
|
||||||
|
def _api(url, *a, **k):
|
||||||
|
if "/pulls" in url:
|
||||||
|
return []
|
||||||
|
if "/branches" in url:
|
||||||
|
return [{"name": "feat/issue-196-mutations", "commit": {"id": sha}}]
|
||||||
|
return []
|
||||||
|
|
||||||
|
mock_api.side_effect = _api
|
||||||
|
lock_res = gitea_lock_issue(
|
||||||
|
issue_number=196, branch_name="feat/issue-196-mutations", remote="prgs"
|
||||||
|
)
|
||||||
|
self.assertIn("adoption", lock_res)
|
||||||
|
|
||||||
|
mock_req.return_value = {"number": 7, "html_url": "https://gitea.prgs.cc/pulls/7"}
|
||||||
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
|
pr = gitea_create_pr(
|
||||||
|
title="feat: parity gate Closes #196",
|
||||||
|
head="feat/issue-196-mutations",
|
||||||
|
base="master",
|
||||||
|
remote="prgs",
|
||||||
|
)
|
||||||
|
self.assertEqual(pr["number"], 7)
|
||||||
|
|
||||||
@patch(
|
@patch(
|
||||||
"mcp_server.issue_lock_worktree.read_worktree_git_state",
|
"mcp_server.issue_lock_worktree.read_worktree_git_state",
|
||||||
@@ -3332,27 +3370,16 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
@patch("mcp_server.api_get_all", return_value=[])
|
@patch("mcp_server.api_get_all", return_value=[])
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_lock_issue_blocks_active_same_operation_lease(self, _auth, _api, _git_state):
|
def test_lock_issue_blocks_active_same_operation_lease(self, _auth, _api, _git_state):
|
||||||
prgs_repo = mcp_server.REMOTES["prgs"]["repo"]
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
issue_lock_store.save_lock_file(
|
json.dump({
|
||||||
issue_lock_store.lock_file_path(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo=prgs_repo,
|
|
||||||
issue_number=196,
|
|
||||||
),
|
|
||||||
{
|
|
||||||
"issue_number": 196,
|
"issue_number": 196,
|
||||||
"branch_name": "feat/issue-196-other-work",
|
"branch_name": "feat/issue-196-other-work",
|
||||||
"remote": "prgs",
|
|
||||||
"org": "Scaled-Tech-Consulting",
|
|
||||||
"repo": prgs_repo,
|
|
||||||
"worktree_path": "/tmp/other-worktree",
|
"worktree_path": "/tmp/other-worktree",
|
||||||
"work_lease": {
|
"work_lease": {
|
||||||
"operation_type": "author_issue_work",
|
"operation_type": "author_issue_work",
|
||||||
"expires_at": "2999-01-01T00:00:00Z",
|
"expires_at": "2999-01-01T00:00:00Z",
|
||||||
},
|
},
|
||||||
},
|
}, f)
|
||||||
)
|
|
||||||
with self.assertRaises(RuntimeError) as ctx:
|
with self.assertRaises(RuntimeError) as ctx:
|
||||||
gitea_lock_issue(issue_number=196, branch_name="feat/issue-196-mutations", remote="prgs")
|
gitea_lock_issue(issue_number=196, branch_name="feat/issue-196-mutations", remote="prgs")
|
||||||
self.assertIn("already has an active author_issue_work lease", str(ctx.exception))
|
self.assertIn("already has an active author_issue_work lease", str(ctx.exception))
|
||||||
@@ -3364,27 +3391,16 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
@patch("mcp_server.api_get_all", return_value=[])
|
@patch("mcp_server.api_get_all", return_value=[])
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_lock_issue_blocks_expired_same_operation_lease_for_recovery(self, _auth, _api, _git_state):
|
def test_lock_issue_blocks_expired_same_operation_lease_for_recovery(self, _auth, _api, _git_state):
|
||||||
prgs_repo = mcp_server.REMOTES["prgs"]["repo"]
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
issue_lock_store.save_lock_file(
|
json.dump({
|
||||||
issue_lock_store.lock_file_path(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo=prgs_repo,
|
|
||||||
issue_number=196,
|
|
||||||
),
|
|
||||||
{
|
|
||||||
"issue_number": 196,
|
"issue_number": 196,
|
||||||
"branch_name": "feat/issue-196-other-work",
|
"branch_name": "feat/issue-196-other-work",
|
||||||
"remote": "prgs",
|
|
||||||
"org": "Scaled-Tech-Consulting",
|
|
||||||
"repo": prgs_repo,
|
|
||||||
"worktree_path": "/tmp/other-worktree",
|
"worktree_path": "/tmp/other-worktree",
|
||||||
"work_lease": {
|
"work_lease": {
|
||||||
"operation_type": "author_issue_work",
|
"operation_type": "author_issue_work",
|
||||||
"expires_at": "2000-01-01T00:00:00Z",
|
"expires_at": "2000-01-01T00:00:00Z",
|
||||||
},
|
},
|
||||||
},
|
}, f)
|
||||||
)
|
|
||||||
with self.assertRaises(RuntimeError) as ctx:
|
with self.assertRaises(RuntimeError) as ctx:
|
||||||
gitea_lock_issue(issue_number=196, branch_name="feat/issue-196-mutations", remote="prgs")
|
gitea_lock_issue(issue_number=196, branch_name="feat/issue-196-mutations", remote="prgs")
|
||||||
self.assertIn("Recovery review is required before takeover", str(ctx.exception))
|
self.assertIn("Recovery review is required before takeover", str(ctx.exception))
|
||||||
@@ -3451,7 +3467,9 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
return_value=(True, []))
|
return_value=(True, []))
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_create_pr_missing_lock_fails(self, _auth, _role):
|
def test_create_pr_missing_lock_fails(self, _auth, _role):
|
||||||
with patch.dict(os.environ, self._create_pr_env(), clear=True):
|
if os.path.exists(ISSUE_LOCK_FILE):
|
||||||
|
os.remove(ISSUE_LOCK_FILE)
|
||||||
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
with self.assertRaises(RuntimeError) as ctx:
|
with self.assertRaises(RuntimeError) as ctx:
|
||||||
gitea_create_pr(title="feat: X Closes #196", head="feat/issue-196-mutations", remote="prgs")
|
gitea_create_pr(title="feat: X Closes #196", head="feat/issue-196-mutations", remote="prgs")
|
||||||
self.assertIn("Issue lock is missing", str(ctx.exception))
|
self.assertIn("Issue lock is missing", str(ctx.exception))
|
||||||
@@ -3460,64 +3478,37 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
return_value=(True, []))
|
return_value=(True, []))
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_create_pr_branch_mismatch_fails(self, _auth, _role):
|
def test_create_pr_branch_mismatch_fails(self, _auth, _role):
|
||||||
worktree = os.path.realpath(os.getcwd())
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
_bind_test_lock(
|
json.dump(_sample_issue_lock(
|
||||||
issue_number=196,
|
issue_number=196, branch_name="feat/issue-196-mutations"), f)
|
||||||
branch_name="feat/issue-196-mutations",
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
remote="prgs",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
with patch.dict(os.environ, self._create_pr_env(), clear=True):
|
|
||||||
with self.assertRaises(ValueError) as ctx:
|
with self.assertRaises(ValueError) as ctx:
|
||||||
gitea_create_pr(
|
gitea_create_pr(title="feat: X Closes #196", head="feat/issue-196-different", remote="prgs")
|
||||||
title="feat: X Closes #196",
|
|
||||||
head="feat/issue-196-different",
|
|
||||||
remote="prgs",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
self.assertIn("does not match locked branch", str(ctx.exception))
|
self.assertIn("does not match locked branch", str(ctx.exception))
|
||||||
|
|
||||||
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
||||||
return_value=(True, []))
|
return_value=(True, []))
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_create_pr_forbidden_terms_fails(self, _auth, _role):
|
def test_create_pr_forbidden_terms_fails(self, _auth, _role):
|
||||||
worktree = os.path.realpath(os.getcwd())
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
_bind_test_lock(
|
json.dump(_sample_issue_lock(
|
||||||
issue_number=196,
|
issue_number=196, branch_name="feat/issue-196-mutations"), f)
|
||||||
branch_name="feat/issue-196-mutations",
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
remote="prgs",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
with patch.dict(os.environ, self._create_pr_env(), clear=True):
|
|
||||||
for term in ("equivalent to #196", "related to #196", "same as #196"):
|
for term in ("equivalent to #196", "related to #196", "same as #196"):
|
||||||
with self.assertRaises(ValueError) as ctx:
|
with self.assertRaises(ValueError) as ctx:
|
||||||
gitea_create_pr(
|
gitea_create_pr(title=f"feat: X {term}", head="feat/issue-196-mutations", remote="prgs")
|
||||||
title=f"feat: X {term}",
|
|
||||||
head="feat/issue-196-mutations",
|
|
||||||
remote="prgs",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
self.assertIn("contains forbidden term", str(ctx.exception))
|
self.assertIn("contains forbidden term", str(ctx.exception))
|
||||||
|
|
||||||
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
||||||
return_value=(True, []))
|
return_value=(True, []))
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_create_pr_missing_closes_ref_fails(self, _auth, _role):
|
def test_create_pr_missing_closes_ref_fails(self, _auth, _role):
|
||||||
worktree = os.path.realpath(os.getcwd())
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
_bind_test_lock(
|
json.dump(_sample_issue_lock(
|
||||||
issue_number=196,
|
issue_number=196, branch_name="feat/issue-196-mutations"), f)
|
||||||
branch_name="feat/issue-196-mutations",
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
remote="prgs",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
with patch.dict(os.environ, self._create_pr_env(), clear=True):
|
|
||||||
with self.assertRaises(ValueError) as ctx:
|
with self.assertRaises(ValueError) as ctx:
|
||||||
gitea_create_pr(
|
gitea_create_pr(title="feat: X refs #196", head="feat/issue-196-mutations", remote="prgs")
|
||||||
title="feat: X refs #196",
|
|
||||||
head="feat/issue-196-mutations",
|
|
||||||
remote="prgs",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
self.assertIn("must contain 'Closes #196' or 'Fixes #196' exactly", str(ctx.exception))
|
self.assertIn("must contain 'Closes #196' or 'Fixes #196' exactly", str(ctx.exception))
|
||||||
|
|
||||||
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
@patch("mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
|
||||||
@@ -3525,13 +3516,13 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_create_pr_worktree_mismatch_fails(self, _auth, _role):
|
def test_create_pr_worktree_mismatch_fails(self, _auth, _role):
|
||||||
scratch = os.path.realpath("/tmp/gitea-tools-author-scratch/issue-249-pr")
|
scratch = os.path.realpath("/tmp/gitea-tools-author-scratch/issue-249-pr")
|
||||||
_bind_test_lock(
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
issue_number=249,
|
json.dump(_sample_issue_lock(
|
||||||
branch_name="feat/issue-249-issue-lock-scratch-worktree",
|
issue_number=249,
|
||||||
worktree_path=scratch,
|
branch_name="feat/issue-249-issue-lock-scratch-worktree",
|
||||||
remote="prgs",
|
worktree_path=scratch,
|
||||||
)
|
), f)
|
||||||
with patch.dict(os.environ, self._create_pr_env(), clear=True):
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
with self.assertRaises(ValueError) as ctx:
|
with self.assertRaises(ValueError) as ctx:
|
||||||
gitea_create_pr(
|
gitea_create_pr(
|
||||||
title="feat: lock scratch worktree Closes #249",
|
title="feat: lock scratch worktree Closes #249",
|
||||||
@@ -3545,35 +3536,22 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
return_value=(True, []))
|
return_value=(True, []))
|
||||||
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
@patch("mcp_server.get_auth_header", return_value=FAKE_AUTH)
|
||||||
def test_create_pr_manual_lock_seed_blocked(self, _auth, _role):
|
def test_create_pr_manual_lock_seed_blocked(self, _auth, _role):
|
||||||
worktree = os.path.realpath(os.getcwd())
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
with tempfile.TemporaryDirectory() as lock_dir:
|
json.dump(
|
||||||
env = {**self._create_pr_env(), "GITEA_ISSUE_LOCK_DIR": lock_dir}
|
|
||||||
with patch.dict(os.environ, env, clear=True):
|
|
||||||
issue_lock_store.save_lock_file(
|
|
||||||
issue_lock_store.lock_file_path(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo=mcp_server.REMOTES["prgs"]["repo"],
|
|
||||||
issue_number=447,
|
|
||||||
lock_dir=lock_dir,
|
|
||||||
),
|
|
||||||
_sample_issue_lock(
|
_sample_issue_lock(
|
||||||
issue_number=447,
|
issue_number=447,
|
||||||
branch_name="feat/issue-447-lock-provenance",
|
branch_name="feat/issue-447-lock-provenance",
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo=mcp_server.REMOTES["prgs"]["repo"],
|
|
||||||
worktree_path=worktree,
|
|
||||||
lock_provenance=None,
|
lock_provenance=None,
|
||||||
),
|
),
|
||||||
|
f,
|
||||||
|
)
|
||||||
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
|
with self.assertRaises(RuntimeError) as ctx:
|
||||||
|
gitea_create_pr(
|
||||||
|
title="feat: lock provenance Closes #447",
|
||||||
|
head="feat/issue-447-lock-provenance",
|
||||||
|
remote="prgs",
|
||||||
)
|
)
|
||||||
with self.assertRaises(RuntimeError) as ctx:
|
|
||||||
gitea_create_pr(
|
|
||||||
title="feat: lock provenance Closes #447",
|
|
||||||
head="feat/issue-447-lock-provenance",
|
|
||||||
remote="prgs",
|
|
||||||
worktree_path=worktree,
|
|
||||||
)
|
|
||||||
self.assertIn("lock provenance", str(ctx.exception).lower())
|
self.assertIn("lock provenance", str(ctx.exception).lower())
|
||||||
|
|
||||||
@patch("mcp_server.api_request")
|
@patch("mcp_server.api_request")
|
||||||
@@ -3583,13 +3561,13 @@ class TestIssueLocking(unittest.TestCase):
|
|||||||
def test_create_pr_honors_scratch_worktree_lock(self, _auth, _role, mock_api):
|
def test_create_pr_honors_scratch_worktree_lock(self, _auth, _role, mock_api):
|
||||||
scratch = os.path.realpath("/tmp/gitea-tools-author-scratch/issue-249-e2e")
|
scratch = os.path.realpath("/tmp/gitea-tools-author-scratch/issue-249-e2e")
|
||||||
mock_api.return_value = {"number": 250, "html_url": "https://example/pr/250"}
|
mock_api.return_value = {"number": 250, "html_url": "https://example/pr/250"}
|
||||||
_bind_test_lock(
|
with open(ISSUE_LOCK_FILE, "w", encoding="utf-8") as f:
|
||||||
issue_number=249,
|
json.dump(_sample_issue_lock(
|
||||||
branch_name="feat/issue-249-issue-lock-scratch-worktree",
|
issue_number=249,
|
||||||
worktree_path=scratch,
|
branch_name="feat/issue-249-issue-lock-scratch-worktree",
|
||||||
remote="prgs",
|
worktree_path=scratch,
|
||||||
)
|
), f)
|
||||||
with patch.dict(os.environ, self._create_pr_env(), clear=True):
|
with patch.dict(os.environ, CREATE_PR_ENV, clear=True):
|
||||||
res = gitea_create_pr(
|
res = gitea_create_pr(
|
||||||
title="feat: issue-lock scratch worktree Closes #249",
|
title="feat: issue-lock scratch worktree Closes #249",
|
||||||
head="feat/issue-249-issue-lock-scratch-worktree",
|
head="feat/issue-249-issue-lock-scratch-worktree",
|
||||||
|
|||||||
@@ -1,153 +0,0 @@
|
|||||||
"""Tests for runtime_context / mutation-guard workspace alignment (#460)."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
from unittest import mock
|
|
||||||
from unittest.mock import MagicMock
|
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
||||||
|
|
||||||
import author_mutation_worktree as amw # noqa: E402
|
|
||||||
import gitea_mcp_server as srv # noqa: E402
|
|
||||||
|
|
||||||
CONTROL_ROOT = str(Path(__file__).resolve().parents[3])
|
|
||||||
BRANCHES_WORKTREE = str(Path(__file__).resolve().parents[1])
|
|
||||||
MCP_PROCESS_ROOT = BRANCHES_WORKTREE
|
|
||||||
|
|
||||||
|
|
||||||
class TestCanonicalRepoRoot(unittest.TestCase):
|
|
||||||
@mock.patch("subprocess.run")
|
|
||||||
def test_resolves_main_repo_from_branches_worktree(self, mock_run):
|
|
||||||
mock_run.return_value = MagicMock(
|
|
||||||
returncode=0,
|
|
||||||
stdout=f"{CONTROL_ROOT}/.git\n",
|
|
||||||
)
|
|
||||||
root = amw.resolve_canonical_repo_root(BRANCHES_WORKTREE, MCP_PROCESS_ROOT)
|
|
||||||
self.assertEqual(root, CONTROL_ROOT)
|
|
||||||
|
|
||||||
def test_falls_back_when_git_unavailable(self):
|
|
||||||
root = amw.resolve_canonical_repo_root("/missing/path", MCP_PROCESS_ROOT)
|
|
||||||
self.assertEqual(root, os.path.realpath(MCP_PROCESS_ROOT))
|
|
||||||
|
|
||||||
|
|
||||||
class TestWorkspaceRepoMembership(unittest.TestCase):
|
|
||||||
@mock.patch("os.path.isdir", return_value=True)
|
|
||||||
@mock.patch("os.path.exists", return_value=True)
|
|
||||||
@mock.patch("subprocess.run")
|
|
||||||
def test_valid_branches_worktree_accepted(self, mock_run, *_exists):
|
|
||||||
mock_run.return_value = MagicMock(
|
|
||||||
returncode=0,
|
|
||||||
stdout=f"{CONTROL_ROOT}/.git\n",
|
|
||||||
)
|
|
||||||
result = amw.assess_workspace_repo_membership(
|
|
||||||
workspace_path=BRANCHES_WORKTREE,
|
|
||||||
canonical_repo_root=CONTROL_ROOT,
|
|
||||||
)
|
|
||||||
self.assertTrue(result["proven"])
|
|
||||||
self.assertFalse(result["block"])
|
|
||||||
|
|
||||||
@mock.patch("os.path.isdir", return_value=True)
|
|
||||||
@mock.patch("os.path.exists", return_value=True)
|
|
||||||
@mock.patch("subprocess.run")
|
|
||||||
def test_wrong_repo_rejected(self, mock_run, *_exists):
|
|
||||||
mock_run.return_value = MagicMock(
|
|
||||||
returncode=0,
|
|
||||||
stdout="/other/repo/.git\n",
|
|
||||||
)
|
|
||||||
result = amw.assess_workspace_repo_membership(
|
|
||||||
workspace_path=BRANCHES_WORKTREE,
|
|
||||||
canonical_repo_root=CONTROL_ROOT,
|
|
||||||
)
|
|
||||||
self.assertTrue(result["block"])
|
|
||||||
self.assertIn("does not belong", result["reasons"][0])
|
|
||||||
|
|
||||||
@mock.patch("os.path.exists", return_value=False)
|
|
||||||
def test_missing_worktree_rejected(self, *_exists):
|
|
||||||
result = amw.assess_workspace_repo_membership(
|
|
||||||
workspace_path=f"{CONTROL_ROOT}/branches/missing-worktree",
|
|
||||||
canonical_repo_root=CONTROL_ROOT,
|
|
||||||
)
|
|
||||||
self.assertTrue(result["block"])
|
|
||||||
self.assertIn("does not exist", result["reasons"][0])
|
|
||||||
|
|
||||||
|
|
||||||
class TestRuntimeContextGuardAlignment(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
srv._preflight_whoami_called = True
|
|
||||||
srv._preflight_capability_called = True
|
|
||||||
srv._preflight_resolved_role = "author"
|
|
||||||
self._orig_in_test = srv._preflight_in_test_mode
|
|
||||||
srv._preflight_in_test_mode = lambda: False
|
|
||||||
self._env_patch = mock.patch.dict(
|
|
||||||
os.environ,
|
|
||||||
{},
|
|
||||||
clear=False,
|
|
||||||
)
|
|
||||||
self._env_patch.start()
|
|
||||||
os.environ.pop("GITEA_ACTIVE_WORKTREE", None)
|
|
||||||
os.environ.pop("GITEA_AUTHOR_WORKTREE", None)
|
|
||||||
|
|
||||||
def tearDown(self):
|
|
||||||
srv._preflight_in_test_mode = self._orig_in_test
|
|
||||||
self._env_patch.stop()
|
|
||||||
|
|
||||||
def test_runtime_context_and_guard_share_resolved_workspace(self):
|
|
||||||
with mock.patch.object(srv, "PROJECT_ROOT", MCP_PROCESS_ROOT):
|
|
||||||
ctx = srv._resolve_author_mutation_context(BRANCHES_WORKTREE)
|
|
||||||
status = srv.assess_preflight_status(worktree_path=BRANCHES_WORKTREE)
|
|
||||||
self.assertEqual(ctx["workspace_path"], os.path.realpath(BRANCHES_WORKTREE))
|
|
||||||
self.assertEqual(ctx["canonical_repo_root"], CONTROL_ROOT)
|
|
||||||
self.assertFalse(ctx["roots_aligned"])
|
|
||||||
self.assertEqual(
|
|
||||||
status["preflight_workspace"]["active_task_workspace_root"],
|
|
||||||
os.path.realpath(BRANCHES_WORKTREE),
|
|
||||||
)
|
|
||||||
self.assertEqual(
|
|
||||||
status["preflight_workspace"]["canonical_repository_root"],
|
|
||||||
CONTROL_ROOT,
|
|
||||||
)
|
|
||||||
self.assertIn("workspace_root_mismatch", status["preflight_workspace"])
|
|
||||||
|
|
||||||
@mock.patch("subprocess.run")
|
|
||||||
@mock.patch("os.path.isdir", return_value=True)
|
|
||||||
@mock.patch("os.path.exists", return_value=True)
|
|
||||||
def test_declared_branches_worktree_passes_when_mcp_root_differs(
|
|
||||||
self, _exists, _isdir, mock_run
|
|
||||||
):
|
|
||||||
mock_run.return_value = MagicMock(
|
|
||||||
returncode=0,
|
|
||||||
stdout=f"{CONTROL_ROOT}/.git\n",
|
|
||||||
)
|
|
||||||
with mock.patch.object(srv, "PROJECT_ROOT", MCP_PROCESS_ROOT):
|
|
||||||
with mock.patch.dict("os.environ", {"GITEA_TEST_PORCELAIN": ""}, clear=False):
|
|
||||||
srv.verify_preflight_purity(worktree_path=BRANCHES_WORKTREE)
|
|
||||||
|
|
||||||
def test_stable_checkout_still_rejected(self):
|
|
||||||
with mock.patch.object(srv, "PROJECT_ROOT", CONTROL_ROOT):
|
|
||||||
with mock.patch.dict("os.environ", {"GITEA_TEST_PORCELAIN": ""}, clear=False):
|
|
||||||
with self.assertRaises(RuntimeError) as ctx:
|
|
||||||
srv.verify_preflight_purity()
|
|
||||||
self.assertIn("stable control checkout", str(ctx.exception))
|
|
||||||
|
|
||||||
@mock.patch("os.path.isdir", return_value=True)
|
|
||||||
@mock.patch("os.path.exists", return_value=True)
|
|
||||||
@mock.patch("subprocess.run")
|
|
||||||
def test_non_branches_worktree_rejected(self, mock_run, *_exists):
|
|
||||||
outside = "/tmp/outside-repo-checkout"
|
|
||||||
mock_run.return_value = MagicMock(
|
|
||||||
returncode=0,
|
|
||||||
stdout=f"{CONTROL_ROOT}/.git\n",
|
|
||||||
)
|
|
||||||
with mock.patch.object(srv, "PROJECT_ROOT", CONTROL_ROOT):
|
|
||||||
with mock.patch.dict("os.environ", {"GITEA_TEST_PORCELAIN": ""}, clear=False):
|
|
||||||
with self.assertRaises(RuntimeError) as ctx:
|
|
||||||
srv.verify_preflight_purity(worktree_path=outside)
|
|
||||||
self.assertIn("not under", str(ctx.exception))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
+9
-26
@@ -20,50 +20,33 @@ def run(script, *args):
|
|||||||
branch = arg
|
branch = arg
|
||||||
break
|
break
|
||||||
|
|
||||||
lock_dir_ctx = None
|
lock_file = Path("/tmp/gitea_issue_lock.json")
|
||||||
extra_env = os.environ.copy()
|
created_lock = False
|
||||||
if script == "worktree-start" and branch:
|
if script == "worktree-start" and branch:
|
||||||
import re
|
import re
|
||||||
import tempfile
|
import json
|
||||||
import issue_lock_store
|
|
||||||
|
|
||||||
m = re.search(r"issue-(\d+)", branch)
|
m = re.search(r"issue-(\d+)", branch)
|
||||||
if not m:
|
if not m:
|
||||||
m = re.search(r"pr-(\d+)", branch)
|
m = re.search(r"pr-(\d+)", branch)
|
||||||
issue_num = int(m.group(1)) if m else 999
|
issue_num = int(m.group(1)) if m else 999
|
||||||
lock_dir_ctx = tempfile.TemporaryDirectory()
|
lock_file.write_text(json.dumps({
|
||||||
extra_env["GITEA_ISSUE_LOCK_DIR"] = lock_dir_ctx.name
|
|
||||||
record = {
|
|
||||||
"issue_number": issue_num,
|
"issue_number": issue_num,
|
||||||
"branch_name": branch,
|
"branch_name": branch,
|
||||||
"remote": "prgs",
|
"remote": "prgs",
|
||||||
"org": "Scaled-Tech-Consulting",
|
"org": "Scaled-Tech-Consulting",
|
||||||
"repo": "Gitea-Tools",
|
"repo": "Gitea-Tools"
|
||||||
"worktree_path": "/tmp/test-worktree",
|
}), encoding="utf-8")
|
||||||
"work_lease": {
|
created_lock = True
|
||||||
"operation_type": "author_issue_work",
|
|
||||||
"expires_at": "2999-01-01T00:00:00Z",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
path = issue_lock_store.lock_file_path(
|
|
||||||
remote="prgs",
|
|
||||||
org="Scaled-Tech-Consulting",
|
|
||||||
repo="Gitea-Tools",
|
|
||||||
issue_number=issue_num,
|
|
||||||
lock_dir=lock_dir_ctx.name,
|
|
||||||
)
|
|
||||||
issue_lock_store.save_lock_file(path, record)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
proc = subprocess.run(
|
proc = subprocess.run(
|
||||||
["bash", str(SCRIPTS / script), *args],
|
["bash", str(SCRIPTS / script), *args],
|
||||||
capture_output=True, text=True, cwd=str(REPO),
|
capture_output=True, text=True, cwd=str(REPO),
|
||||||
env=extra_env,
|
|
||||||
)
|
)
|
||||||
return proc.returncode, proc.stdout, proc.stderr
|
return proc.returncode, proc.stdout, proc.stderr
|
||||||
finally:
|
finally:
|
||||||
if lock_dir_ctx is not None:
|
if created_lock and lock_file.exists():
|
||||||
lock_dir_ctx.cleanup()
|
lock_file.unlink()
|
||||||
|
|
||||||
|
|
||||||
class TestWorktreeStart(unittest.TestCase):
|
class TestWorktreeStart(unittest.TestCase):
|
||||||
|
|||||||
Reference in New Issue
Block a user