github-ai-mcp 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. github_ai_mcp/__init__.py +1 -0
  2. github_ai_mcp/__main__.py +3 -0
  3. github_ai_mcp/cli/__init__.py +1 -0
  4. github_ai_mcp/cli/app.py +128 -0
  5. github_ai_mcp/config.py +112 -0
  6. github_ai_mcp/core/__init__.py +1 -0
  7. github_ai_mcp/core/git_engine.py +76 -0
  8. github_ai_mcp/core/github_api.py +86 -0
  9. github_ai_mcp/core/job_engine.py +889 -0
  10. github_ai_mcp/core/locking.py +41 -0
  11. github_ai_mcp/desktop/__init__.py +1 -0
  12. github_ai_mcp/desktop/control.py +26 -0
  13. github_ai_mcp/desktop/entry.py +77 -0
  14. github_ai_mcp/desktop/legal.py +9 -0
  15. github_ai_mcp/desktop/prerequisites.py +31 -0
  16. github_ai_mcp/desktop/processes.py +116 -0
  17. github_ai_mcp/desktop/runtime.py +34 -0
  18. github_ai_mcp/desktop/setup.py +408 -0
  19. github_ai_mcp/desktop/startup.py +64 -0
  20. github_ai_mcp/desktop/streams.py +50 -0
  21. github_ai_mcp/desktop/supervisor.py +358 -0
  22. github_ai_mcp/desktop/tunnel.py +242 -0
  23. github_ai_mcp/exceptions.py +6 -0
  24. github_ai_mcp/gui/__init__.py +1 -0
  25. github_ai_mcp/gui/app.py +969 -0
  26. github_ai_mcp/gui/workers.py +26 -0
  27. github_ai_mcp/security/__init__.py +1 -0
  28. github_ai_mcp/security/auth_github.py +67 -0
  29. github_ai_mcp/security/auth_mcp.py +38 -0
  30. github_ai_mcp/security/paths.py +34 -0
  31. github_ai_mcp/security/policy.py +40 -0
  32. github_ai_mcp/security/secret_scan.py +24 -0
  33. github_ai_mcp/server.py +97 -0
  34. github_ai_mcp/storage/__init__.py +1 -0
  35. github_ai_mcp/storage/database.py +88 -0
  36. github_ai_mcp/tool_definitions.py +185 -0
  37. github_ai_mcp-1.0.2.dist-info/METADATA +33 -0
  38. github_ai_mcp-1.0.2.dist-info/RECORD +42 -0
  39. github_ai_mcp-1.0.2.dist-info/WHEEL +5 -0
  40. github_ai_mcp-1.0.2.dist-info/entry_points.txt +2 -0
  41. github_ai_mcp-1.0.2.dist-info/licenses/LICENSE +21 -0
  42. github_ai_mcp-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,889 @@
