| | @@ -3,22 +3,34 @@ |
| 3 | 3 | All endpoints live under /projects/<slug>/fossil/api/. |
| 4 | 4 | Auth: Bearer token (APIToken or PersonalAccessToken) or session cookie. |
| 5 | 5 | All responses are JSON. All read endpoints check can_read_project. |
| 6 | 6 | """ |
| 7 | 7 | |
| 8 | +import json |
| 9 | +import logging |
| 8 | 10 | import math |
| 11 | +import re |
| 12 | +import shutil |
| 13 | +import subprocess |
| 14 | +import tempfile |
| 15 | +import time |
| 9 | 16 | |
| 10 | | -from django.http import JsonResponse |
| 17 | +from django.db import transaction |
| 18 | +from django.http import JsonResponse, StreamingHttpResponse |
| 11 | 19 | from django.shortcuts import get_object_or_404 |
| 20 | +from django.test import RequestFactory |
| 21 | +from django.utils import timezone |
| 12 | 22 | from django.views.decorators.csrf import csrf_exempt |
| 13 | 23 | from django.views.decorators.http import require_GET |
| 14 | 24 | |
| 15 | 25 | from fossil.api_auth import authenticate_request |
| 16 | 26 | from fossil.models import FossilRepository |
| 17 | 27 | from fossil.reader import FossilReader |
| 18 | | -from projects.access import can_read_project |
| 28 | +from projects.access import can_read_project, can_write_project |
| 19 | 29 | from projects.models import Project |
| 30 | + |
| 31 | +logger = logging.getLogger(__name__) |
| 20 | 32 | |
| 21 | 33 | |
| 22 | 34 | def _get_repo(slug): |
| 23 | 35 | """Look up project and repository by slug, or return 404 JSON.""" |
| 24 | 36 | project = get_object_or_404(Project, slug=slug, deleted_at__isnull=True) |
| | @@ -97,10 +109,87 @@ |
| 97 | 109 | {"method": "GET", "path": f"{base}/wiki/<name>", "description": "Single wiki page with content"}, |
| 98 | 110 | {"method": "GET", "path": f"{base}/branches", "description": "Branch list"}, |
| 99 | 111 | {"method": "GET", "path": f"{base}/tags", "description": "Tag list"}, |
| 100 | 112 | {"method": "GET", "path": f"{base}/releases", "description": "Release list"}, |
| 101 | 113 | {"method": "GET", "path": f"{base}/search", "description": "Search across checkins, tickets, wiki", "params": "q"}, |
| 114 | + { |
| 115 | + "method": "POST", |
| 116 | + "path": f"{base}/batch", |
| 117 | + "description": "Execute multiple API calls in a single request (max 25)", |
| 118 | + "body": '{"requests": [{"method": "GET", "path": "/api/timeline", "params": {}}]}', |
| 119 | + }, |
| 120 | + {"method": "GET", "path": f"{base}/workspaces", "description": "List agent workspaces", "params": "status"}, |
| 121 | + { |
| 122 | + "method": "POST", |
| 123 | + "path": f"{base}/workspaces/create", |
| 124 | + "description": "Create an isolated agent workspace", |
| 125 | + "body": '{"name": "...", "description": "...", "agent_id": "..."}', |
| 126 | + }, |
| 127 | + {"method": "GET", "path": f"{base}/workspaces/<name>", "description": "Get workspace details"}, |
| 128 | + { |
| 129 | + "method": "POST", |
| 130 | + "path": f"{base}/workspaces/<name>/commit", |
| 131 | + "description": "Commit changes in a workspace", |
| 132 | + "body": '{"message": "...", "files": []}', |
| 133 | + }, |
| 134 | + { |
| 135 | + "method": "POST", |
| 136 | + "path": f"{base}/workspaces/<name>/merge", |
| 137 | + "description": "Merge workspace branch back to trunk", |
| 138 | + "body": '{"target_branch": "trunk"}', |
| 139 | + }, |
| 140 | + { |
| 141 | + "method": "DELETE", |
| 142 | + "path": f"{base}/workspaces/<name>/abandon", |
| 143 | + "description": "Abandon and clean up a workspace", |
| 144 | + }, |
| 145 | + { |
| 146 | + "method": "POST", |
| 147 | + "path": f"{base}/tickets/<uuid>/claim", |
| 148 | + "description": "Claim a ticket for exclusive agent work", |
| 149 | + "body": '{"agent_id": "...", "workspace": "..."}', |
| 150 | + }, |
| 151 | + { |
| 152 | + "method": "POST", |
| 153 | + "path": f"{base}/tickets/<uuid>/release", |
| 154 | + "description": "Release a ticket claim", |
| 155 | + }, |
| 156 | + { |
| 157 | + "method": "POST", |
| 158 | + "path": f"{base}/tickets/<uuid>/submit", |
| 159 | + "description": "Submit completed work for a claimed ticket", |
| 160 | + "body": '{"summary": "...", "files_changed": [...]}', |
| 161 | + }, |
| 162 | + { |
| 163 | + "method": "GET", |
| 164 | + "path": f"{base}/tickets/unclaimed", |
| 165 | + "description": "List tickets not claimed by any agent", |
| 166 | + "params": "status, limit", |
| 167 | + }, |
| 168 | + {"method": "GET", "path": f"{base}/events", "description": "Server-Sent Events stream for real-time events"}, |
| 169 | + { |
| 170 | + "method": "POST", |
| 171 | + "path": f"{base}/reviews/create", |
| 172 | + "description": "Submit code changes for review", |
| 173 | + "body": '{"title": "...", "diff": "...", "files_changed": [...], "agent_id": "..."}', |
| 174 | + }, |
| 175 | + { |
| 176 | + "method": "GET", |
| 177 | + "path": f"{base}/reviews", |
| 178 | + "description": "List code reviews", |
| 179 | + "params": "status, page, per_page", |
| 180 | + }, |
| 181 | + {"method": "GET", "path": f"{base}/reviews/<id>", "description": "Get review with comments"}, |
| 182 | + { |
| 183 | + "method": "POST", |
| 184 | + "path": f"{base}/reviews/<id>/comment", |
| 185 | + "description": "Add a comment to a review", |
| 186 | + "body": '{"body": "...", "file_path": "...", "line_number": 42, "author": "..."}', |
| 187 | + }, |
| 188 | + {"method": "POST", "path": f"{base}/reviews/<id>/approve", "description": "Approve a review"}, |
| 189 | + {"method": "POST", "path": f"{base}/reviews/<id>/request-changes", "description": "Request changes on a review"}, |
| 190 | + {"method": "POST", "path": f"{base}/reviews/<id>/merge", "description": "Merge an approved review"}, |
| 102 | 191 | ], |
| 103 | 192 | "auth": "Bearer token (Authorization: Bearer <token>) or session cookie", |
| 104 | 193 | } |
| 105 | 194 | ) |
| 106 | 195 | |
| | @@ -471,5 +560,1354 @@ |
| 471 | 560 | checkin["timestamp"] = _isoformat(checkin.get("timestamp")) |
| 472 | 561 | for ticket in results.get("tickets", []): |
| 473 | 562 | ticket["created"] = _isoformat(ticket.get("created")) |
| 474 | 563 | |
| 475 | 564 | return JsonResponse(results) |
| 565 | + |
| 566 | + |
| 567 | +# --- Batch API --- |
| 568 | + |
| 569 | +# Map API paths to (view_function, extra_path_regex_or_None). |
| 570 | +# Entries with a regex capture group extract path params (e.g. ticket uuid, wiki page name). |
| 571 | +_BATCH_STATIC_ROUTES = { |
| 572 | + "/api/project": api_project, |
| 573 | + "/api/timeline": api_timeline, |
| 574 | + "/api/tickets": api_tickets, |
| 575 | + "/api/wiki": api_wiki_list, |
| 576 | + "/api/branches": api_branches, |
| 577 | + "/api/tags": api_tags, |
| 578 | + "/api/releases": api_releases, |
| 579 | + "/api/search": api_search, |
| 580 | +} |
| 581 | + |
| 582 | +_BATCH_DYNAMIC_ROUTES = [ |
| 583 | + (re.compile(r"^/api/tickets/([0-9a-fA-F-]+)$"), api_ticket_detail, "ticket_uuid"), |
| 584 | + (re.compile(r"^/api/wiki/(.+)$"), api_wiki_page, "page_name"), |
| 585 | +] |
| 586 | + |
| 587 | +_BATCH_MAX_REQUESTS = 25 |
| 588 | + |
| 589 | + |
| 590 | +def _resolve_batch_route(path): |
| 591 | + """Resolve a batch sub-request path to (view_func, kwargs) or (None, None).""" |
| 592 | + view_func = _BATCH_STATIC_ROUTES.get(path) |
| 593 | + if view_func is not None: |
| 594 | + return view_func, {} |
| 595 | + |
| 596 | + for pattern, view_func, kwarg_name in _BATCH_DYNAMIC_ROUTES: |
| 597 | + m = pattern.match(path) |
| 598 | + if m: |
| 599 | + return view_func, {kwarg_name: m.group(1)} |
| 600 | + |
| 601 | + return None, None |
| 602 | + |
| 603 | + |
| 604 | +@csrf_exempt |
| 605 | +def api_batch(request, slug): |
| 606 | + """Execute multiple API calls in a single request. |
| 607 | + |
| 608 | + POST /projects/<slug>/fossil/api/batch |
| 609 | + { |
| 610 | + "requests": [ |
| 611 | + {"method": "GET", "path": "/api/timeline", "params": {"per_page": 5}}, |
| 612 | + {"method": "GET", "path": "/api/tickets", "params": {"status": "Open"}}, |
| 613 | + {"method": "GET", "path": "/api/wiki/Home"} |
| 614 | + ] |
| 615 | + } |
| 616 | + |
| 617 | + Returns: |
| 618 | + { |
| 619 | + "responses": [ |
| 620 | + {"status": 200, "body": {...}}, |
| 621 | + {"status": 200, "body": {...}}, |
| 622 | + {"status": 200, "body": {...}} |
| 623 | + ] |
| 624 | + } |
| 625 | + |
| 626 | + Auth: same as other API endpoints (Bearer token or session). |
| 627 | + Limit: 25 sub-requests per batch. |
| 628 | + Only GET sub-requests are supported. |
| 629 | + """ |
| 630 | + if request.method != "POST": |
| 631 | + return JsonResponse({"error": "POST required"}, status=405) |
| 632 | + |
| 633 | + # Auth check -- same as every other API endpoint |
| 634 | + project, repo = _get_repo(slug) |
| 635 | + user, token, err = _check_api_auth(request, project, repo) |
| 636 | + if err is not None: |
| 637 | + return err |
| 638 | + |
| 639 | + try: |
| 640 | + body = json.loads(request.body) |
| 641 | + except (json.JSONDecodeError, ValueError): |
| 642 | + return JsonResponse({"error": "Invalid JSON body"}, status=400) |
| 643 | + |
| 644 | + requests_list = body.get("requests") |
| 645 | + if not isinstance(requests_list, list): |
| 646 | + return JsonResponse({"error": "'requests' must be a list"}, status=400) |
| 647 | + |
| 648 | + if len(requests_list) > _BATCH_MAX_REQUESTS: |
| 649 | + return JsonResponse({"error": f"Maximum {_BATCH_MAX_REQUESTS} requests per batch"}, status=400) |
| 650 | + |
| 651 | + if len(requests_list) == 0: |
| 652 | + return JsonResponse({"responses": []}) |
| 653 | + |
| 654 | + factory = RequestFactory() |
| 655 | + responses = [] |
| 656 | + |
| 657 | + for sub in requests_list: |
| 658 | + if not isinstance(sub, dict): |
| 659 | + responses.append({"status": 400, "body": {"error": "Each request must be an object"}}) |
| 660 | + continue |
| 661 | + |
| 662 | + method = (sub.get("method") or "GET").upper() |
| 663 | + path = sub.get("path", "") |
| 664 | + params = sub.get("params") or {} |
| 665 | + |
| 666 | + if method != "GET": |
| 667 | + responses.append({"status": 405, "body": {"error": "Only GET is supported in batch requests"}}) |
| 668 | + continue |
| 669 | + |
| 670 | + if not path: |
| 671 | + responses.append({"status": 400, "body": {"error": "Missing 'path'"}}) |
| 672 | + continue |
| 673 | + |
| 674 | + view_func, extra_kwargs = _resolve_batch_route(path) |
| 675 | + if view_func is None: |
| 676 | + responses.append({"status": 404, "body": {"error": f"Unknown API path: {path}"}}) |
| 677 | + continue |
| 678 | + |
| 679 | + # Build a synthetic GET request preserving auth from the outer request |
| 680 | + full_path = f"/projects/{slug}/fossil{path}" |
| 681 | + synthetic = factory.get(full_path, data=params) |
| 682 | + |
| 683 | + # Carry over auth state so sub-requests don't re-authenticate |
| 684 | + synthetic.user = request.user |
| 685 | + synthetic.session = request.session |
| 686 | + if "HTTP_AUTHORIZATION" in request.META: |
| 687 | + synthetic.META["HTTP_AUTHORIZATION"] = request.META["HTTP_AUTHORIZATION"] |
| 688 | + |
| 689 | + try: |
| 690 | + sub_response = view_func(synthetic, slug=slug, **extra_kwargs) |
| 691 | + try: |
| 692 | + response_body = json.loads(sub_response.content) |
| 693 | + except (json.JSONDecodeError, ValueError): |
| 694 | + response_body = {"raw": sub_response.content.decode("utf-8", errors="replace")} |
| 695 | + responses.append({"status": sub_response.status_code, "body": response_body}) |
| 696 | + except Exception: |
| 697 | + logger.exception("Batch sub-request failed: %s %s", method, path) |
| 698 | + responses.append({"status": 500, "body": {"error": "Internal error processing sub-request"}}) |
| 699 | + |
| 700 | + return JsonResponse({"responses": responses}) |
| 701 | + |
| 702 | + |
| 703 | +# --- Agent Workspace API --- |
| 704 | + |
| 705 | + |
| 706 | +def _get_workspace(repo, workspace_name): |
| 707 | + """Look up an active workspace by name, or return 404 JSON.""" |
| 708 | + from fossil.workspaces import AgentWorkspace |
| 709 | + |
| 710 | + workspace = AgentWorkspace.objects.filter(repository=repo, name=workspace_name).first() |
| 711 | + if workspace is None: |
| 712 | + return None |
| 713 | + return workspace |
| 714 | + |
| 715 | + |
| 716 | +@csrf_exempt |
| 717 | +def api_workspace_list(request, slug): |
| 718 | + """List agent workspaces for a repository. |
| 719 | + |
| 720 | + GET /projects/<slug>/fossil/api/workspaces |
| 721 | + Optional query params: status (active, merged, abandoned) |
| 722 | + """ |
| 723 | + if request.method != "GET": |
| 724 | + return JsonResponse({"error": "GET required"}, status=405) |
| 725 | + |
| 726 | + project, repo = _get_repo(slug) |
| 727 | + user, token, err = _check_api_auth(request, project, repo) |
| 728 | + if err is not None: |
| 729 | + return err |
| 730 | + |
| 731 | + from fossil.workspaces import AgentWorkspace |
| 732 | + |
| 733 | + qs = AgentWorkspace.objects.filter(repository=repo) |
| 734 | + status_filter = request.GET.get("status", "").strip() |
| 735 | + if status_filter: |
| 736 | + qs = qs.filter(status=status_filter) |
| 737 | + |
| 738 | + workspaces = [] |
| 739 | + for ws in qs: |
| 740 | + workspaces.append( |
| 741 | + { |
| 742 | + "name": ws.name, |
| 743 | + "branch": ws.branch, |
| 744 | + "status": ws.status, |
| 745 | + "agent_id": ws.agent_id, |
| 746 | + "description": ws.description, |
| 747 | + "files_changed": ws.files_changed, |
| 748 | + "commits_made": ws.commits_made, |
| 749 | + "created_at": _isoformat(ws.created_at), |
| 750 | + } |
| 751 | + ) |
| 752 | + |
| 753 | + return JsonResponse({"workspaces": workspaces}) |
| 754 | + |
| 755 | + |
| 756 | +@csrf_exempt |
| 757 | +def api_workspace_create(request, slug): |
| 758 | + """Create an isolated agent workspace. |
| 759 | + |
| 760 | + POST /projects/<slug>/fossil/api/workspaces/create |
| 761 | + {"name": "agent-fix-123", "description": "Fixing bug #123", "agent_id": "claude-abc"} |
| 762 | + |
| 763 | + Creates a new Fossil branch and checkout directory for the agent. |
| 764 | + """ |
| 765 | + if request.method != "POST": |
| 766 | + return JsonResponse({"error": "POST required"}, status=405) |
| 767 | + |
| 768 | + project, repo = _get_repo(slug) |
| 769 | + user, token, err = _check_api_auth(request, project, repo) |
| 770 | + if err is not None: |
| 771 | + return err |
| 772 | + |
| 773 | + # Write access required to create workspaces |
| 774 | + if token is None and (user is None or not can_write_project(user, project)): |
| 775 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 776 | + |
| 777 | + try: |
| 778 | + data = json.loads(request.body) |
| 779 | + except (json.JSONDecodeError, ValueError): |
| 780 | + return JsonResponse({"error": "Invalid JSON body"}, status=400) |
| 781 | + |
| 782 | + name = (data.get("name") or "").strip() |
| 783 | + if not name: |
| 784 | + return JsonResponse({"error": "Workspace name is required"}, status=400) |
| 785 | + |
| 786 | + if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9._-]{0,198}$", name): |
| 787 | + return JsonResponse( |
| 788 | + {"error": "Invalid workspace name. Use alphanumeric characters, hyphens, dots, and underscores."}, |
| 789 | + status=400, |
| 790 | + ) |
| 791 | + |
| 792 | + from fossil.workspaces import AgentWorkspace |
| 793 | + |
| 794 | + if AgentWorkspace.objects.filter(repository=repo, name=name).exists(): |
| 795 | + return JsonResponse({"error": f"Workspace '{name}' already exists"}, status=409) |
| 796 | + |
| 797 | + branch = f"workspace/{name}" |
| 798 | + |
| 799 | + # Create workspace checkout directory |
| 800 | + checkout_dir = tempfile.mkdtemp(prefix=f"fossilrepo-ws-{name}-") |
| 801 | + |
| 802 | + from fossil.cli import FossilCLI |
| 803 | + |
| 804 | + cli = FossilCLI() |
| 805 | + |
| 806 | + # Open a checkout in the workspace dir |
| 807 | + result = subprocess.run( |
| 808 | + [cli.binary, "open", str(repo.full_path), "--workdir", checkout_dir], |
| 809 | + capture_output=True, |
| 810 | + text=True, |
| 811 | + timeout=30, |
| 812 | + env=cli._env, |
| 813 | + cwd=checkout_dir, |
| 814 | + ) |
| 815 | + if result.returncode != 0: |
| 816 | + shutil.rmtree(checkout_dir, ignore_errors=True) |
| 817 | + return JsonResponse({"error": "Failed to open Fossil checkout", "detail": result.stderr.strip()}, status=500) |
| 818 | + |
| 819 | + # Create the branch from trunk |
| 820 | + result = subprocess.run( |
| 821 | + [cli.binary, "branch", "new", branch, "trunk"], |
| 822 | + capture_output=True, |
| 823 | + text=True, |
| 824 | + timeout=30, |
| 825 | + env=cli._env, |
| 826 | + cwd=checkout_dir, |
| 827 | + ) |
| 828 | + if result.returncode != 0: |
| 829 | + # Clean up on failure |
| 830 | + subprocess.run([cli.binary, "close", "--force"], capture_output=True, cwd=checkout_dir, timeout=10, env=cli._env) |
| 831 | + shutil.rmtree(checkout_dir, ignore_errors=True) |
| 832 | + return JsonResponse({"error": "Failed to create branch", "detail": result.stderr.strip()}, status=500) |
| 833 | + |
| 834 | + # Switch to the new branch |
| 835 | + result = subprocess.run( |
| 836 | + [cli.binary, "update", branch], |
| 837 | + capture_output=True, |
| 838 | + text=True, |
| 839 | + timeout=30, |
| 840 | + env=cli._env, |
| 841 | + cwd=checkout_dir, |
| 842 | + ) |
| 843 | + if result.returncode != 0: |
| 844 | + subprocess.run([cli.binary, "close", "--force"], capture_output=True, cwd=checkout_dir, timeout=10, env=cli._env) |
| 845 | + shutil.rmtree(checkout_dir, ignore_errors=True) |
| 846 | + return JsonResponse({"error": "Failed to switch to branch", "detail": result.stderr.strip()}, status=500) |
| 847 | + |
| 848 | + workspace = AgentWorkspace.objects.create( |
| 849 | + repository=repo, |
| 850 | + name=name, |
| 851 | + branch=branch, |
| 852 | + agent_id=data.get("agent_id", ""), |
| 853 | + description=data.get("description", ""), |
| 854 | + checkout_path=checkout_dir, |
| 855 | + created_by=user, |
| 856 | + ) |
| 857 | + |
| 858 | + return JsonResponse( |
| 859 | + { |
| 860 | + "name": workspace.name, |
| 861 | + "branch": workspace.branch, |
| 862 | + "status": workspace.status, |
| 863 | + "agent_id": workspace.agent_id, |
| 864 | + "description": workspace.description, |
| 865 | + "checkout_path": workspace.checkout_path, |
| 866 | + "created_at": _isoformat(workspace.created_at), |
| 867 | + }, |
| 868 | + status=201, |
| 869 | + ) |
| 870 | + |
| 871 | + |
| 872 | +@csrf_exempt |
| 873 | +def api_workspace_detail(request, slug, workspace_name): |
| 874 | + """Get details of a specific workspace. |
| 875 | + |
| 876 | + GET /projects/<slug>/fossil/api/workspaces/<name> |
| 877 | + """ |
| 878 | + if request.method != "GET": |
| 879 | + return JsonResponse({"error": "GET required"}, status=405) |
| 880 | + |
| 881 | + project, repo = _get_repo(slug) |
| 882 | + user, token, err = _check_api_auth(request, project, repo) |
| 883 | + if err is not None: |
| 884 | + return err |
| 885 | + |
| 886 | + workspace = _get_workspace(repo, workspace_name) |
| 887 | + if workspace is None: |
| 888 | + return JsonResponse({"error": "Workspace not found"}, status=404) |
| 889 | + |
| 890 | + return JsonResponse( |
| 891 | + { |
| 892 | + "name": workspace.name, |
| 893 | + "branch": workspace.branch, |
| 894 | + "status": workspace.status, |
| 895 | + "agent_id": workspace.agent_id, |
| 896 | + "description": workspace.description, |
| 897 | + "checkout_path": workspace.checkout_path, |
| 898 | + "files_changed": workspace.files_changed, |
| 899 | + "commits_made": workspace.commits_made, |
| 900 | + "created_at": _isoformat(workspace.created_at), |
| 901 | + "updated_at": _isoformat(workspace.updated_at), |
| 902 | + } |
| 903 | + ) |
| 904 | + |
| 905 | + |
| 906 | +@csrf_exempt |
| 907 | +def api_workspace_commit(request, slug, workspace_name): |
| 908 | + """Commit changes in a workspace. |
| 909 | + |
| 910 | + POST /projects/<slug>/fossil/api/workspaces/<name>/commit |
| 911 | + {"message": "Fix bug #123", "files": ["src/foo.py"]} |
| 912 | + |
| 913 | + If files is empty or omitted, commits all changed files. |
| 914 | + """ |
| 915 | + if request.method != "POST": |
| 916 | + return JsonResponse({"error": "POST required"}, status=405) |
| 917 | + |
| 918 | + project, repo = _get_repo(slug) |
| 919 | + user, token, err = _check_api_auth(request, project, repo) |
| 920 | + if err is not None: |
| 921 | + return err |
| 922 | + |
| 923 | + if token is None and (user is None or not can_write_project(user, project)): |
| 924 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 925 | + |
| 926 | + workspace = _get_workspace(repo, workspace_name) |
| 927 | + if workspace is None: |
| 928 | + return JsonResponse({"error": "Workspace not found"}, status=404) |
| 929 | + |
| 930 | + if workspace.status != "active": |
| 931 | + return JsonResponse({"error": f"Workspace is {workspace.status}, cannot commit"}, status=409) |
| 932 | + |
| 933 | + try: |
| 934 | + data = json.loads(request.body) |
| 935 | + except (json.JSONDecodeError, ValueError): |
| 936 | + return JsonResponse({"error": "Invalid JSON body"}, status=400) |
| 937 | + |
| 938 | + message = (data.get("message") or "").strip() |
| 939 | + if not message: |
| 940 | + return JsonResponse({"error": "Commit message is required"}, status=400) |
| 941 | + |
| 942 | + files = data.get("files") or [] |
| 943 | + checkout_dir = workspace.checkout_path |
| 944 | + |
| 945 | + from fossil.cli import FossilCLI |
| 946 | + |
| 947 | + cli = FossilCLI() |
| 948 | + |
| 949 | + # Add files if specified, otherwise add all changes |
| 950 | + if files: |
| 951 | + for f in files: |
| 952 | + subprocess.run( |
| 953 | + [cli.binary, "add", f], |
| 954 | + capture_output=True, |
| 955 | + text=True, |
| 956 | + timeout=30, |
| 957 | + env=cli._env, |
| 958 | + cwd=checkout_dir, |
| 959 | + ) |
| 960 | + else: |
| 961 | + subprocess.run( |
| 962 | + [cli.binary, "addremove"], |
| 963 | + capture_output=True, |
| 964 | + text=True, |
| 965 | + timeout=30, |
| 966 | + env=cli._env, |
| 967 | + cwd=checkout_dir, |
| 968 | + ) |
| 969 | + |
| 970 | + # Commit |
| 971 | + commit_cmd = [cli.binary, "commit", "-m", message, "--no-warnings"] |
| 972 | + result = subprocess.run( |
| 973 | + commit_cmd, |
| 974 | + capture_output=True, |
| 975 | + text=True, |
| 976 | + timeout=60, |
| 977 | + env=cli._env, |
| 978 | + cwd=checkout_dir, |
| 979 | + ) |
| 980 | + |
| 981 | + if result.returncode != 0: |
| 982 | + stderr = result.stderr.strip() |
| 983 | + # "nothing has changed" is not really an error |
| 984 | + if "nothing has changed" in stderr.lower() or "nothing has changed" in result.stdout.lower(): |
| 985 | + return JsonResponse({"error": "Nothing to commit"}, status=409) |
| 986 | + return JsonResponse({"error": "Commit failed", "detail": stderr}, status=500) |
| 987 | + |
| 988 | + workspace.commits_made += 1 |
| 989 | + workspace.save(update_fields=["commits_made", "updated_at", "version"]) |
| 990 | + |
| 991 | + return JsonResponse( |
| 992 | + { |
| 993 | + "name": workspace.name, |
| 994 | + "branch": workspace.branch, |
| 995 | + "commits_made": workspace.commits_made, |
| 996 | + "message": message, |
| 997 | + "output": result.stdout.strip(), |
| 998 | + } |
| 999 | + ) |
| 1000 | + |
| 1001 | + |
| 1002 | +@csrf_exempt |
| 1003 | +def api_workspace_merge(request, slug, workspace_name): |
| 1004 | + """Merge workspace branch back to trunk. |
| 1005 | + |
| 1006 | + POST /projects/<slug>/fossil/api/workspaces/<name>/merge |
| 1007 | + {"target_branch": "trunk"} |
| 1008 | + |
| 1009 | + Merges the workspace branch into the target branch (default: trunk), |
| 1010 | + then closes the workspace checkout and cleans up the directory. |
| 1011 | + """ |
| 1012 | + if request.method != "POST": |
| 1013 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1014 | + |
| 1015 | + project, repo = _get_repo(slug) |
| 1016 | + user, token, err = _check_api_auth(request, project, repo) |
| 1017 | + if err is not None: |
| 1018 | + return err |
| 1019 | + |
| 1020 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1021 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1022 | + |
| 1023 | + workspace = _get_workspace(repo, workspace_name) |
| 1024 | + if workspace is None: |
| 1025 | + return JsonResponse({"error": "Workspace not found"}, status=404) |
| 1026 | + |
| 1027 | + if workspace.status != "active": |
| 1028 | + return JsonResponse({"error": f"Workspace is {workspace.status}, cannot merge"}, status=409) |
| 1029 | + |
| 1030 | + try: |
| 1031 | + data = json.loads(request.body) if request.body else {} |
| 1032 | + except (json.JSONDecodeError, ValueError): |
| 1033 | + data = {} |
| 1034 | + |
| 1035 | + target_branch = (data.get("target_branch") or "trunk").strip() |
| 1036 | + |
| 1037 | + from fossil.cli import FossilCLI |
| 1038 | + |
| 1039 | + cli = FossilCLI() |
| 1040 | + checkout_dir = workspace.checkout_path |
| 1041 | + |
| 1042 | + # Switch to target branch |
| 1043 | + result = subprocess.run( |
| 1044 | + [cli.binary, "update", target_branch], |
| 1045 | + capture_output=True, |
| 1046 | + text=True, |
| 1047 | + timeout=30, |
| 1048 | + env=cli._env, |
| 1049 | + cwd=checkout_dir, |
| 1050 | + ) |
| 1051 | + if result.returncode != 0: |
| 1052 | + return JsonResponse({"error": "Failed to switch to target branch", "detail": result.stderr.strip()}, status=500) |
| 1053 | + |
| 1054 | + # Merge workspace branch into target |
| 1055 | + result = subprocess.run( |
| 1056 | + [cli.binary, "merge", workspace.branch], |
| 1057 | + capture_output=True, |
| 1058 | + text=True, |
| 1059 | + timeout=60, |
| 1060 | + env=cli._env, |
| 1061 | + cwd=checkout_dir, |
| 1062 | + ) |
| 1063 | + if result.returncode != 0: |
| 1064 | + return JsonResponse({"error": "Merge failed", "detail": result.stderr.strip()}, status=500) |
| 1065 | + |
| 1066 | + # Commit the merge |
| 1067 | + merge_msg = f"Merge {workspace.branch} into {target_branch}" |
| 1068 | + commit_result = subprocess.run( |
| 1069 | + [cli.binary, "commit", "-m", merge_msg, "--no-warnings"], |
| 1070 | + capture_output=True, |
| 1071 | + text=True, |
| 1072 | + timeout=60, |
| 1073 | + env=cli._env, |
| 1074 | + cwd=checkout_dir, |
| 1075 | + ) |
| 1076 | + |
| 1077 | + # Close the checkout and clean up |
| 1078 | + subprocess.run([cli.binary, "close", "--force"], capture_output=True, cwd=checkout_dir, timeout=10, env=cli._env) |
| 1079 | + shutil.rmtree(checkout_dir, ignore_errors=True) |
| 1080 | + |
| 1081 | + workspace.status = "merged" |
| 1082 | + workspace.checkout_path = "" |
| 1083 | + workspace.save(update_fields=["status", "checkout_path", "updated_at", "version"]) |
| 1084 | + |
| 1085 | + return JsonResponse( |
| 1086 | + { |
| 1087 | + "name": workspace.name, |
| 1088 | + "branch": workspace.branch, |
| 1089 | + "status": workspace.status, |
| 1090 | + "target_branch": target_branch, |
| 1091 | + "merge_output": result.stdout.strip(), |
| 1092 | + "commit_output": commit_result.stdout.strip() if commit_result.returncode == 0 else "", |
| 1093 | + } |
| 1094 | + ) |
| 1095 | + |
| 1096 | + |
| 1097 | +@csrf_exempt |
| 1098 | +def api_workspace_abandon(request, slug, workspace_name): |
| 1099 | + """Abandon a workspace, closing the checkout and cleaning up. |
| 1100 | + |
| 1101 | + DELETE /projects/<slug>/fossil/api/workspaces/<name>/abandon |
| 1102 | + |
| 1103 | + The branch remains in Fossil history but the checkout directory is removed. |
| 1104 | + """ |
| 1105 | + if request.method != "DELETE": |
| 1106 | + return JsonResponse({"error": "DELETE required"}, status=405) |
| 1107 | + |
| 1108 | + project, repo = _get_repo(slug) |
| 1109 | + user, token, err = _check_api_auth(request, project, repo) |
| 1110 | + if err is not None: |
| 1111 | + return err |
| 1112 | + |
| 1113 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1114 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1115 | + |
| 1116 | + workspace = _get_workspace(repo, workspace_name) |
| 1117 | + if workspace is None: |
| 1118 | + return JsonResponse({"error": "Workspace not found"}, status=404) |
| 1119 | + |
| 1120 | + if workspace.status != "active": |
| 1121 | + return JsonResponse({"error": f"Workspace is already {workspace.status}"}, status=409) |
| 1122 | + |
| 1123 | + from fossil.cli import FossilCLI |
| 1124 | + |
| 1125 | + cli = FossilCLI() |
| 1126 | + checkout_dir = workspace.checkout_path |
| 1127 | + |
| 1128 | + # Close checkout and clean up directory |
| 1129 | + if checkout_dir: |
| 1130 | + subprocess.run([cli.binary, "close", "--force"], capture_output=True, cwd=checkout_dir, timeout=10, env=cli._env) |
| 1131 | + shutil.rmtree(checkout_dir, ignore_errors=True) |
| 1132 | + |
| 1133 | + workspace.status = "abandoned" |
| 1134 | + workspace.checkout_path = "" |
| 1135 | + workspace.save(update_fields=["status", "checkout_path", "updated_at", "version"]) |
| 1136 | + |
| 1137 | + return JsonResponse( |
| 1138 | + { |
| 1139 | + "name": workspace.name, |
| 1140 | + "branch": workspace.branch, |
| 1141 | + "status": workspace.status, |
| 1142 | + } |
| 1143 | + ) |
| 1144 | + |
| 1145 | + |
| 1146 | +# --- Ticket Claiming --- |
| 1147 | + |
| 1148 | + |
| 1149 | +@csrf_exempt |
| 1150 | +def api_ticket_claim(request, slug, ticket_uuid): |
| 1151 | + """Claim a ticket for exclusive agent work. |
| 1152 | + |
| 1153 | + POST /projects/<slug>/fossil/api/tickets/<uuid>/claim |
| 1154 | + {"agent_id": "claude-abc", "workspace": "agent-fix-123"} |
| 1155 | + |
| 1156 | + Returns 200 if claimed, 409 if already claimed by another agent. |
| 1157 | + Uses the unique_together constraint on (repository, ticket_uuid) for atomicity. |
| 1158 | + """ |
| 1159 | + if request.method != "POST": |
| 1160 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1161 | + |
| 1162 | + project, repo = _get_repo(slug) |
| 1163 | + user, token, err = _check_api_auth(request, project, repo) |
| 1164 | + if err is not None: |
| 1165 | + return err |
| 1166 | + |
| 1167 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1168 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1169 | + |
| 1170 | + try: |
| 1171 | + data = json.loads(request.body) |
| 1172 | + except (json.JSONDecodeError, ValueError): |
| 1173 | + return JsonResponse({"error": "Invalid JSON body"}, status=400) |
| 1174 | + |
| 1175 | + agent_id = (data.get("agent_id") or "").strip() |
| 1176 | + if not agent_id: |
| 1177 | + return JsonResponse({"error": "agent_id is required"}, status=400) |
| 1178 | + |
| 1179 | + # Verify the ticket exists in Fossil |
| 1180 | + reader = FossilReader(repo.full_path) |
| 1181 | + with reader: |
| 1182 | + ticket = reader.get_ticket_detail(ticket_uuid) |
| 1183 | + if ticket is None: |
| 1184 | + return JsonResponse({"error": "Ticket not found in repository"}, status=404) |
| 1185 | + |
| 1186 | + # Resolve optional workspace reference |
| 1187 | + workspace_name = (data.get("workspace") or "").strip() |
| 1188 | + workspace_obj = None |
| 1189 | + if workspace_name: |
| 1190 | + from fossil.workspaces import AgentWorkspace |
| 1191 | + |
| 1192 | + workspace_obj = AgentWorkspace.objects.filter(repository=repo, name=workspace_name).first() |
| 1193 | + |
| 1194 | + from fossil.agent_claims import TicketClaim |
| 1195 | + |
| 1196 | + with transaction.atomic(): |
| 1197 | + # Check for existing active claim (not soft-deleted) with row lock |
| 1198 | + existing = TicketClaim.objects.select_for_update().filter(repository=repo, ticket_uuid=ticket_uuid).first() |
| 1199 | + |
| 1200 | + if existing: |
| 1201 | + if existing.agent_id == agent_id: |
| 1202 | + # Idempotent: same agent re-claiming |
| 1203 | + return JsonResponse( |
| 1204 | + { |
| 1205 | + "ticket_uuid": existing.ticket_uuid, |
| 1206 | + "agent_id": existing.agent_id, |
| 1207 | + "status": existing.status, |
| 1208 | + "claimed_at": _isoformat(existing.claimed_at), |
| 1209 | + "message": "Already claimed by you", |
| 1210 | + } |
| 1211 | + ) |
| 1212 | + return JsonResponse( |
| 1213 | + { |
| 1214 | + "error": "Ticket already claimed", |
| 1215 | + "claimed_by": existing.agent_id, |
| 1216 | + "claimed_at": _isoformat(existing.claimed_at), |
| 1217 | + }, |
| 1218 | + status=409, |
| 1219 | + ) |
| 1220 | + |
| 1221 | + claim = TicketClaim.objects.create( |
| 1222 | + repository=repo, |
| 1223 | + ticket_uuid=ticket_uuid, |
| 1224 | + agent_id=agent_id, |
| 1225 | + workspace=workspace_obj, |
| 1226 | + created_by=user, |
| 1227 | + ) |
| 1228 | + |
| 1229 | + return JsonResponse( |
| 1230 | + { |
| 1231 | + "ticket_uuid": claim.ticket_uuid, |
| 1232 | + "agent_id": claim.agent_id, |
| 1233 | + "status": claim.status, |
| 1234 | + "claimed_at": _isoformat(claim.claimed_at), |
| 1235 | + "workspace": workspace_name or None, |
| 1236 | + }, |
| 1237 | + status=201, |
| 1238 | + ) |
| 1239 | + |
| 1240 | + |
| 1241 | +@csrf_exempt |
| 1242 | +def api_ticket_release(request, slug, ticket_uuid): |
| 1243 | + """Release a ticket claim. |
| 1244 | + |
| 1245 | + POST /projects/<slug>/fossil/api/tickets/<uuid>/release |
| 1246 | + {"agent_id": "claude-abc"} |
| 1247 | + |
| 1248 | + Soft-deletes the claim record so the unique constraint slot is freed. |
| 1249 | + """ |
| 1250 | + if request.method != "POST": |
| 1251 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1252 | + |
| 1253 | + project, repo = _get_repo(slug) |
| 1254 | + user, token, err = _check_api_auth(request, project, repo) |
| 1255 | + if err is not None: |
| 1256 | + return err |
| 1257 | + |
| 1258 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1259 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1260 | + |
| 1261 | + from fossil.agent_claims import TicketClaim |
| 1262 | + |
| 1263 | + claim = TicketClaim.objects.filter(repository=repo, ticket_uuid=ticket_uuid).first() |
| 1264 | + if claim is None: |
| 1265 | + return JsonResponse({"error": "No active claim for this ticket"}, status=404) |
| 1266 | + |
| 1267 | + claim.status = "released" |
| 1268 | + claim.released_at = timezone.now() |
| 1269 | + claim.save(update_fields=["status", "released_at", "updated_at", "version"]) |
| 1270 | + # Soft-delete to free the unique constraint slot for future claims |
| 1271 | + claim.soft_delete(user=user) |
| 1272 | + |
| 1273 | + return JsonResponse( |
| 1274 | + { |
| 1275 | + "ticket_uuid": claim.ticket_uuid, |
| 1276 | + "agent_id": claim.agent_id, |
| 1277 | + "status": "released", |
| 1278 | + "released_at": _isoformat(claim.released_at), |
| 1279 | + } |
| 1280 | + ) |
| 1281 | + |
| 1282 | + |
| 1283 | +@csrf_exempt |
| 1284 | +def api_ticket_submit(request, slug, ticket_uuid): |
| 1285 | + """Submit completed work for a claimed ticket. |
| 1286 | + |
| 1287 | + POST /projects/<slug>/fossil/api/tickets/<uuid>/submit |
| 1288 | + { |
| 1289 | + "agent_id": "claude-abc", |
| 1290 | + "workspace": "agent-fix-123", |
| 1291 | + "summary": "Fixed the bug by ...", |
| 1292 | + "files_changed": ["src/foo.py", "tests/test_foo.py"] |
| 1293 | + } |
| 1294 | + |
| 1295 | + Updates the claim status to "submitted" and records the work summary. |
| 1296 | + Optionally adds a comment to the Fossil ticket. |
| 1297 | + """ |
| 1298 | + if request.method != "POST": |
| 1299 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1300 | + |
| 1301 | + project, repo = _get_repo(slug) |
| 1302 | + user, token, err = _check_api_auth(request, project, repo) |
| 1303 | + if err is not None: |
| 1304 | + return err |
| 1305 | + |
| 1306 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1307 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1308 | + |
| 1309 | + try: |
| 1310 | + data = json.loads(request.body) |
| 1311 | + except (json.JSONDecodeError, ValueError): |
| 1312 | + return JsonResponse({"error": "Invalid JSON body"}, status=400) |
| 1313 | + |
| 1314 | + from fossil.agent_claims import TicketClaim |
| 1315 | + |
| 1316 | + claim = TicketClaim.objects.filter(repository=repo, ticket_uuid=ticket_uuid).first() |
| 1317 | + if claim is None: |
| 1318 | + return JsonResponse({"error": "No active claim for this ticket"}, status=404) |
| 1319 | + |
| 1320 | + if claim.status != "claimed": |
| 1321 | + return JsonResponse({"error": f"Claim is already {claim.status}"}, status=409) |
| 1322 | + |
| 1323 | + summary = (data.get("summary") or "").strip() |
| 1324 | + files_changed = data.get("files_changed") or [] |
| 1325 | + |
| 1326 | + claim.status = "submitted" |
| 1327 | + claim.summary = summary |
| 1328 | + claim.files_changed = files_changed |
| 1329 | + claim.save(update_fields=["status", "summary", "files_changed", "updated_at", "version"]) |
| 1330 | + |
| 1331 | + # Optionally add a comment to the Fossil ticket via CLI |
| 1332 | + if summary: |
| 1333 | + from fossil.cli import FossilCLI |
| 1334 | + |
| 1335 | + cli = FossilCLI() |
| 1336 | + comment_text = f"[Agent: {claim.agent_id}] Work submitted.\n\n{summary}" |
| 1337 | + if files_changed: |
| 1338 | + comment_text += f"\n\nFiles changed: {', '.join(files_changed)}" |
| 1339 | + cli.ticket_change(repo.full_path, ticket_uuid, {"comment": comment_text}) |
| 1340 | + |
| 1341 | + return JsonResponse( |
| 1342 | + { |
| 1343 | + "ticket_uuid": claim.ticket_uuid, |
| 1344 | + "agent_id": claim.agent_id, |
| 1345 | + "status": claim.status, |
| 1346 | + "summary": claim.summary, |
| 1347 | + "files_changed": claim.files_changed, |
| 1348 | + } |
| 1349 | + ) |
| 1350 | + |
| 1351 | + |
| 1352 | +@csrf_exempt |
| 1353 | +def api_tickets_unclaimed(request, slug): |
| 1354 | + """List open tickets that aren't claimed by any agent. |
| 1355 | + |
| 1356 | + GET /projects/<slug>/fossil/api/tickets/unclaimed |
| 1357 | + Optional query params: status (default: Open), limit (default: 50) |
| 1358 | + """ |
| 1359 | + if request.method != "GET": |
| 1360 | + return JsonResponse({"error": "GET required"}, status=405) |
| 1361 | + |
| 1362 | + project, repo = _get_repo(slug) |
| 1363 | + user, token, err = _check_api_auth(request, project, repo) |
| 1364 | + if err is not None: |
| 1365 | + return err |
| 1366 | + |
| 1367 | + status_filter = request.GET.get("status", "Open").strip() |
| 1368 | + try: |
| 1369 | + limit = min(200, max(1, int(request.GET.get("limit", "50")))) |
| 1370 | + except (ValueError, TypeError): |
| 1371 | + limit = 50 |
| 1372 | + |
| 1373 | + # Get open tickets from Fossil |
| 1374 | + reader = FossilReader(repo.full_path) |
| 1375 | + with reader: |
| 1376 | + all_tickets = reader.get_tickets(status=status_filter, limit=500) |
| 1377 | + |
| 1378 | + # Get currently claimed ticket UUIDs |
| 1379 | + from fossil.agent_claims import TicketClaim |
| 1380 | + |
| 1381 | + claimed_uuids = set(TicketClaim.objects.filter(repository=repo).values_list("ticket_uuid", flat=True)) |
| 1382 | + |
| 1383 | + # Filter out claimed tickets |
| 1384 | + unclaimed = [] |
| 1385 | + for t in all_tickets: |
| 1386 | + if t.uuid not in claimed_uuids: |
| 1387 | + unclaimed.append( |
| 1388 | + { |
| 1389 | + "uuid": t.uuid, |
| 1390 | + "title": t.title, |
| 1391 | + "status": t.status, |
| 1392 | + "type": t.type, |
| 1393 | + "priority": t.priority, |
| 1394 | + "severity": t.severity, |
| 1395 | + "created": _isoformat(t.created), |
| 1396 | + } |
| 1397 | + ) |
| 1398 | + if len(unclaimed) >= limit: |
| 1399 | + break |
| 1400 | + |
| 1401 | + return JsonResponse({"tickets": unclaimed, "total": len(unclaimed)}) |
| 1402 | + |
| 1403 | + |
| 1404 | +# --- Server-Sent Events --- |
| 1405 | + |
| 1406 | + |
| 1407 | +@csrf_exempt |
| 1408 | +def api_events(request, slug): |
| 1409 | + """Server-Sent Events stream for real-time repository events. |
| 1410 | + |
| 1411 | + GET /projects/<slug>/fossil/api/events |
| 1412 | + |
| 1413 | + Streams events as SSE: |
| 1414 | + - checkin: new checkin pushed |
| 1415 | + - ticket: ticket created/updated (by count change) |
| 1416 | + - claim: ticket claimed/released/submitted |
| 1417 | + - workspace: workspace created/merged/abandoned |
| 1418 | + - review: code review created/updated |
| 1419 | + |
| 1420 | + Heartbeat sent every 15 seconds if no events. Poll interval: 5 seconds. |
| 1421 | + """ |
| 1422 | + if request.method != "GET": |
| 1423 | + return JsonResponse({"error": "GET required"}, status=405) |
| 1424 | + |
| 1425 | + project, repo = _get_repo(slug) |
| 1426 | + user, token, err = _check_api_auth(request, project, repo) |
| 1427 | + if err is not None: |
| 1428 | + return err |
| 1429 | + |
| 1430 | + def event_stream(): |
| 1431 | + from fossil.agent_claims import TicketClaim |
| 1432 | + from fossil.code_reviews import CodeReview |
| 1433 | + from fossil.workspaces import AgentWorkspace |
| 1434 | + |
| 1435 | + # Snapshot current state to detect changes |
| 1436 | + last_checkin_count = 0 |
| 1437 | + try: |
| 1438 | + with FossilReader(repo.full_path) as reader: |
| 1439 | + last_checkin_count = reader.get_checkin_count() |
| 1440 | + except Exception: |
| 1441 | + pass |
| 1442 | + |
| 1443 | + last_claim_id = TicketClaim.all_objects.filter(repository=repo).order_by("-pk").values_list("pk", flat=True).first() or 0 |
| 1444 | + last_workspace_id = AgentWorkspace.all_objects.filter(repository=repo).order_by("-pk").values_list("pk", flat=True).first() or 0 |
| 1445 | + last_review_id = CodeReview.all_objects.filter(repository=repo).order_by("-pk").values_list("pk", flat=True).first() or 0 |
| 1446 | + |
| 1447 | + heartbeat_counter = 0 |
| 1448 | + |
| 1449 | + while True: |
| 1450 | + events = [] |
| 1451 | + |
| 1452 | + # Check for new checkins |
| 1453 | + try: |
| 1454 | + with FossilReader(repo.full_path) as reader: |
| 1455 | + current_count = reader.get_checkin_count() |
| 1456 | + if current_count > last_checkin_count: |
| 1457 | + new_count = current_count - last_checkin_count |
| 1458 | + timeline = reader.get_timeline(limit=new_count, event_type="ci") |
| 1459 | + for entry in timeline: |
| 1460 | + events.append( |
| 1461 | + { |
| 1462 | + "type": "checkin", |
| 1463 | + "data": { |
| 1464 | + "uuid": entry.uuid, |
| 1465 | + "user": entry.user, |
| 1466 | + "comment": entry.comment, |
| 1467 | + "branch": entry.branch, |
| 1468 | + "timestamp": _isoformat(entry.timestamp), |
| 1469 | + }, |
| 1470 | + } |
| 1471 | + ) |
| 1472 | + last_checkin_count = current_count |
| 1473 | + except Exception: |
| 1474 | + pass |
| 1475 | + |
| 1476 | + # Check for new claims |
| 1477 | + new_claims = TicketClaim.all_objects.filter(repository=repo, pk__gt=last_claim_id).order_by("pk") |
| 1478 | + for claim in new_claims: |
| 1479 | + events.append( |
| 1480 | + { |
| 1481 | + "type": "claim", |
| 1482 | + "data": { |
| 1483 | + "ticket_uuid": claim.ticket_uuid, |
| 1484 | + "agent_id": claim.agent_id, |
| 1485 | + "status": claim.status, |
| 1486 | + "claimed_at": _isoformat(claim.claimed_at), |
| 1487 | + }, |
| 1488 | + } |
| 1489 | + ) |
| 1490 | + last_claim_id = claim.pk |
| 1491 | + |
| 1492 | + # Check for new workspaces |
| 1493 | + new_workspaces = AgentWorkspace.all_objects.filter(repository=repo, pk__gt=last_workspace_id).order_by("pk") |
| 1494 | + for ws in new_workspaces: |
| 1495 | + events.append( |
| 1496 | + { |
| 1497 | + "type": "workspace", |
| 1498 | + "data": { |
| 1499 | + "name": ws.name, |
| 1500 | + "branch": ws.branch, |
| 1501 | + "status": ws.status, |
| 1502 | + "agent_id": ws.agent_id, |
| 1503 | + }, |
| 1504 | + } |
| 1505 | + ) |
| 1506 | + last_workspace_id = ws.pk |
| 1507 | + |
| 1508 | + # Check for new code reviews |
| 1509 | + new_reviews = CodeReview.all_objects.filter(repository=repo, pk__gt=last_review_id).order_by("pk") |
| 1510 | + for review in new_reviews: |
| 1511 | + events.append( |
| 1512 | + { |
| 1513 | + "type": "review", |
| 1514 | + "data": { |
| 1515 | + "id": review.pk, |
| 1516 | + "title": review.title, |
| 1517 | + "status": review.status, |
| 1518 | + "agent_id": review.agent_id, |
| 1519 | + }, |
| 1520 | + } |
| 1521 | + ) |
| 1522 | + last_review_id = review.pk |
| 1523 | + |
| 1524 | + # Yield events |
| 1525 | + for event in events: |
| 1526 | + yield f"event: {event['type']}\ndata: {json.dumps(event['data'])}\n\n" |
| 1527 | + |
| 1528 | + # Heartbeat every ~15 seconds (3 iterations * 5s sleep) |
| 1529 | + heartbeat_counter += 1 |
| 1530 | + if not events and heartbeat_counter >= 3: |
| 1531 | + yield ": heartbeat\n\n" |
| 1532 | + heartbeat_counter = 0 |
| 1533 | + |
| 1534 | + time.sleep(5) |
| 1535 | + |
| 1536 | + response = StreamingHttpResponse(event_stream(), content_type="text/event-stream") |
| 1537 | + response["Cache-Control"] = "no-cache" |
| 1538 | + response["X-Accel-Buffering"] = "no" |
| 1539 | + return response |
| 1540 | + |
| 1541 | + |
| 1542 | +# --- Code Review API --- |
| 1543 | + |
| 1544 | + |
| 1545 | +@csrf_exempt |
| 1546 | +def api_review_create(request, slug): |
| 1547 | + """Submit code changes for review. |
| 1548 | + |
| 1549 | + POST /projects/<slug>/fossil/api/reviews/create |
| 1550 | + { |
| 1551 | + "title": "Fix null pointer in auth module", |
| 1552 | + "description": "The auth check was failing when ...", |
| 1553 | + "diff": "--- a/src/auth.py\\n+++ b/src/auth.py\\n...", |
| 1554 | + "files_changed": ["src/auth.py", "tests/test_auth.py"], |
| 1555 | + "agent_id": "claude-abc", |
| 1556 | + "workspace": "agent-fix-123", |
| 1557 | + "ticket_uuid": "abc123..." |
| 1558 | + } |
| 1559 | + """ |
| 1560 | + if request.method != "POST": |
| 1561 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1562 | + |
| 1563 | + project, repo = _get_repo(slug) |
| 1564 | + user, token, err = _check_api_auth(request, project, repo) |
| 1565 | + if err is not None: |
| 1566 | + return err |
| 1567 | + |
| 1568 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1569 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1570 | + |
| 1571 | + try: |
| 1572 | + data = json.loads(request.body) |
| 1573 | + except (json.JSONDecodeError, ValueError): |
| 1574 | + return JsonResponse({"error": "Invalid JSON body"}, status=400) |
| 1575 | + |
| 1576 | + title = (data.get("title") or "").strip() |
| 1577 | + if not title: |
| 1578 | + return JsonResponse({"error": "Review title is required"}, status=400) |
| 1579 | + |
| 1580 | + diff = (data.get("diff") or "").strip() |
| 1581 | + if not diff: |
| 1582 | + return JsonResponse({"error": "Diff is required"}, status=400) |
| 1583 | + |
| 1584 | + # Resolve optional workspace reference |
| 1585 | + workspace_name = (data.get("workspace") or "").strip() |
| 1586 | + workspace_obj = None |
| 1587 | + if workspace_name: |
| 1588 | + from fossil.workspaces import AgentWorkspace |
| 1589 | + |
| 1590 | + workspace_obj = AgentWorkspace.objects.filter(repository=repo, name=workspace_name).first() |
| 1591 | + |
| 1592 | + from fossil.code_reviews import CodeReview |
| 1593 | + |
| 1594 | + review = CodeReview.objects.create( |
| 1595 | + repository=repo, |
| 1596 | + workspace=workspace_obj, |
| 1597 | + title=title, |
| 1598 | + description=data.get("description", ""), |
| 1599 | + diff=diff, |
| 1600 | + files_changed=data.get("files_changed", []), |
| 1601 | + agent_id=data.get("agent_id", ""), |
| 1602 | + ticket_uuid=data.get("ticket_uuid", ""), |
| 1603 | + created_by=user, |
| 1604 | + ) |
| 1605 | + |
| 1606 | + return JsonResponse( |
| 1607 | + { |
| 1608 | + "id": review.pk, |
| 1609 | + "title": review.title, |
| 1610 | + "description": review.description, |
| 1611 | + "status": review.status, |
| 1612 | + "agent_id": review.agent_id, |
| 1613 | + "files_changed": review.files_changed, |
| 1614 | + "created_at": _isoformat(review.created_at), |
| 1615 | + }, |
| 1616 | + status=201, |
| 1617 | + ) |
| 1618 | + |
| 1619 | + |
| 1620 | +@csrf_exempt |
| 1621 | +def api_review_list(request, slug): |
| 1622 | + """List code reviews for a repository, optionally filtered by status. |
| 1623 | + |
| 1624 | + GET /projects/<slug>/fossil/api/reviews |
| 1625 | + Optional query params: status (pending, approved, changes_requested, merged) |
| 1626 | + """ |
| 1627 | + if request.method != "GET": |
| 1628 | + return JsonResponse({"error": "GET required"}, status=405) |
| 1629 | + |
| 1630 | + project, repo = _get_repo(slug) |
| 1631 | + user, token, err = _check_api_auth(request, project, repo) |
| 1632 | + if err is not None: |
| 1633 | + return err |
| 1634 | + |
| 1635 | + from fossil.code_reviews import CodeReview |
| 1636 | + |
| 1637 | + qs = CodeReview.objects.filter(repository=repo) |
| 1638 | + status_filter = request.GET.get("status", "").strip() |
| 1639 | + if status_filter: |
| 1640 | + qs = qs.filter(status=status_filter) |
| 1641 | + |
| 1642 | + page, per_page = _paginate_params(request) |
| 1643 | + total = qs.count() |
| 1644 | + total_pages = max(1, math.ceil(total / per_page)) |
| 1645 | + page = min(page, total_pages) |
| 1646 | + reviews_page = qs[(page - 1) * per_page : page * per_page] |
| 1647 | + |
| 1648 | + reviews = [] |
| 1649 | + for r in reviews_page: |
| 1650 | + reviews.append( |
| 1651 | + { |
| 1652 | + "id": r.pk, |
| 1653 | + "title": r.title, |
| 1654 | + "status": r.status, |
| 1655 | + "agent_id": r.agent_id, |
| 1656 | + "files_changed": r.files_changed, |
| 1657 | + "comment_count": r.comments.count(), |
| 1658 | + "created_at": _isoformat(r.created_at), |
| 1659 | + "updated_at": _isoformat(r.updated_at), |
| 1660 | + } |
| 1661 | + ) |
| 1662 | + |
| 1663 | + return JsonResponse( |
| 1664 | + { |
| 1665 | + "reviews": reviews, |
| 1666 | + "total": total, |
| 1667 | + "page": page, |
| 1668 | + "per_page": per_page, |
| 1669 | + "total_pages": total_pages, |
| 1670 | + } |
| 1671 | + ) |
| 1672 | + |
| 1673 | + |
| 1674 | +@csrf_exempt |
| 1675 | +def api_review_detail(request, slug, review_id): |
| 1676 | + """Get a code review with its comments. |
| 1677 | + |
| 1678 | + GET /projects/<slug>/fossil/api/reviews/<id> |
| 1679 | + """ |
| 1680 | + if request.method != "GET": |
| 1681 | + return JsonResponse({"error": "GET required"}, status=405) |
| 1682 | + |
| 1683 | + project, repo = _get_repo(slug) |
| 1684 | + user, token, err = _check_api_auth(request, project, repo) |
| 1685 | + if err is not None: |
| 1686 | + return err |
| 1687 | + |
| 1688 | + from fossil.code_reviews import CodeReview |
| 1689 | + |
| 1690 | + review = CodeReview.objects.filter(repository=repo, pk=review_id).first() |
| 1691 | + if review is None: |
| 1692 | + return JsonResponse({"error": "Review not found"}, status=404) |
| 1693 | + |
| 1694 | + comments = [] |
| 1695 | + for c in review.comments.all(): |
| 1696 | + comments.append( |
| 1697 | + { |
| 1698 | + "id": c.pk, |
| 1699 | + "body": c.body, |
| 1700 | + "file_path": c.file_path, |
| 1701 | + "line_number": c.line_number, |
| 1702 | + "author": c.author, |
| 1703 | + "created_at": _isoformat(c.created_at), |
| 1704 | + } |
| 1705 | + ) |
| 1706 | + |
| 1707 | + return JsonResponse( |
| 1708 | + { |
| 1709 | + "id": review.pk, |
| 1710 | + "title": review.title, |
| 1711 | + "description": review.description, |
| 1712 | + "diff": review.diff, |
| 1713 | + "status": review.status, |
| 1714 | + "agent_id": review.agent_id, |
| 1715 | + "files_changed": review.files_changed, |
| 1716 | + "ticket_uuid": review.ticket_uuid, |
| 1717 | + "workspace": review.workspace.name if review.workspace else None, |
| 1718 | + "comments": comments, |
| 1719 | + "created_at": _isoformat(review.created_at), |
| 1720 | + "updated_at": _isoformat(review.updated_at), |
| 1721 | + } |
| 1722 | + ) |
| 1723 | + |
| 1724 | + |
| 1725 | +@csrf_exempt |
| 1726 | +def api_review_comment(request, slug, review_id): |
| 1727 | + """Add a comment to a code review. |
| 1728 | + |
| 1729 | + POST /projects/<slug>/fossil/api/reviews/<id>/comment |
| 1730 | + { |
| 1731 | + "body": "This looks good but consider...", |
| 1732 | + "file_path": "src/auth.py", |
| 1733 | + "line_number": 42, |
| 1734 | + "author": "human-reviewer" |
| 1735 | + } |
| 1736 | + """ |
| 1737 | + if request.method != "POST": |
| 1738 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1739 | + |
| 1740 | + project, repo = _get_repo(slug) |
| 1741 | + user, token, err = _check_api_auth(request, project, repo) |
| 1742 | + if err is not None: |
| 1743 | + return err |
| 1744 | + |
| 1745 | + from fossil.code_reviews import CodeReview, ReviewComment |
| 1746 | + |
| 1747 | + review = CodeReview.objects.filter(repository=repo, pk=review_id).first() |
| 1748 | + if review is None: |
| 1749 | + return JsonResponse({"error": "Review not found"}, status=404) |
| 1750 | + |
| 1751 | + try: |
| 1752 | + data = json.loads(request.body) |
| 1753 | + except (json.JSONDecodeError, ValueError): |
| 1754 | + return JsonResponse({"error": "Invalid JSON body"}, status=400) |
| 1755 | + |
| 1756 | + body = (data.get("body") or "").strip() |
| 1757 | + if not body: |
| 1758 | + return JsonResponse({"error": "Comment body is required"}, status=400) |
| 1759 | + |
| 1760 | + author = (data.get("author") or "").strip() |
| 1761 | + if not author and user: |
| 1762 | + author = user.username |
| 1763 | + if not author: |
| 1764 | + return JsonResponse({"error": "Author is required"}, status=400) |
| 1765 | + |
| 1766 | + comment = ReviewComment.objects.create( |
| 1767 | + review=review, |
| 1768 | + body=body, |
| 1769 | + file_path=data.get("file_path", ""), |
| 1770 | + line_number=data.get("line_number"), |
| 1771 | + author=author, |
| 1772 | + created_by=user, |
| 1773 | + ) |
| 1774 | + |
| 1775 | + return JsonResponse( |
| 1776 | + { |
| 1777 | + "id": comment.pk, |
| 1778 | + "body": comment.body, |
| 1779 | + "file_path": comment.file_path, |
| 1780 | + "line_number": comment.line_number, |
| 1781 | + "author": comment.author, |
| 1782 | + "created_at": _isoformat(comment.created_at), |
| 1783 | + }, |
| 1784 | + status=201, |
| 1785 | + ) |
| 1786 | + |
| 1787 | + |
| 1788 | +@csrf_exempt |
| 1789 | +def api_review_approve(request, slug, review_id): |
| 1790 | + """Approve a code review. |
| 1791 | + |
| 1792 | + POST /projects/<slug>/fossil/api/reviews/<id>/approve |
| 1793 | + """ |
| 1794 | + if request.method != "POST": |
| 1795 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1796 | + |
| 1797 | + project, repo = _get_repo(slug) |
| 1798 | + user, token, err = _check_api_auth(request, project, repo) |
| 1799 | + if err is not None: |
| 1800 | + return err |
| 1801 | + |
| 1802 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1803 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1804 | + |
| 1805 | + from fossil.code_reviews import CodeReview |
| 1806 | + |
| 1807 | + review = CodeReview.objects.filter(repository=repo, pk=review_id).first() |
| 1808 | + if review is None: |
| 1809 | + return JsonResponse({"error": "Review not found"}, status=404) |
| 1810 | + |
| 1811 | + if review.status == "merged": |
| 1812 | + return JsonResponse({"error": "Review is already merged"}, status=409) |
| 1813 | + |
| 1814 | + review.status = "approved" |
| 1815 | + review.save(update_fields=["status", "updated_at", "version"]) |
| 1816 | + |
| 1817 | + return JsonResponse({"id": review.pk, "status": review.status}) |
| 1818 | + |
| 1819 | + |
| 1820 | +@csrf_exempt |
| 1821 | +def api_review_request_changes(request, slug, review_id): |
| 1822 | + """Request changes on a code review. |
| 1823 | + |
| 1824 | + POST /projects/<slug>/fossil/api/reviews/<id>/request-changes |
| 1825 | + {"comment": "Please fix the error handling in auth.py"} |
| 1826 | + """ |
| 1827 | + if request.method != "POST": |
| 1828 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1829 | + |
| 1830 | + project, repo = _get_repo(slug) |
| 1831 | + user, token, err = _check_api_auth(request, project, repo) |
| 1832 | + if err is not None: |
| 1833 | + return err |
| 1834 | + |
| 1835 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1836 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1837 | + |
| 1838 | + from fossil.code_reviews import CodeReview, ReviewComment |
| 1839 | + |
| 1840 | + review = CodeReview.objects.filter(repository=repo, pk=review_id).first() |
| 1841 | + if review is None: |
| 1842 | + return JsonResponse({"error": "Review not found"}, status=404) |
| 1843 | + |
| 1844 | + if review.status == "merged": |
| 1845 | + return JsonResponse({"error": "Review is already merged"}, status=409) |
| 1846 | + |
| 1847 | + review.status = "changes_requested" |
| 1848 | + review.save(update_fields=["status", "updated_at", "version"]) |
| 1849 | + |
| 1850 | + # Optionally add a comment with the change request |
| 1851 | + try: |
| 1852 | + data = json.loads(request.body) if request.body else {} |
| 1853 | + except (json.JSONDecodeError, ValueError): |
| 1854 | + data = {} |
| 1855 | + |
| 1856 | + comment_body = (data.get("comment") or "").strip() |
| 1857 | + if comment_body: |
| 1858 | + author = user.username if user else "reviewer" |
| 1859 | + ReviewComment.objects.create( |
| 1860 | + review=review, |
| 1861 | + body=comment_body, |
| 1862 | + author=author, |
| 1863 | + created_by=user, |
| 1864 | + ) |
| 1865 | + |
| 1866 | + return JsonResponse({"id": review.pk, "status": review.status}) |
| 1867 | + |
| 1868 | + |
| 1869 | +@csrf_exempt |
| 1870 | +def api_review_merge(request, slug, review_id): |
| 1871 | + """Merge an approved code review. |
| 1872 | + |
| 1873 | + POST /projects/<slug>/fossil/api/reviews/<id>/merge |
| 1874 | + |
| 1875 | + Only approved reviews can be merged. If the review is linked to a workspace, |
| 1876 | + the workspace merge is triggered. |
| 1877 | + """ |
| 1878 | + if request.method != "POST": |
| 1879 | + return JsonResponse({"error": "POST required"}, status=405) |
| 1880 | + |
| 1881 | + project, repo = _get_repo(slug) |
| 1882 | + user, token, err = _check_api_auth(request, project, repo) |
| 1883 | + if err is not None: |
| 1884 | + return err |
| 1885 | + |
| 1886 | + if token is None and (user is None or not can_write_project(user, project)): |
| 1887 | + return JsonResponse({"error": "Write access required"}, status=403) |
| 1888 | + |
| 1889 | + from fossil.code_reviews import CodeReview |
| 1890 | + |
| 1891 | + review = CodeReview.objects.filter(repository=repo, pk=review_id).first() |
| 1892 | + if review is None: |
| 1893 | + return JsonResponse({"error": "Review not found"}, status=404) |
| 1894 | + |
| 1895 | + if review.status == "merged": |
| 1896 | + return JsonResponse({"error": "Review is already merged"}, status=409) |
| 1897 | + |
| 1898 | + if review.status != "approved": |
| 1899 | + return JsonResponse({"error": "Review must be approved before merging"}, status=409) |
| 1900 | + |
| 1901 | + review.status = "merged" |
| 1902 | + review.save(update_fields=["status", "updated_at", "version"]) |
| 1903 | + |
| 1904 | + # If linked to a ticket claim, update the claim status |
| 1905 | + if review.ticket_uuid: |
| 1906 | + from fossil.agent_claims import TicketClaim |
| 1907 | + |
| 1908 | + claim = TicketClaim.objects.filter(repository=repo, ticket_uuid=review.ticket_uuid).first() |
| 1909 | + if claim and claim.status in ("claimed", "submitted"): |
| 1910 | + claim.status = "merged" |
| 1911 | + claim.save(update_fields=["status", "updated_at", "version"]) |
| 1912 | + |
| 1913 | + return JsonResponse({"id": review.pk, "status": review.status, "title": review.title}) |
| 476 | 1914 | |
| 477 | 1915 | ADDED fossil/code_reviews.py |
| 478 | 1916 | ADDED fossil/migrations/0010_historicalagentworkspace_agentworkspace.py |
| 479 | 1917 | ADDED fossil/migrations/0011_codereview_historicalcodereview_and_more.py |
| 480 | 1918 | ADDED fossil/migrations/0012_alter_ticketclaim_unique_together.py |