Merge branch 'master' into fix/issue-850-native-mcp-bootstrap
This commit is contained in:
+355
-6
@@ -440,13 +440,32 @@ def _session_author_lock_worktree() -> str | None:
|
||||
|
||||
Used to derive the author mutation workspace when no explicit
|
||||
``worktree_path`` or env binding is provided. Never invents a path.
|
||||
|
||||
#864: a session pointer whose owner PID is dead and is not this process
|
||||
must not force workspace binding for other issues — rebind is required for
|
||||
that issue, and a stale dead-owner pointer must not poison unrelated work.
|
||||
"""
|
||||
try:
|
||||
lock = issue_lock_store.read_session_issue_lock() or {}
|
||||
except Exception:
|
||||
return None
|
||||
path = (lock.get("worktree_path") or "").strip()
|
||||
return path or None
|
||||
if not path:
|
||||
return None
|
||||
pid = lock.get("session_pid")
|
||||
if pid is None:
|
||||
pid = lock.get("pid")
|
||||
try:
|
||||
pid_i = int(pid) if pid is not None else None
|
||||
except (TypeError, ValueError):
|
||||
pid_i = None
|
||||
if (
|
||||
pid_i is not None
|
||||
and pid_i != os.getpid()
|
||||
and not issue_lock_store.is_process_alive(pid_i)
|
||||
):
|
||||
return None
|
||||
return path
|
||||
|
||||
|
||||
def _resolve_preflight_workspace_path(worktree_path: str | None = None) -> str:
|
||||
@@ -2057,6 +2076,7 @@ import issue_lock_store # noqa: E402
|
||||
import issue_lock_adoption # noqa: E402
|
||||
import issue_lock_recovery # noqa: E402
|
||||
import issue_lock_renewal # noqa: E402
|
||||
import dirty_same_claimant_session_rebind # noqa: E402 # #864
|
||||
import stacked_pr_support # noqa: E402
|
||||
import merge_approval_gate # noqa: E402
|
||||
import review_quarantine # noqa: E402 # #695 contaminated formal-review quarantine
|
||||
@@ -4368,6 +4388,263 @@ def gitea_lock_issue(
|
||||
return result
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def gitea_rebind_dirty_same_claimant_author_session(
|
||||
issue_number: int,
|
||||
branch_name: str,
|
||||
worktree_path: str,
|
||||
old_pid: int,
|
||||
expected_local_head: str,
|
||||
expected_remote_head: str,
|
||||
expected_dirty_paths: list[str],
|
||||
expected_fingerprints: dict,
|
||||
remote: str = "dadeschools",
|
||||
host: str | None = None,
|
||||
org: str | None = None,
|
||||
repo: str | None = None,
|
||||
dry_run: bool = False,
|
||||
authorize_reconciler_execute: bool = False,
|
||||
) -> dict:
|
||||
"""Rebind a dirty registered issue worktree to this session (#864).
|
||||
|
||||
Sanctioned only when every pin agrees: same claimant, dead old_pid matching
|
||||
the durable lock, matching local/remote heads, exact dirty path set, and
|
||||
per-path sha256 fingerprints. Preserves every tracked/untracked byte.
|
||||
Does not sync remote, create recovery worktrees, clean, reset, or move heads.
|
||||
|
||||
Role gate:
|
||||
* author — must match the lock claimant identity/profile
|
||||
* reconciler — execute only when ``authorize_reconciler_execute=True``
|
||||
* reviewer/merger — always refuse
|
||||
|
||||
``gitea.issue.comment`` (author map entry) is required for mutation; dry_run
|
||||
still assesses fully but writes nothing. Permission alone is never ownership
|
||||
proof — every pin is re-checked server-side.
|
||||
|
||||
Args:
|
||||
issue_number: Tracking issue number on the durable lock.
|
||||
branch_name: Exact locked branch name.
|
||||
worktree_path: Registered dirty worktree path (must be under branches/).
|
||||
old_pid: Dead owner PID recorded on the lock (must match session_pid/pid).
|
||||
expected_local_head: Full local HEAD sha the caller observed.
|
||||
expected_remote_head: Full remote-tracking HEAD sha the caller observed.
|
||||
expected_dirty_paths: Exact set of dirty relative paths (tracked+untracked).
|
||||
expected_fingerprints: Map of relative path -> sha256 hex of file bytes.
|
||||
remote: Known instance — 'dadeschools' or 'prgs'.
|
||||
host/org/repo: Optional target overrides (validated against binding).
|
||||
dry_run: When true, assess only (no lock/session writes).
|
||||
authorize_reconciler_execute: Reconciler-only execute gate.
|
||||
"""
|
||||
role = _profile_role_kind(get_profile())
|
||||
role_norm = (role or "").strip().lower()
|
||||
|
||||
# Permission: authors need comment; dry_run assess is reachable under read
|
||||
# for diagnosis, but execute always needs comment. Reconciler execute also
|
||||
# needs comment when authorized.
|
||||
if dry_run:
|
||||
read_block = _profile_operation_gate("gitea.read")
|
||||
if read_block:
|
||||
return {
|
||||
"success": False,
|
||||
"dry_run": True,
|
||||
"reasons": read_block,
|
||||
"permission_report": _permission_block_report("gitea.read"),
|
||||
}
|
||||
else:
|
||||
blocked = _profile_permission_block(
|
||||
task_capability_map.required_permission(
|
||||
"rebind_dirty_same_claimant_author_session"
|
||||
),
|
||||
issue_number=issue_number,
|
||||
remote=remote,
|
||||
host=host,
|
||||
org=org,
|
||||
repo=repo,
|
||||
org_explicit=org is not None,
|
||||
repo_explicit=repo is not None,
|
||||
)
|
||||
if blocked:
|
||||
return blocked
|
||||
|
||||
if role_norm in {"reviewer", "merger"}:
|
||||
return {
|
||||
"success": False,
|
||||
"dry_run": bool(dry_run),
|
||||
"outcome": dirty_same_claimant_session_rebind.REFUSED,
|
||||
"reasons": [
|
||||
f"role '{role_norm}' cannot rebind dirty same-claimant author "
|
||||
"sessions (fail closed)"
|
||||
],
|
||||
}
|
||||
if role_norm == "reconciler" and not authorize_reconciler_execute and not dry_run:
|
||||
return {
|
||||
"success": False,
|
||||
"dry_run": False,
|
||||
"outcome": dirty_same_claimant_session_rebind.REFUSED,
|
||||
"reasons": [
|
||||
"reconciler role requires authorize_reconciler_execute=True "
|
||||
"to execute dirty same-claimant rebind (fail closed)"
|
||||
],
|
||||
}
|
||||
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
try:
|
||||
identity = _authenticated_username(h)
|
||||
except Exception:
|
||||
identity = None
|
||||
profile = get_profile()
|
||||
profile_name = profile.get("profile_name")
|
||||
|
||||
existing = _load_existing_issue_lock(
|
||||
remote=remote, org=o, repo=r, issue_number=issue_number
|
||||
)
|
||||
resolved_wt = os.path.realpath(os.path.abspath((worktree_path or "").strip()))
|
||||
inv = dirty_same_claimant_session_rebind.collect_dirty_inventory(resolved_wt)
|
||||
|
||||
branch_res = subprocess.run(
|
||||
["git", "-C", resolved_wt, "branch", "--show-current"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
current_branch = (branch_res.stdout or "").strip() or None
|
||||
head_res = subprocess.run(
|
||||
["git", "-C", resolved_wt, "rev-parse", "HEAD"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
local_head = (head_res.stdout or "").strip() if head_res.returncode == 0 else None
|
||||
|
||||
# Observe remote-tracking head without network when possible.
|
||||
remote_head = None
|
||||
for ref in (
|
||||
f"refs/remotes/origin/{branch_name}",
|
||||
f"origin/{branch_name}",
|
||||
f"refs/remotes/{remote}/{branch_name}",
|
||||
f"{remote}/{branch_name}",
|
||||
):
|
||||
rh = subprocess.run(
|
||||
["git", "-C", resolved_wt, "rev-parse", "--verify", "--quiet", ref],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if rh.returncode == 0 and (rh.stdout or "").strip():
|
||||
remote_head = (rh.stdout or "").strip()
|
||||
break
|
||||
if remote_head is None:
|
||||
# Fall back to caller's pin only for observation absence — assessment
|
||||
# still requires pin==observed, so missing observation fails closed.
|
||||
remote_head = None
|
||||
|
||||
# Competing live locks (other issues / other worktrees).
|
||||
competing_live = []
|
||||
for entry in issue_lock_store.list_live_locks():
|
||||
competing_live.append(entry)
|
||||
|
||||
# Session pointers that claim this issue lock.
|
||||
competing_sessions = []
|
||||
lock_dir = issue_lock_store.default_lock_dir()
|
||||
lock_path = issue_lock_store.lock_file_path(
|
||||
remote=remote, org=o, repo=r, issue_number=issue_number, lock_dir=lock_dir
|
||||
)
|
||||
try:
|
||||
for name in os.listdir(lock_dir):
|
||||
if not name.startswith("session-") or not name.endswith(".json"):
|
||||
continue
|
||||
ptr = issue_lock_store.read_lock_file(os.path.join(lock_dir, name))
|
||||
if not ptr:
|
||||
continue
|
||||
ptr_lock = str(ptr.get("lock_file_path") or "").strip()
|
||||
if not ptr_lock:
|
||||
continue
|
||||
try:
|
||||
same = os.path.realpath(ptr_lock) == os.path.realpath(lock_path)
|
||||
except OSError:
|
||||
same = ptr_lock == lock_path
|
||||
if not same:
|
||||
continue
|
||||
try:
|
||||
sess_pid = int(str(name)[len("session-") : -len(".json")])
|
||||
except ValueError:
|
||||
sess_pid = ptr.get("pid")
|
||||
competing_sessions.append(
|
||||
{
|
||||
"pid": sess_pid,
|
||||
"lock_file_path": ptr_lock,
|
||||
"live": issue_lock_store.is_process_alive(sess_pid),
|
||||
}
|
||||
)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Best-effort workflow-lease scan: any live lock file whose work_lease is a
|
||||
# non-author workflow lease on this issue/branch counts as active.
|
||||
workflow_lease_active = False
|
||||
for path in issue_lock_store.iter_lock_files(lock_dir):
|
||||
rec = issue_lock_store.read_lock_file(path)
|
||||
if not rec:
|
||||
continue
|
||||
lease = rec.get("work_lease") if isinstance(rec.get("work_lease"), dict) else {}
|
||||
op = str(lease.get("operation_type") or "")
|
||||
if op and op != issue_lock_store.AUTHOR_ISSUE_WORK_LEASE:
|
||||
if rec.get("issue_number") == issue_number or str(
|
||||
rec.get("branch_name") or ""
|
||||
) == branch_name:
|
||||
if issue_lock_store.is_lease_live(rec):
|
||||
workflow_lease_active = True
|
||||
break
|
||||
|
||||
repo_root = _canonical_local_git_root()
|
||||
# permission_allowed reflects profile gate only — never ownership proof.
|
||||
permission_allowed = True
|
||||
|
||||
result = dirty_same_claimant_session_rebind.apply_dirty_same_claimant_session_rebind(
|
||||
remote=remote,
|
||||
org=o,
|
||||
repo=r,
|
||||
issue_number=issue_number,
|
||||
branch_name=branch_name,
|
||||
worktree_path=resolved_wt,
|
||||
claimant_identity=identity,
|
||||
claimant_profile=profile_name,
|
||||
old_pid=old_pid,
|
||||
expected_local_head=expected_local_head,
|
||||
expected_remote_head=expected_remote_head,
|
||||
expected_dirty_paths=list(expected_dirty_paths or []),
|
||||
expected_fingerprints=dict(expected_fingerprints or {}),
|
||||
existing_lock=existing,
|
||||
current_identity=identity,
|
||||
current_profile=profile_name,
|
||||
role_kind=role_norm or role,
|
||||
current_pid=os.getpid(),
|
||||
current_branch=current_branch,
|
||||
local_head=local_head,
|
||||
remote_head=remote_head,
|
||||
dirty_inventory=inv,
|
||||
competing_live_locks=competing_live,
|
||||
competing_sessions=competing_sessions,
|
||||
workflow_lease_active=workflow_lease_active,
|
||||
authorize_reconciler_execute=bool(authorize_reconciler_execute),
|
||||
permission_allowed=permission_allowed,
|
||||
repo_root=repo_root,
|
||||
dry_run=bool(dry_run),
|
||||
lock_dir=lock_dir,
|
||||
)
|
||||
result["observed"] = {
|
||||
"local_head": local_head,
|
||||
"remote_head": remote_head,
|
||||
"current_branch": current_branch,
|
||||
"dirty_paths": inv.get("dirty_paths"),
|
||||
"fingerprints": inv.get("fingerprints"),
|
||||
"identity": identity,
|
||||
"profile": profile_name,
|
||||
"role_kind": role_norm,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def gitea_assess_work_issue_duplicate(
|
||||
issue_number: int,
|
||||
@@ -11751,6 +12028,7 @@ def gitea_audit_worktree_cleanup(
|
||||
org: str | None = None,
|
||||
repo: str | None = None,
|
||||
ttl_hours: float = worktree_cleanup_audit.DEFAULT_TTL_HOURS,
|
||||
merged_pr_limit: int = 200,
|
||||
) -> dict:
|
||||
"""Read-only: classify every session-owned worktree under ``branches/`` (#401).
|
||||
|
||||
@@ -11761,17 +12039,26 @@ def gitea_audit_worktree_cleanup(
|
||||
the active issue-lock branch is read from the local lock file and treated
|
||||
as active work. Deletes nothing and mutates no Gitea state.
|
||||
|
||||
Fails closed if the live open-PR list cannot be fetched: without it,
|
||||
removability cannot be proven, so no candidates are returned.
|
||||
Merged PRs are fetched as well, so an issue worktree can be linked to the
|
||||
PR that owns its branch (#858). Such a worktree only becomes removable
|
||||
when that owning PR is unambiguous and merged, the worktree head is
|
||||
already contained in authoritative master, and nothing else protects it —
|
||||
no open or competing PR, lease, issue lock, live session, dirty file, or
|
||||
protected/control checkout. Anything unproven keeps it classified as
|
||||
active issue work.
|
||||
|
||||
Fails closed if the live open-PR list, the merged-PR list, or the
|
||||
control-plane lease state cannot be read: without them removability
|
||||
cannot be proven, so no candidates are returned.
|
||||
|
||||
Args:
|
||||
remote: Known instance — 'dadeschools' or 'prgs'.
|
||||
host: Override the Gitea host.
|
||||
org: Override the owner/organization.
|
||||
repo: Override the repository name.
|
||||
ttl_hours: Age (hours) after which a clean issue/conflict-fix
|
||||
worktree becomes stale-removable (default from
|
||||
GITEA_WORKTREE_TTL_HOURS).
|
||||
ttl_hours: Age (hours) after which a clean conflict-fix worktree
|
||||
becomes stale-removable (default from GITEA_WORKTREE_TTL_HOURS).
|
||||
merged_pr_limit: Max closed PRs scanned for merged-PR ownership.
|
||||
|
||||
Returns:
|
||||
dict with per-worktree classifications, counts, removable
|
||||
@@ -11807,22 +12094,84 @@ def gitea_audit_worktree_cleanup(
|
||||
if (pr.get("head") or {}).get("ref")
|
||||
}
|
||||
|
||||
# #858: merged PRs are the ownership evidence that lets a landed issue
|
||||
# worktree stop being reported as active work. Without them the audit can
|
||||
# never agree with the PR-scoped reconciler, so treat a fetch failure the
|
||||
# same way an open-PR fetch failure is treated: fail closed.
|
||||
try:
|
||||
closed_prs = api_get_all(
|
||||
f"{repo_api_url(h, o, r)}/pulls?state=closed", auth, limit=merged_pr_limit
|
||||
)
|
||||
except Exception as exc:
|
||||
return {
|
||||
"success": False,
|
||||
"performed": False,
|
||||
"open_pr_state_verified": True,
|
||||
"merged_pr_state_verified": False,
|
||||
"reasons": [
|
||||
"could not fetch merged PRs; worktree ownership unverified "
|
||||
f"(fail closed): {_redact(str(exc))}"
|
||||
],
|
||||
}
|
||||
merged_prs = [pr for pr in closed_prs if (pr.get("merged") or pr.get("merged_at"))]
|
||||
pr_index = worktree_cleanup_audit.build_pr_index(list(open_prs) + merged_prs)
|
||||
|
||||
# #858: the auditor already accepted lease evidence but nothing ever
|
||||
# supplied it, so every worktree looked unleased. Removability is now
|
||||
# reachable for issue worktrees, so authoritative control-plane leases
|
||||
# must be readable or the audit fails closed.
|
||||
db, lease_errs = _control_plane_db_or_error()
|
||||
if db is None:
|
||||
return {
|
||||
"success": False,
|
||||
"performed": False,
|
||||
"open_pr_state_verified": True,
|
||||
"merged_pr_state_verified": True,
|
||||
"lease_state_verified": False,
|
||||
"reasons": [
|
||||
"could not read control-plane leases; worktree protection "
|
||||
"unverified (fail closed)",
|
||||
*lease_errs,
|
||||
],
|
||||
}
|
||||
lease_result = lease_lifecycle.list_active_leases(
|
||||
db, remote=remote, org=o, repo=r, include_non_active=False, limit=500
|
||||
)
|
||||
leased_issue_numbers: set[int] = set()
|
||||
live_session_paths: set[str] = set()
|
||||
for lease in lease_result.get("leases") or []:
|
||||
if lease.get("work_kind") == "issue" and lease.get("work_number") is not None:
|
||||
try:
|
||||
leased_issue_numbers.add(int(lease["work_number"]))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if lease.get("worktree_path"):
|
||||
live_session_paths.add(str(lease["worktree_path"]))
|
||||
|
||||
active_issue_branches: set[str] = set()
|
||||
lock = merged_cleanup_reconcile.read_issue_lock(ISSUE_LOCK_FILE)
|
||||
if lock and lock.get("branch_name"):
|
||||
active_issue_branches.add(str(lock["branch_name"]).strip())
|
||||
|
||||
master_ref = f"{remote}/master" if remote in REMOTES else "origin/master"
|
||||
report = worktree_cleanup_audit.audit_branches_directory(
|
||||
_canonical_local_git_root(),
|
||||
open_pr_branches=open_pr_branches,
|
||||
active_issue_branches=active_issue_branches,
|
||||
now=datetime.now(timezone.utc),
|
||||
ttl_hours=ttl_hours,
|
||||
pr_index=pr_index,
|
||||
leased_issue_numbers=leased_issue_numbers,
|
||||
live_session_paths=live_session_paths,
|
||||
master_ref=master_ref,
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"performed": False,
|
||||
"open_pr_state_verified": True,
|
||||
"merged_pr_state_verified": True,
|
||||
"lease_state_verified": True,
|
||||
"master_ref": master_ref,
|
||||
"task_mode": "work-issue",
|
||||
**report,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user