1
+ """Shared application service. No AI inputs can grant permissions or configure checks."""
2
+ import base64
3
+ import difflib
4
+ import functools
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import unicodedata
11
+
12
+ from github_ai_mcp.desktop.processes import run_background
13
+ import time
14
+ import uuid
15
+ from pathlib import Path
16
+ from typing import Any
17
+ from urllib.parse import quote
18
+
19
+ from github_ai_mcp.config import Config
20
+ from github_ai_mcp.core.git_engine import Git
21
+ from github_ai_mcp.core.github_api import GitHub
22
+ from github_ai_mcp.core.locking import lock
23
+ from github_ai_mcp.exceptions import AppError
24
+ from github_ai_mcp.security.paths import safe_path
25
+ from github_ai_mcp.security.policy import Policy
26
+ from github_ai_mcp.security.secret_scan import redact, scan
27
+ from github_ai_mcp.storage.database import Database
28
+
29
+
30
+ def task_branch_name(title: str) -> str:
31
+ """A flat, English-language Git branch slug derived from a task title.
32
+
33
+ MCP clients should translate non-English requests into a short English task
34
+ title before calling create_job. This function does not pretend to translate.
35
+ """
36
+ if not 1 <= len(title) <= 200 or any(ord(ch) < 32 for ch in title):
37
+ raise AppError("INVALID_INPUT", "Task title must be 1–200 characters, single-line")
38
+ normalized = unicodedata.normalize("NFKD", title).encode("ascii", "ignore").decode("ascii")
39
+ if not normalized.strip() and title.strip():
40
+ raise AppError("INVALID_INPUT", "Provide a short English task title for branch naming")
41
+ slug = re.sub(r"[^a-z0-9]+", "-", normalized.lower()).strip("-")[:100].rstrip("-")
42
+ if not slug or not re.match(r"[a-z]", slug):
43
+ raise AppError("INVALID_INPUT", "Task title must start with an English word")
44
+ return slug
45
+
46
+
47
+ def is_safe_task_branch(name: str) -> bool:
48
+ """New branches have no namespace; older ai/* jobs stay compatible."""
49
+ return bool(re.fullmatch(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*", name)
50
+ or re.fullmatch(r"ai/[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*", name))
51
+
52
+
53
+ def numbered_task_branch(base: str, index: int) -> str:
54
+ suffix = f"-{index}"
55
+ return base[:120 - len(suffix)].rstrip("-") + suffix
56
+
57
+
58
+ def reject_case_collisions(paths):
59
+ """Reject case-only file or directory aliases before touching a Windows worktree.
60
+
61
+ Check every path component, not just complete filenames: Docs/a and docs/b
62
+ would otherwise silently share a physical directory on Windows.
63
+ """
64
+ seen: dict[str, str] = {}
65
+ for path in sorted(set(paths)):
66
+ components = []
67
+ for component in path.split("/"):
68
+ components.append(component)
69
+ prefix = "/".join(components)
70
+ folded = prefix.casefold()
71
+ other = seen.setdefault(folded, prefix)
72
+ if other != prefix:
73
+ raise AppError("CASE_COLLISION", "Case-insensitive path collision denied")
74
+
75
+
76
+ def serialized(function):
77
+ @functools.wraps(function)
78
+ def wrapped(self, *args, **kwargs):
79
+ # Deliberately serialize all operations across GUI, CLI and MCP processes.
80
+ with lock(self.root / "locks", "service"):
81
+ return function(self, *args, **kwargs)
82
+ return wrapped
83
+
84
+
85
+ class Service:
86
+ def __init__(self, config: Config, github: GitHub | None = None):
87
+ self.config = config
88
+ self.root = config.data_dir.resolve()
89
+ self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
90
+ self.db = Database(self.root / "jobs.sqlite3")
91
+ self.policy = Policy(config, self.db)
92
+ self.git = Git(config.git_timeout)
93
+ self.github = github or GitHub()
94
+
95
+ def health_check(self) -> dict:
96
+ import importlib.metadata
97
+ import sys
98
+ try:
99
+ git_status = self.git.text(self.root, "--version")
100
+ except AppError:
101
+ git_status = "Unavailable"
102
+ return {"python": sys.version.split()[0], "git": git_status,
103
+ "sdk": importlib.metadata.version("mcp"), "mode": self.config.mode,
104
+ "endpoint": f"http://127.0.0.1:{self.config.port}/mcp",
105
+ "remote_enabled": False, "capabilities": ["stdio", "streamable-http", "strict-path-commits"],
106
+ "github_connectivity": "not_checked", "auth": "local process / HTTP bearer vault"}
107
+
108
+ def list_repositories(self) -> dict:
109
+ return {"repositories": list(self.config.repositories)}
110
+
111
+ def _work(self, job: dict) -> Path:
112
+ # Paths are always derived from a UUID, never from caller-supplied job fields.
113
+ return self.root / "jobs" / str(uuid.UUID(job["id"])) / "work"
114
+
115
+ def _job(self, job_id: str, mutable=False) -> dict:
116
+ job = self.db.get(job_id)
117
+ self.policy.repo(job["repository"])
118
+ if mutable:
119
+ self.policy.write()
120
+ if job["state"] == "CANCELLED":
121
+ raise AppError("CANCELLED", "Job cancelled; create a new job")
122
+ return job
123
+
124
+ def _editable(self, job):
125
+ if job.get("commits") or job["state"] not in {"SNAPSHOT_READY", "PATCHING", "PREVIEW_READY", "CHECK_FAILED"}:
126
+ raise AppError("INVALID_STATE", "Frozen or published job cannot be edited")
127
+
128
+ def _cached(self, repository: str) -> Path:
129
+ repo = self.policy.repo(repository)
130
+ path = self.root / "read_cache" / hashlib.sha256(repository.encode()).hexdigest()
131
+ if not path.exists():
132
+ self.git.clone(repo.source, path)
133
+ else:
134
+ if self.git.text(path, "remote", "get-url", "origin") != repo.source:
135
+ raise AppError("CACHE_SOURCE_CHANGED", "Configured source changed; remove only the owned read_cache entry locally")
136
+ self.git.run(path, "fetch", "--prune", "origin")
137
+ self.git.run(path, "checkout", "--detach", "refs/remotes/origin/" + repo.default_branch)
138
+ return path
139
+
140
+ @serialized
141
+ def get_repository_info(self, repository: str) -> dict:
142
+ repo = self.policy.repo(repository)
143
+ if repo.source.startswith("https://github.com/"):
144
+ return self.github.info(repository)
145
+ path = self._cached(repository)
146
+ return {"repository": repository, "default_branch": repo.default_branch,
147
+ "head": self.git.text(path, "rev-parse", "HEAD"), "github": "local source; unknown"}
148
+
149
+ @serialized
150
+ def list_branches(self, repository: str) -> dict:
151
+ path = self._cached(repository)
152
+ return {"refs": self.git.text(path, "for-each-ref", "--format=%(refname) %(objectname)",
153
+ "refs/heads", "refs/remotes").splitlines()[:200]}
154
+
155
+ @serialized
156
+ def list_tree(self, repository: str, offset: int = 0, limit: int = 100) -> dict:
157
+ if not 0 <= offset or not 1 <= limit <= 200:
158
+ raise AppError("INVALID_INPUT", "Invalid pagination")
159
+ path = self._cached(repository)
160
+ entries = []
161
+ for name, entry in self.git.tree(path).items():
162
+ try:
163
+ safe_path(path, name)
164
+ except AppError:
165
+ continue
166
+ entries.append({"path": name, **entry})
167
+ return {"entries": entries[offset:offset+limit], "total": len(entries),
168
+ "next_offset": offset + limit if offset + limit < len(entries) else None}
169
+
170
+ def _read(self, work: Path, path: str, binary: bool = False) -> dict:
171
+ dest = safe_path(work, path)
172
+ if not dest.is_file():
173
+ raise AppError("NOT_FOUND", "File unavailable")
174
+ if dest.stat().st_size > self.config.max_file_bytes:
175
+ raise AppError("LIMIT_EXCEEDED", "File exceeds configured limit")
176
+ content = dest.read_bytes()
177
+ scan(content)
178
+ sha = hashlib.sha256(content).hexdigest()
179
+ try:
180
+ text = content.decode("utf-8")
181
+ if b"\0" in content:
182
+ raise UnicodeDecodeError("utf-8", content, 0, 1, "binary")
183
+ return {"path": path, "content": text, "encoding": "utf-8", "checksum": sha, "bytes": len(content),
184
+ "snapshot_sha": self.git.text(work, "rev-parse", "HEAD")}
185
+ except UnicodeDecodeError:
186
+ if not binary:
187
+ raise AppError("BINARY_DENIED", "Explicit binary read required") from None
188
+ return {"path": path, "content": base64.b64encode(content).decode(), "encoding": "base64",
189
+ "checksum": sha, "bytes": len(content)}
190
+
191
+ @serialized
192
+ def read_file(self, repository: str, path: str, job_id: str | None = None, binary: bool = False) -> dict:
193
+ self.policy.repo(repository)
194
+ if job_id:
195
+ job = self._job(job_id)
196
+ if job["repository"] != repository:
197
+ raise AppError("PERMISSION_DENIED", "Job belongs to another repository")
198
+ work = self._work(job)
199
+ else:
200
+ work = self._cached(repository)
201
+ return self._read(work, path, binary)
202
+
203
+ @serialized
204
+ def read_files_batch(self, repository: str, paths: list[str]) -> dict:
205
+ if not 1 <= len(paths) <= 20:
206
+ raise AppError("LIMIT_EXCEEDED", "Read 1–20 paths per batch")
207
+ work = self._cached(repository)
208
+ items = [self._read(work, p) for p in paths]
209
+ if sum(i["bytes"] for i in items) > 2_000_000:
210
+ raise AppError("LIMIT_EXCEEDED", "Batch too large")
211
+ return {"files": items}
212
+
213
+ @serialized
214
+ def list_recent_commits(self, repository: str, limit: int = 20) -> dict:
215
+ if not 1 <= limit <= 100:
216
+ raise AppError("LIMIT_EXCEEDED", "Limit must be 1–100")
217
+ work = self._cached(repository)
218
+ data = self.git.text(work, "log", f"-{limit}", "--format=%H%x09%an%x09%ae%x09%s")
219
+ return {"commits": redact(data).splitlines()}
220
+
221
+ @serialized
222
+ def create_job(self, repository: str, idempotency_key: str, target_branch: str | None = None,
223
+ expected_base_sha: str | None = None, base_ref: str | None = None,
224
+ task_name: str | None = None) -> dict:
225
+ """Create an isolated job. Supply an English task_name to auto-name its branch.
226
+
227
+ Example: task_name='fix tunnel startup' creates fix-tunnel-startup; if
228
+ taken, fix-tunnel-startup-2, etc. An AI client should translate the
229
+ user's task into English before calling this tool. target_branch is
230
+ an optional explicit override. Old ai/* branches remain supported.
231
+ """
232
+ self.policy.write()
233
+ repo = self.policy.repo(repository)
234
+ if not 1 <= len(idempotency_key) <= 100:
235
+ raise AppError("INVALID_INPUT", "Idempotency key must be 1–100 characters")
236
+ previous = self.db.by_key(idempotency_key)
237
+ if previous:
238
+ if (previous["repository"] != repository
239
+ or (target_branch and previous["target_branch"] != target_branch)
240
+ or (task_name is not None and previous.get("task_name") != task_name)):
241
+ raise AppError("IDEMPOTENCY_CONFLICT", "Key already used for different job")
242
+ return previous
243
+ base_branch = base_ref or repo.default_branch
244
+ if not re.fullmatch(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*", base_branch):
245
+ raise AppError("INVALID_INPUT", "Base ref must be a simple branch name")
246
+ ident = str(uuid.uuid4())
247
+ automatic = target_branch is None
248
+ base_name = ""
249
+ if automatic:
250
+ if task_name is not None:
251
+ base_name = task_branch_name(task_name)
252
+ else:
253
+ # Legacy clients supply only an idempotency key. A UUID or an
254
+ # opaque key is not a task title: retain a safe fallback.
255
+ try:
256
+ base_name = task_branch_name(idempotency_key)
257
+ except AppError:
258
+ base_name = "task-" + ident[:8]
259
+ if re.fullmatch(r"[0-9a-f]{8}-[0-9a-f-]{27,}", idempotency_key.lower()):
260
+ base_name = "task-" + ident[:8]
261
+ target = base_name if automatic else target_branch
262
+ if target is None or not is_safe_task_branch(target) or len(target) > 120:
263
+ raise AppError("PERMISSION_DENIED", "Target must be a safe task branch without a prefix")
264
+ if target in {repo.default_branch, base_branch}:
265
+ raise AppError("PERMISSION_DENIED", "Base/default branch publication forbidden")
266
+ if automatic:
267
+ index = 2
268
+ while self.db.branch_owned(repository, target) or target in {repo.default_branch, base_branch}:
269
+ if index > 1000:
270
+ raise AppError("BUSY", "No available task branch name")
271
+ target = numbered_task_branch(base_name, index)
272
+ index += 1
273
+ elif self.db.branch_owned(repository, target):
274
+ raise AppError("BUSY", "Existing active job owns branch")
275
+ job: dict = {"id": ident, "repository": repository, "idempotency_key": idempotency_key,
276
+ "target_branch": target, "base_branch": base_branch, "task_name": task_name,
277
+ "state": "CREATED", "created_at": time.time(),
278
+ "commits": [], "checks": {}, "plan": {}, "warnings": [], "pr_url": None}
279
+ self.db.save(job, "CREATED")
280
+ work = self._work(job)
281
+ try:
282
+ self.git.clone(repo.source, work)
283
+ self.git.run(work, "check-ref-format", "--branch", repo.default_branch)
284
+ base = self.git.text(work, "rev-parse", "refs/remotes/origin/" + base_branch)
285
+ if expected_base_sha and expected_base_sha != base:
286
+ raise AppError("BASE_MISMATCH", "Expected base differs from default branch SHA")
287
+ if automatic:
288
+ # Check the remote, not just the local job DB: a real GitHub
289
+ # branch may already exist. No force-push or branch reuse.
290
+ index = 2
291
+ while self.git.remote_sha(work, target) is not None:
292
+ if index > 1000:
293
+ raise AppError("BUSY", "No available task branch name")
294
+ candidate = numbered_task_branch(base_name, index)
295
+ index += 1
296
+ if (candidate in {repo.default_branch, base_branch}
297
+ or self.db.branch_owned(repository, candidate)):
298
+ continue
299
+ target = candidate
300
+ if target != job["target_branch"]:
301
+ job["target_branch"] = target
302
+ self.db.save(job, "TARGET_BRANCH_SELECTED")
303
+ self.git.run(work, "checkout", "-b", target, base)
304
+ # Identity is configured locally only, after trusted local authorization.
305
+ if repo.identity_authorized:
306
+ self.git.run(work, "config", "--local", "user.name", repo.author_name)
307
+ self.git.run(work, "config", "--local", "user.email", repo.author_email)
308
+ job.update(base_sha=base, current_sha=base, base_tree=self.git.text(work, "rev-parse", "HEAD^{tree}"),
309
+ expected_remote=self.git.remote_sha(work, target), state="SNAPSHOT_READY")
310
+ self.db.save(job, "SNAPSHOT_READY")
311
+ except AppError:
312
+ job["state"] = "RECOVERY_REQUIRED"
313
+ self.db.save(job, "CREATE_FAILED")
314
+ raise
315
+ return job
316
+
317
+ @serialized
318
+ def plan_changes(self, job_id: str, messages: dict[str, str]) -> dict:
319
+ job = self._job(job_id, True)
320
+ self._editable(job)
321
+ if len(set(job["plan"]) | set(messages)) > self.config.max_files:
322
+ raise AppError("LIMIT_EXCEEDED", "Too many planned paths")
323
+ # Check against the tracked base and all planned paths, before any writes.
324
+ reject_case_collisions([*self.git.tree(self._work(job), job["base_sha"]),
325
+ *job["plan"], *messages])
326
+ for path, message in messages.items():
327
+ safe_path(self._work(job), path)
328
+ if not re.fullmatch(r"(?:feat|fix|docs|test|refactor|chore|style|perf|build|ci)(?:\([\w.-]+\))?: [^\r\n]{3,120}", message):
329
+ raise AppError("INVALID_INPUT", "Meaningful conventional commit subject required")
330
+ scan(message.encode())
331
+ job["plan"].update(messages)
332
+ job["fingerprint"] = ""
333
+ job["checks"] = {}
334
+ self.db.save(job, "PLANNED")
335
+ return {"job_id": job_id, "planned_paths": sorted(job["plan"])}
336
+
337
+ def _expected(self, dest: Path, expected_checksum: str | None):
338
+ actual = hashlib.sha256(dest.read_bytes()).hexdigest() if dest.is_file() else None
339
+ if actual != expected_checksum:
340
+ raise AppError("STALE_FILE", "Expected checksum differs from workspace; read the file again")
341
+
342
+ def _write(self, job, path: str, data: bytes, expected_checksum: str | None, executable: bool | None):
343
+ self._editable(job)
344
+ if path not in job["plan"]:
345
+ raise AppError("UNPLANNED_PATH", "Declare path and intent before editing")
346
+ work = self._work(job)
347
+ # Protect jobs saved by older versions whose plan was not checked.
348
+ reject_case_collisions([*self.git.tree(work, job["base_sha"]), *job["plan"], path])
349
+ dest = safe_path(work, path)
350
+ self._expected(dest, expected_checksum)
351
+ if len(data) > self.config.max_file_bytes:
352
+ raise AppError("LIMIT_EXCEEDED", "File too large")
353
+ scan(data)
354
+ if data.startswith(b"version https://git-lfs.github.com/spec/v1"):
355
+ raise AppError("LFS_UNSUPPORTED", "LFS writes require a dedicated client workflow")
356
+ tree_entry = self.git.tree(work).get(path)
357
+ if tree_entry and tree_entry["mode"] not in {"100644", "100755"}:
358
+ raise AppError("UNSUPPORTED_MODE", "Symlink and submodule edits forbidden")
359
+ dest.parent.mkdir(parents=True, exist_ok=True)
360
+ temp = dest.with_name(dest.name + ".mcp-tmp-" + uuid.uuid4().hex)
361
+ temp.write_bytes(data)
362
+ if dest.exists():
363
+ temp.chmod(dest.stat().st_mode)
364
+ if executable is not None:
365
+ temp.chmod(0o755 if executable else 0o644)
366
+ os.replace(temp, dest)
367
+ if executable is not None:
368
+ job.setdefault("requested_modes", {})[path] = "100755" if executable else "100644"
369
+ job.update(state="PATCHING", fingerprint="", checks={})
370
+ self.db.save(job, "FILE_WRITTEN")
371
+ return {"path": path, "checksum": hashlib.sha256(data).hexdigest(), "bytes": len(data)}
372
+
373
+ @serialized
374
+ def write_file(self, job_id: str, path: str, content: str, expected_checksum: str | None = None,
375
+ encoding: str = "utf-8", executable: bool | None = None) -> dict:
376
+ job = self._job(job_id, True)
377
+ if encoding == "base64":
378
+ if not self.policy.repo(job["repository"]).allow_binary:
379
+ raise AppError("BINARY_DENIED", "Binary writes disabled in trusted policy")
380
+ try:
381
+ data = base64.b64decode(content, validate=True)
382
+ except ValueError:
383
+ raise AppError("INVALID_INPUT", "Invalid base64") from None
384
+ elif encoding == "utf-8":
385
+ data = content.encode("utf-8")
386
+ if b"\0" in data:
387
+ raise AppError("BINARY_DENIED", "Use explicit binary policy for NUL content")
388
+ else:
389
+ raise AppError("INVALID_INPUT", "Encoding must be utf-8 or base64")
390
+ return self._write(job, path, data, expected_checksum, executable)
391
+
392
+ @serialized
393
+ def apply_patch(self, job_id: str, path: str, old_text: str, new_text: str,
394
+ expected_checksum: str) -> dict:
395
+ """Exact contextual replacement. Context must occur exactly once; never fuzzy apply."""
396
+ job = self._job(job_id, True)
397
+ dest = safe_path(self._work(job), path)
398
+ self._expected(dest, expected_checksum)
399
+ raw = dest.read_bytes()
400
+ try:
401
+ text = raw.decode("utf-8")
402
+ except UnicodeDecodeError:
403
+ raise AppError("BINARY_DENIED", "Context patch requires UTF-8") from None
404
+ if not old_text or text.count(old_text) != 1:
405
+ raise AppError("PATCH_CONFLICT", "Patch context missing or ambiguous")
406
+ return self._write(job, path, text.replace(old_text, new_text, 1).encode(), expected_checksum, None)
407
+
408
+ @serialized
409
+ def delete_file(self, job_id: str, path: str, expected_checksum: str) -> dict:
410
+ job = self._job(job_id, True)
411
+ self._editable(job)
412
+ if path not in job["plan"]:
413
+ raise AppError("UNPLANNED_PATH", "Plan path before deletion")
414
+ dest = safe_path(self._work(job), path)
415
+ self._expected(dest, expected_checksum)
416
+ if not dest.is_file():
417
+ raise AppError("NOT_FOUND", "File does not exist")
418
+ dest.unlink()
419
+ # Remove only empty parents inside this isolated worktree. No recursive deletion.
420
+ parent = dest.parent
421
+ work = self._work(job).resolve()
422
+ while parent != work and parent.is_relative_to(work):
423
+ try:
424
+ parent.rmdir()
425
+ except OSError:
426
+ break
427
+ parent = parent.parent
428
+ job.update(state="PATCHING", fingerprint="", checks={})
429
+ self.db.save(job, "FILE_DELETED")
430
+ return {"path": path, "deleted": True}
431
+
432
+ def _snapshot(self, job):
433
+ work = self._work(job)
434
+ if self.git.text(work, "rev-parse", "HEAD") != job["base_sha"]:
435
+ raise AppError("INVALID_STATE", "Snapshot can only be made before committing")
436
+ base = self.git.tree(work, job["base_sha"])
437
+ # Validate before Git stages anything, including plans persisted pre-fix.
438
+ reject_case_collisions([*base, *job["plan"]])
439
+ self.git.run(work, "read-tree", "HEAD")
440
+ for path in job["plan"]:
441
+ safe_path(work, path)
442
+ self.git.run(work, "add", "-A", "--", path)
443
+ if path in job.get("requested_modes", {}) and safe_path(work, path).is_file():
444
+ flag = "+x" if job["requested_modes"][path] == "100755" else "-x"
445
+ self.git.run(work, "update-index", "--chmod=" + flag, "--", path)
446
+ paths = self.git.paths(work, "diff", "--cached", "--name-only", "--no-renames", "-z", job["base_sha"])
447
+ if len(paths) > self.config.max_files:
448
+ raise AppError("LIMIT_EXCEEDED", "Too many changes")
449
+ desired = self.git.tree(work, self.git.text(work, "write-tree"))
450
+ reject_case_collisions([*base, *desired, *job["plan"]])
451
+ total = 0
452
+ changes = []
453
+ for path in sorted(paths):
454
+ if path not in job["plan"]:
455
+ raise AppError("UNPLANNED_PATH", "Snapshot contains an undeclared path")
456
+ safe_path(work, path)
457
+ entry = desired.get(path)
458
+ if entry:
459
+ if entry["mode"] not in {"100644", "100755"}:
460
+ raise AppError("UNSUPPORTED_MODE", "Symlinks and gitlinks blocked")
461
+ data = self.git.blob(work, entry["sha"])
462
+ if len(data) > self.config.max_file_bytes:
463
+ raise AppError("LIMIT_EXCEEDED", "Blob too large")
464
+ scan(data)
465
+ if data != safe_path(work, path).read_bytes():
466
+ raise AppError("FILTER_TRANSFORM", "Git attributes transformed approved bytes; review attributes first")
467
+ total += len(data)
468
+ changes.append({"path": path, "entry": entry, "old": base.get(path), "message": job["plan"][path]})
469
+ if total > self.config.max_job_bytes:
470
+ raise AppError("LIMIT_EXCEEDED", "Job too large")
471
+ tree = self.git.text(work, "write-tree")
472
+ repo = self.policy.repo(job["repository"])
473
+ identity = {"name": repo.author_name, "email": repo.author_email}
474
+ fp = hashlib.sha256(json.dumps({"base": job["base_sha"], "tree": tree, "changes": changes, "identity": identity},
475
+ sort_keys=True).encode()).hexdigest()
476
+ return changes, tree, fp, total
477
+
478
+ def _preview(self, job):
479
+ changes, tree, fp, total = self._snapshot(job)
480
+ repo = self.policy.repo(job["repository"])
481
+ job["commit_identity"] = {"name": repo.author_name, "email": repo.author_email}
482
+ job.update(changes=changes, final_tree=tree, fingerprint=fp, total_bytes=total, state="PREVIEW_READY")
483
+ self.db.save(job, "PREVIEW_READY")
484
+ return job
485
+
486
+ @serialized
487
+ def preview_job(self, job_id: str, offset: int = 0, limit: int = 20) -> dict:
488
+ job = self._job(job_id)
489
+ if not 0 <= offset or not 1 <= limit <= 50:
490
+ raise AppError("INVALID_INPUT", "Invalid preview pagination")
491
+ if job["state"] in {"SNAPSHOT_READY", "PATCHING", "PREVIEW_READY", "CHECK_FAILED"}:
492
+ self.policy.write()
493
+ job = self._preview(job)
494
+ diffs = []
495
+ work = self._work(job)
496
+ for change in job.get("changes", [])[offset:offset+limit]:
497
+ old = self.git.blob(work, change["old"]["sha"]) if change["old"] else b""
498
+ new = self.git.blob(work, change["entry"]["sha"]) if change["entry"] else b""
499
+ scan(new)
500
+ lines = difflib.unified_diff(old.decode("utf-8", "replace").splitlines(True),
501
+ new.decode("utf-8", "replace").splitlines(True),
502
+ fromfile=change["path"], tofile=change["path"])
503
+ diff = redact("".join(lines))
504
+ diffs.append({"path": change["path"], "message": change["message"],
505
+ "diff": diff[:20000], "truncated": len(diff) > 20000,
506
+ "old_mode": (change["old"] or {}).get("mode"),
507
+ "new_mode": (change["entry"] or {}).get("mode")})
508
+ return {"job_id": job_id, "fingerprint": job.get("fingerprint"), "final_tree": job.get("final_tree"),
509
+ "state": job["state"], "count": len(job.get("changes", [])), "diffs": diffs,
510
+ "warnings": ["Intermediate commits may not build", "Independent clone hooks/filters are intentionally disabled"],
511
+ "next_offset": offset+limit if offset+limit < len(job.get("changes", [])) else None}
512
+
513
+ @serialized
514
+ def approve_local(self, job_id: str, fingerprint: str, actions: list[str]) -> dict:
515
+ """Trusted local CLI/GUI only. NEVER register this method as an MCP tool."""
516
+ job = self._job(job_id, True)
517
+ if not job.get("fingerprint") or fingerprint != job["fingerprint"]:
518
+ raise AppError("STALE_APPROVAL", "Preview fingerprint changed")
519
+ if not set(actions) <= {"commit", "push", "pr"} or not actions:
520
+ raise AppError("INVALID_INPUT", "Invalid approval actions")
521
+ if job["state"] in {"PREVIEW_READY", "CHECK_FAILED"}:
522
+ _, _, actual, _ = self._snapshot(job)
523
+ if actual != fingerprint:
524
+ raise AppError("STALE_APPROVAL", "Workspace changed since preview")
525
+ if any(a in {"push", "pr"} for a in actions) and self.config.mode != "AUTO_APPROVED":
526
+ raise AppError("PERMISSION_DENIED", "Remote approval requires AUTO_APPROVED")
527
+ self.db.grant(job, actions)
528
+ self.db.save(job, "HUMAN_APPROVAL_" + "_".join(actions))
529
+ return {"approved": actions, "fingerprint": fingerprint, "expires_in_seconds": 3600}
530
+
531
+ def _checks(self, job):
532
+ work = self._work(job)
533
+ repo = self.policy.repo(job["repository"])
534
+ results: dict[str, dict[str, Any]] = {"secrets": {"passed": True}, "tree": {"passed": True}}
535
+ for change in job.get("changes", []):
536
+ if change["entry"]:
537
+ scan(self.git.blob(work, change["entry"]["sha"]))
538
+ for name in repo.required_checks:
539
+ if not repo.trusted_execution or name not in repo.checks:
540
+ raise AppError("EXECUTION_DENIED", "Required check needs trusted local command authorization")
541
+ args = repo.checks[name]
542
+ if not args or any("\x00" in a for a in args):
543
+ raise AppError("INVALID_INPUT", "Invalid configured check")
544
+ # No secret environment inherited by repository code. Host execution is explicit opt-in.
545
+ env = {k: v for k, v in os.environ.items() if k in {"PATH", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "LANG"}}
546
+ try:
547
+ p = run_background(args, cwd=work, env=env, capture_output=True, timeout=120)
548
+ results[name] = {"passed": p.returncode == 0, "exit_code": p.returncode}
549
+ except (OSError, subprocess.TimeoutExpired):
550
+ results[name] = {"passed": False, "error": "unavailable or timeout"}
551
+ # Check commands may mutate tracked or untracked files. Re-stage only approved paths and
552
+ # detect tracked differences and untracked artifacts; refuse publication on any change.
553
+ current_tree = self.git.text(work, "write-tree")
554
+ diff = self.git.run(work, "diff", "--name-only", "-z")
555
+ untracked = self.git.paths(work, "ls-files", "--others", "--exclude-standard", "-z")
556
+ if diff or untracked or current_tree != job["final_tree"]:
557
+ results["tree"] = {"passed": False, "error": "Check altered snapshot"}
558
+ passed = all(r["passed"] for r in results.values())
559
+ job["checks"] = results
560
+ job["checked_tree"] = job["final_tree"] if passed else None
561
+ if not passed:
562
+ job["state"] = "CHECK_FAILED"
563
+ elif job["state"] == "CHECK_FAILED" and job.get("commits"):
564
+ # Recovery must not recreate commits or trust a stale database status.
565
+ self._reconcile(job)
566
+ if len(job["commits"]) != len(job.get("changes", [])):
567
+ raise AppError("RECOVERY_REQUIRED", "Incomplete commit chain")
568
+ if self.git.text(work, "rev-parse", "HEAD^{tree}") != job["final_tree"]:
569
+ raise AppError("INVARIANT_FAILED", "Committed tree mismatch")
570
+ job["state"] = "VERIFIED"
571
+ self.db.save(job, "CHECKS_PASSED" if passed else "CHECK_FAILED")
572
+ return {"passed": passed, "checks": results, "execution_isolation": "host opt-in; not an OS sandbox"}
573
+
574
+ @serialized
575
+ def run_checks(self, job_id: str) -> dict:
576
+ job = self._job(job_id, True)
577
+ if not job.get("final_tree"):
578
+ raise AppError("INVALID_STATE", "Preview first")
579
+ return self._checks(job)
580
+
581
+ def _reconcile(self, job):
582
+ work = self._work(job)
583
+ expected_fingerprint = hashlib.sha256(json.dumps({"base": job["base_sha"],
584
+ "tree": job["final_tree"], "changes": job.get("changes", []),
585
+ "identity": job["commit_identity"]}, sort_keys=True).encode()).hexdigest()
586
+ if expected_fingerprint != job["fingerprint"]:
587
+ raise AppError("INVARIANT_FAILED", "Immutable snapshot fingerprint mismatch")
588
+ head = self.git.text(work, "rev-parse", "HEAD")
589
+ chain = self.git.text(work, "rev-list", "--reverse", job["base_sha"] + ".." + head).splitlines()
590
+ if head != job["base_sha"] and not chain:
591
+ raise AppError("INVARIANT_FAILED", "HEAD is not a descendant of the approved base")
592
+ changes = job.get("changes", [])
593
+ if len(chain) > len(changes):
594
+ raise AppError("RECOVERY_REQUIRED", "Unexpected commit count")
595
+ commits = []
596
+ parent = job["base_sha"]
597
+ for sha, change in zip(chain, changes):
598
+ parents = self.git.text(work, "show", "-s", "--format=%P", sha).split()
599
+ paths = self.git.paths(work, "diff-tree", "--no-commit-id", "--no-renames", "--name-only", "-r", "-z", parent, sha)
600
+ if parents != [parent] or paths != [change["path"]]:
601
+ raise AppError("INVARIANT_FAILED", "Commit parent or path invariant failed")
602
+ identity = job["commit_identity"]
603
+ author = self.git.text(work, "show", "-s", "--format=%an%x00%ae%x00%cn%x00%ce", sha).split("\0")
604
+ if author != [identity["name"], identity["email"], identity["name"], identity["email"]]:
605
+ raise AppError("INVARIANT_FAILED", "Commit author/committer differs from approved identity")
606
+ subject = self.git.text(work, "show", "-s", "--format=%B", sha)
607
+ if subject != change["message"] + "\n\nAI-assisted: GitHub-AI-MCP":
608
+ raise AppError("INVARIANT_FAILED", "Commit message differs from approved plan")
609
+ entry = self.git.tree(work, sha).get(change["path"])
610
+ if entry != change["entry"]:
611
+ raise AppError("INVARIANT_FAILED", "Commit differs from frozen snapshot")
612
+ commits.append({"path": change["path"], "sha": sha, "parent": parent, "status": "created_locally"})
613
+ parent = sha
614
+ job.update(commits=commits, current_sha=head)
615
+ self.db.save(job, "RECOVERY_RECONCILED")
616
+
617
+ def _commit(self, job):
618
+ self.policy.authorize(job, "commit")
619
+ work = self._work(job)
620
+ if job["state"] not in {"COMMITTING", "RECOVERY_REQUIRED"}:
621
+ if job["state"] not in {"PREVIEW_READY", "CHECK_FAILED"}:
622
+ raise AppError("INVALID_STATE", "Preview changes before committing")
623
+ _, tree, fp, _ = self._snapshot(job)
624
+ if tree != job["final_tree"] or fp != job["fingerprint"]:
625
+ raise AppError("STALE_APPROVAL", "Snapshot changed; preview and approve again")
626
+ if not self._checks(job)["passed"]:
627
+ raise AppError("CHECK_FAILED", "Required checks failed")
628
+ job["state"] = "COMMITTING"
629
+ self.db.save(job, "COMMITTING")
630
+ self._reconcile(job)
631
+ identity = job["commit_identity"]
632
+ self.git.run(work, "config", "--local", "user.name", identity["name"])
633
+ self.git.run(work, "config", "--local", "user.email", identity["email"])
634
+ for change in job["changes"][len(job["commits"]):]:
635
+ parent = job["current_sha"]
636
+ self.git.run(work, "read-tree", parent)
637
+ entry = change["entry"]
638
+ if entry:
639
+ self.git.run(work, "update-index", "--add", "--cacheinfo", entry["mode"], entry["sha"], change["path"])
640
+ else:
641
+ self.git.run(work, "update-index", "--force-remove", "--", change["path"])
642
+ staged = self.git.paths(work, "diff", "--cached", "--no-renames", "--name-only", "-z", parent)
643
+ if staged != [change["path"]]:
644
+ raise AppError("INVARIANT_FAILED", "Exactly one nonempty staged path required")
645
+ self.git.run(work, "diff", "--cached", "--check")
646
+ tree = self.git.text(work, "write-tree")
647
+ message = change["message"] + "\n\nAI-assisted: GitHub-AI-MCP\n"
648
+ sha = self.git.run(work, "commit-tree", tree, "-p", parent, input=message.encode()).decode().strip()
649
+ # Atomic compare-and-swap ref. If a crash precedes this, the unreachable object can be GC'd.
650
+ self.git.run(work, "update-ref", "refs/heads/" + job["target_branch"], sha, parent)
651
+ self._reconcile(job)
652
+ if self.git.text(work, "rev-parse", "HEAD^{tree}") != job["final_tree"]:
653
+ raise AppError("INVARIANT_FAILED", "Final tree does not match approved snapshot")
654
+ self.git.run(work, "read-tree", "HEAD")
655
+ job["state"] = "COMMITTED" if job["commits"] else "NO_CHANGE"
656
+ self.db.save(job, job["state"])
657
+ if not self._checks(job)["passed"]:
658
+ raise AppError("CHECK_FAILED", "Final checks failed; publication blocked")
659
+ if job["commits"]:
660
+ job["state"] = "VERIFIED"
661
+ self.db.save(job, "FINAL_TREE_VERIFIED")
662
+ return self._report(job)
663
+
664
+ @serialized
665
+ def create_file_commits(self, job_id: str) -> dict:
666
+ job = self._job(job_id, True)
667
+ if job["state"] in {"VERIFIED", "PUBLISHED", "COMPLETED", "NO_CHANGE"}:
668
+ self._reconcile(job)
669
+ return self._report(job)
670
+ if job["state"] == "CHECK_FAILED" and job.get("commits"):
671
+ self._verify_completed(job)
672
+ return self._report(job)
673
+ return self._commit(job)
674
+
675
+ def _verify_completed(self, job):
676
+ self._reconcile(job)
677
+ if not job["commits"] or len(job["commits"]) != len(job.get("changes", [])):
678
+ raise AppError("RECOVERY_REQUIRED", "Incomplete commit chain")
679
+ if self.git.text(self._work(job), "rev-parse", "HEAD^{tree}") != job["final_tree"]:
680
+ raise AppError("INVARIANT_FAILED", "Approved final tree mismatch")
681
+ if not self._checks(job)["passed"]:
682
+ raise AppError("CHECK_FAILED", "Final checks failed")
683
+ job["state"] = "VERIFIED"
684
+ self.db.save(job, "FINAL_TREE_VERIFIED")
685
+
686
+ @serialized
687
+ def resume_job(self, job_id: str) -> dict:
688
+ job = self._job(job_id, True)
689
+ if job["state"] in {"COMMITTING", "RECOVERY_REQUIRED"} and job.get("final_tree"):
690
+ return self._commit(job)
691
+ if job["state"] == "CHECK_FAILED" and job.get("commits"):
692
+ self._verify_completed(job)
693
+ return self._report(job)
694
+ if job["state"] == "PUBLISHING":
695
+ remote = self.git.remote_sha(self._work(job), job["target_branch"])
696
+ if remote == job["current_sha"]:
697
+ job["state"] = "PUBLISHED"
698
+ self.db.save(job, "PUSH_RECOVERED")
699
+ elif remote != job["expected_remote"]:
700
+ raise AppError("REMOTE_DIVERGED", "Remote changed; no automatic retry")
701
+ return self._report(job)
702
+
703
+ @serialized
704
+ def cancel_job(self, job_id: str) -> dict:
705
+ job = self._job(job_id, True)
706
+ job["state"] = "CANCELLED"
707
+ self.db.save(job, "CANCELLED")
708
+ return {"job_id": job_id, "state": "CANCELLED", "workspace_retained": True}
709
+
710
+ @serialized
711
+ def get_git_status(self, job_id: str) -> dict:
712
+ job = self._job(job_id)
713
+ return {"status": redact(self.git.text(self._work(job), "status", "--short")), "state": job["state"]}
714
+
715
+ @serialized
716
+ def get_diff(self, job_id: str) -> dict:
717
+ job = self._job(job_id)
718
+ out = self.git.run(self._work(job), "diff", "--no-ext-diff", "--no-textconv", job["base_sha"])
719
+ return {"diff": redact(out.decode("utf-8", "replace"))[:100000], "truncated": len(out) > 100000}
720
+
721
+ @serialized
722
+ def get_job_status(self, job_id: str) -> dict:
723
+ return self._report(self._job(job_id))
724
+
725
+ def _report(self, job):
726
+ remote = job["state"] in {"PUBLISHED", "COMPLETED"}
727
+ source = self.policy.repo(job["repository"]).source
728
+ commits = [dict(c, status="pushed" if remote else "created_locally",
729
+ url=f"https://github.com/{job['repository']}/commit/{c['sha']}" if remote and source.startswith("https://github.com/") else None)
730
+ for c in job["commits"]]
731
+ return {"job_id": job["id"], "repository": job["repository"], "state": job["state"],
732
+ "base_sha": job.get("base_sha"), "final_sha": job.get("current_sha"),
733
+ "final_tree": job.get("final_tree"), "fingerprint": job.get("fingerprint"),
734
+ "target_branch": job["target_branch"], "created_commits": len(commits),
735
+ "pushed_commits": len(commits) if remote else 0, "commits": commits,
736
+ "checks": job["checks"], "pull_request_url": job["pr_url"],
737
+ "contribution_eligibility": "unknown", "observed_profile_contributions": None,
738
+ "warnings": job["warnings"] + ["Feature branches may count only after a qualifying merge; squash changes SHAs"]}
739
+
740
+ @serialized
741
+ def get_job_report(self, job_id: str) -> dict:
742
+ job = self._job(job_id)
743
+ report = self._report(job)
744
+ report["audit"] = self.db.audit(job_id)
745
+ return report
746
+
747
+ @serialized
748
+ def check_contribution_eligibility(self, repository: str, branch: str) -> dict:
749
+ repo = self.policy.repo(repository)
750
+ if not repo.source.startswith("https://github.com/"):
751
+ return {"eligibility": "unknown", "reasons": ["Local source; GitHub attribution not verified"]}
752
+ info = self.github.info(repository)
753
+ identity = self.github.identity(repo.author_email)
754
+ reasons = []
755
+ if info["fork"]:
756
+ reasons.append("Fork commits do not qualify")
757
+ if branch not in {info["default_branch"], "gh-pages"}:
758
+ reasons.append("Feature branch is not yet eligible")
759
+ eligible = "not_eligible" if reasons else "unknown"
760
+ if not reasons and identity["email_association"] == "verified" and info.get("permissions", {}).get("push"):
761
+ eligible = "likely"
762
+ return {"eligibility": eligible, "identity": identity, "reasons": reasons,
763
+ "guaranteed": False, "observed_profile_contributions": None}
764
+
765
+ @serialized
766
+ def publish_branch(self, job_id: str) -> dict:
767
+ job = self._job(job_id, True)
768
+ self.policy.authorize(job, "push")
769
+ if job["state"] not in {"VERIFIED", "PUBLISHING", "PUBLISHED", "COMPLETED"}:
770
+ raise AppError("INVALID_STATE", "Verified nonempty final tree required")
771
+ work = self._work(job)
772
+ self._reconcile(job)
773
+ if self.git.text(work, "rev-parse", "HEAD^{tree}") != job["final_tree"]:
774
+ raise AppError("INVARIANT_FAILED", "Approved final tree mismatch")
775
+ if not self._checks(job)["passed"]:
776
+ raise AppError("CHECK_FAILED", "Final checks failed")
777
+ remote = self.git.remote_sha(work, job["target_branch"])
778
+ if remote == job["current_sha"] and job["state"] in {"PUBLISHING", "PUBLISHED", "COMPLETED"}:
779
+ job["state"] = "PUBLISHED" if not job["pr_url"] else "COMPLETED"
780
+ self.db.save(job, "PUSH_CONFIRMED")
781
+ return self._report(job)
782
+ if remote != job["expected_remote"]:
783
+ raise AppError("REMOTE_DIVERGED", "Target branch changed; push stopped")
784
+ repo = self.policy.repo(job["repository"])
785
+ if self.git.remote_sha(work, job.get("base_branch", repo.default_branch)) != job["base_sha"]:
786
+ raise AppError("REMOTE_DIVERGED", "Base branch advanced; create a fresh job")
787
+ if repo.source.startswith("https://github.com/"):
788
+ if not repo.required_checks:
789
+ raise AppError("CHECKS_REQUIRED", "Configure and authorize required tests before GitHub publishing")
790
+ info = self.github.info(job["repository"])
791
+ if not info.get("permissions", {}).get("push"):
792
+ raise AppError("PERMISSION_DENIED", "GitHub actor lacks push rights")
793
+ try:
794
+ rules = self.github.request("GET", f"/repos/{job['repository']}/rules/branches/" + quote(job["target_branch"], safe=""))
795
+ except AppError as error:
796
+ # Only a verified, private-repository GitHub plan limitation may
797
+ # fall back to no available rulesets. All other errors fail closed.
798
+ if error.code != "RULESETS_UNAVAILABLE" or info.get("private") is not True:
799
+ raise
800
+ rules = []
801
+ if any(r.get("type") == "required_signatures" for r in rules):
802
+ raise AppError("SIGNING_REQUIRED", "Configure a legitimate signing workflow; unsigned publication blocked")
803
+ # gh owns HTTPS credential transport, separately from the REST vault. No PAT arguments.
804
+ self._push_via_gh(job, work)
805
+ else:
806
+ job["state"] = "PUBLISHING"
807
+ self.db.save(job, "PUBLISHING")
808
+ self.git.run(work, "push", "--porcelain", "origin", "HEAD:refs/heads/" + job["target_branch"])
809
+ if self.git.remote_sha(work, job["target_branch"]) != job["current_sha"]:
810
+ raise AppError("RETRYABLE_ERROR", "Push acknowledgment uncertain; resume inspects remote")
811
+ job["state"] = "PUBLISHED"
812
+ self.db.save(job, "PUBLISHED")
813
+ return self._report(job)
814
+
815
+ def _push_via_gh(self, job, work):
816
+ # Use the same OS-vault PAT for REST and gh without gh auth login's
817
+ # documented plaintext fallback. Only these trusted network children see it.
818
+ from github_ai_mcp.security.auth_github import get_token
819
+ env = {k: v for k, v in os.environ.items() if not k.startswith(("GIT_", "GH_", "GITHUB_"))}
820
+ env.update(GH_TOKEN=get_token(), GIT_TERMINAL_PROMPT="0", GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull)
821
+ try:
822
+ auth = run_background(["gh", "auth", "status", "--hostname", "github.com"],
823
+ env=env, capture_output=True, timeout=20)
824
+ except (OSError, subprocess.TimeoutExpired):
825
+ raise AppError("AUTH_REQUIRED", "Install GitHub CLI, then sign in using the GUI") from None
826
+ if auth.returncode:
827
+ raise AppError("AUTH_REQUIRED", "Sign in using the GUI for HTTPS Git transport")
828
+ # Verify Git transport actor matches API actor; differing accounts cannot silently publish.
829
+ try:
830
+ actor = run_background(["gh", "api", "user", "--jq", ".login"], env=env, capture_output=True, timeout=20)
831
+ except (OSError, subprocess.TimeoutExpired):
832
+ raise AppError("AUTH_REQUIRED", "GitHub CLI actor verification failed") from None
833
+ expected = self.github.request("GET", "/user")["login"]
834
+ if actor.returncode or actor.stdout.decode().strip() != expected:
835
+ raise AppError("IDENTITY_MISMATCH", "GitHub CLI and REST credentials belong to different actors")
836
+ job["state"] = "PUBLISHING"
837
+ self.db.save(job, "PUBLISHING")
838
+ try:
839
+ process = run_background(["git", "-c", "credential.helper=", "-c",
840
+ "credential.https://github.com.helper=!gh auth git-credential",
841
+ "-c", "core.hooksPath=" + os.devnull,
842
+ "push", "--porcelain", "origin", "HEAD:refs/heads/" + job["target_branch"]],
843
+ cwd=work, env=env, capture_output=True, timeout=120)
844
+ except (OSError, subprocess.TimeoutExpired):
845
+ raise AppError("RETRYABLE_ERROR", "Push interrupted; resume before retry") from None
846
+ if process.returncode:
847
+ raise AppError("PUSH_REJECTED", "GitHub rejected push; inspect permissions, protection or divergence")
848
+
849
+ @serialized
850
+ def create_pull_request(self, job_id: str, title: str, description: str) -> dict:
851
+ job = self._job(job_id, True)
852
+ self.policy.authorize(job, "pr")
853
+ if job["state"] not in {"PUBLISHED", "COMPLETED"}:
854
+ raise AppError("INVALID_STATE", "Publish branch before PR")
855
+ if not 1 <= len(title) <= 200 or len(description) > 10000:
856
+ raise AppError("LIMIT_EXCEEDED", "PR title/body too large")
857
+ scan((title + description).encode())
858
+ if not self.policy.repo(job["repository"]).source.startswith("https://github.com/"):
859
+ raise AppError("LOCAL_REMOTE", "Local Git remote has no GitHub PR API")
860
+ if self.git.remote_sha(self._work(job), job["target_branch"]) != job["current_sha"]:
861
+ raise AppError("REMOTE_DIVERGED", "Remote no longer matches job")
862
+ if job["pr_url"]:
863
+ return {"url": job["pr_url"], "existing": True}
864
+ # Reconcile a successful POST with lost acknowledgment before issuing another POST.
865
+ prs = self.github.request("GET", f"/repos/{job['repository']}/pulls")
866
+ existing = next((p for p in prs if p["head"]["ref"] == job["target_branch"]
867
+ and p["base"]["ref"] == self.policy.repo(job["repository"]).default_branch), None)
868
+ breakdown = "\n".join(f"- `{c['path']}`: `{c['sha']}`" for c in job["commits"])
869
+ body = (f"## Summary\n{description}\n\n## Files Changed\n{breakdown}\n\n## Testing\n"
870
+ f"{json.dumps(job['checks'])}\n\n## Commit Breakdown\n{breakdown}\n\n"
871
+ "## Security/Compatibility Notes\nAI-assisted; final tree verified. Intermediate commits may not build. "
872
+ f"Squash merge changes history. Local report: job {job['id']}.")
873
+ pr = existing or self.github.request("POST", f"/repos/{job['repository']}/pulls",
874
+ {"title": title, "body": body, "head": job["target_branch"],
875
+ "base": self.policy.repo(job["repository"]).default_branch})
876
+ job.update(pr_url=pr["html_url"], state="COMPLETED")
877
+ self.db.save(job, "PR_CONFIRMED")
878
+ return {"url": job["pr_url"], "existing": existing is not None}
879
+
880
+ @serialized
881
+ def get_remote_status(self, job_id: str) -> dict:
882
+ job = self._job(job_id)
883
+ remote = self.git.remote_sha(self._work(job), job["target_branch"])
884
+ result = {"remote_sha": remote, "matches": remote == job.get("current_sha"), "ci": "unknown", "pr_url": job["pr_url"]}
885
+ repo = self.policy.repo(job["repository"])
886
+ if remote and repo.source.startswith("https://github.com/"):
887
+ result["ci"] = self.github.request("GET", f"/repos/{job['repository']}/commits/{remote}/status")["state"]
888
+ result["check_runs"] = self.github.request("GET", f"/repos/{job['repository']}/commits/{remote}/check-runs")
889
+ return result