The file C:/Users/MikeSwanson/claude-projects/Autocode-remix/Autocode-fork/backend/app/routers/permissions.py has been updated. Here's the result of running `cat -n` on a snippet of the edited file:
     1→"""
     2→Permissions Router
     3→==================
     4→
     5→API endpoints for permission management within projects.
     6→"""
     7→
     8→from datetime import datetime
     9→from typing import Optional, List
    10→
    11→from fastapi import APIRouter, Depends, HTTPException, status
    12→from pydantic import BaseModel, Field
    13→from sqlalchemy import select, and_
    14→from sqlalchemy.ext.asyncio import AsyncSession
    15→
    16→from ..database import get_db
    17→from ..models import Project, Permission, PermissionRequest
    18→
    19→router = APIRouter(prefix="/api/projects", tags=["permissions"])
    20→
    21→
    22→# ============================================================================
    23→# Pydantic Schemas
    24→# ============================================================================
    25→
    26→class PermissionResponse(BaseModel):
    27→    """Schema for permission response."""
    28→    id: int
    29→    project_id: int
    30→    permission_type: str
    31→    permission_value: str
    32→    granted: bool
    33→    created_at: datetime
    34→
    35→    class Config:
    36→        from_attributes = True
    37→
    38→
    39→class PermissionListResponse(BaseModel):
    40→    """Schema for permission list response."""
    41→    permissions: List[PermissionResponse]
    42→    count: int
    43→
    44→
    45→class PermissionCreate(BaseModel):
    46→    """Schema for creating a permission."""
    47→    permission_type: str = Field(..., min_length=1, max_length=50)
    48→    permission_value: str = Field(..., min_length=1, max_length=500)
    49→    granted: bool = True
    50→
    51→
    52→class PermissionUpdate(BaseModel):
    53→    """Schema for updating a permission."""
    54→    granted: Optional[bool] = None
    55→
    56→
    57→class PermissionRequestResponse(BaseModel):
    58→    """Schema for permission request response."""
    59→    id: int
    60→    project_id: int
    61→    feature_id: Optional[int]
    62→    agent_id: str
    63→    permission_type: str
    64→    permission_value: str
    65→    status: str
    66→    requested_at: datetime
    67→    resolved_at: Optional[datetime]
    68→
    69→    class Config:
    70→        from_attributes = True
    71→
    72→
    73→class PermissionRequestListResponse(BaseModel):
    74→    """Schema for permission request list response."""
    75→    requests: List[PermissionRequestResponse]
    76→    count: int
    77→
    78→
    79→class PermissionRequestCreate(BaseModel):
    80→    """Schema for creating a permission request."""
    81→    agent_id: str = Field(..., min_length=1, max_length=1)  # "A" or "B"
    82→    permission_type: str = Field(..., min_length=1, max_length=50)
    83→    permission_value: str = Field(..., min_length=1, max_length=500)
    84→    feature_id: Optional[int] = None
    85→
    86→
    87→# ============================================================================
    88→# Permission Endpoints
    89→# ============================================================================
    90→
    91→@router.get("/{name}/permissions", response_model=PermissionListResponse)
    92→async def list_permissions(name: str, db: AsyncSession = Depends(get_db)):
    93→    """List all permissions for a project."""
    94→    # Verify project exists
    95→    result = await db.execute(select(Project).where(Project.name == name))
    96→    project = result.scalar_one_or_none()
    97→
    98→    if not project:
    99→        raise HTTPException(
   100→            status_code=status.HTTP_404_NOT_FOUND,
   101→            detail=f"Project '{name}' not found"
   102→        )
   103→
   104→    # Get permissions
   105→    result = await db.execute(
   106→        select(Permission)
   107→        .where(Permission.project_id == project.id)
   108→        .order_by(Permission.created_at.desc())
   109→    )
   110→    permissions = result.scalars().all()
   111→
   112→    return PermissionListResponse(
   113→        permissions=[PermissionResponse.model_validate(p) for p in permissions],
   114→        count=len(permissions)
   115→    )
   116→
   117→
   118→@router.post("/{name}/permissions", response_model=PermissionResponse, status_code=status.HTTP_201_CREATED)
   119→async def create_permission(name: str, permission: PermissionCreate, db: AsyncSession = Depends(get_db)):
   120→    """Create a new permission for a project."""
   121→    # Verify project exists
   122→    result = await db.execute(select(Project).where(Project.name == name))
   123→    project = result.scalar_one_or_none()
   124→
   125→    if not project:
   126→        raise HTTPException(
   127→            status_code=status.HTTP_404_NOT_FOUND,
   128→            detail=f"Project '{name}' not found"
   129→        )
   130→
   131→    # Check if permission already exists
   132→    result = await db.execute(
   133→        select(Permission).where(and_(
   134→            Permission.project_id == project.id,
   135→            Permission.permission_type == permission.permission_type,
   136→            Permission.permission_value == permission.permission_value
   137→        ))
   138→    )
   139→    existing = result.scalar_one_or_none()
   140→    if existing:
   141→        raise HTTPException(
   142→            status_code=status.HTTP_409_CONFLICT,
   143→            detail=f"Permission already exists"
   144→        )
   145→
   146→    # Create permission
   147→    db_permission = Permission(
   148→        project_id=project.id,
   149→        permission_type=permission.permission_type,
   150→        permission_value=permission.permission_value,
   151→        granted=permission.granted,
   152→    )
   153→    db.add(db_permission)
   154→    await db.commit()
   155→    await db.refresh(db_permission)
   156→
   157→    return PermissionResponse.model_validate(db_permission)
   158→
   159→
   160→@router.get("/{name}/permissions/{permission_id}", response_model=PermissionResponse)
   161→async def get_permission(name: str, permission_id: int, db: AsyncSession = Depends(get_db)):
   162→    """Get a specific permission by ID."""
   163→    # Verify project exists
   164→    result = await db.execute(select(Project).where(Project.name == name))
   165→    project = result.scalar_one_or_none()
   166→
   167→    if not project:
   168→        raise HTTPException(
   169→            status_code=status.HTTP_404_NOT_FOUND,
   170→            detail=f"Project '{name}' not found"
   171→        )
   172→
   173→    # Get permission
   174→    result = await db.execute(
   175→        select(Permission).where(and_(
   176→            Permission.id == permission_id,
   177→            Permission.project_id == project.id
   178→        ))
   179→    )
   180→    permission = result.scalar_one_or_none()
   181→
   182→    if not permission:
   183→        raise HTTPException(
   184→            status_code=status.HTTP_404_NOT_FOUND,
   185→            detail=f"Permission {permission_id} not found in project '{name}'"
   186→        )
   187→
   188→    return PermissionResponse.model_validate(permission)
   189→
   190→
   191→@router.put("/{name}/permissions/{permission_id}", response_model=PermissionResponse)
   192→async def update_permission(name: str, permission_id: int, permission_update: PermissionUpdate, db: AsyncSession = Depends(get_db)):
   193→    """Update a permission."""
   194→    # Verify project exists
   195→    result = await db.execute(select(Project).where(Project.name == name))
   196→    project = result.scalar_one_or_none()
   197→
   198→    if not project:
   199→        raise HTTPException(
   200→            status_code=status.HTTP_404_NOT_FOUND,
   201→            detail=f"Project '{name}' not found"
   202→        )
   203→
   204→    # Get permission
   205→    result = await db.execute(
   206→        select(Permission).where(and_(
   207→            Permission.id == permission_id,
   208→            Permission.project_id == project.id
   209→        ))
   210→    )
   211→    permission = result.scalar_one_or_none()
   212→
   213→    if not permission:
   214→        raise HTTPException(
   215→            status_code=status.HTTP_404_NOT_FOUND,
   216→            detail=f"Permission {permission_id} not found in project '{name}'"
   217→        )
   218→
   219→    # Update granted status
   220→    if permission_update.granted is not None:
   221→        permission.granted = permission_update.granted
   222→
   223→    await db.commit()
   224→    await db.refresh(permission)
   225→
   226→    return PermissionResponse.model_validate(permission)
   227→
   228→
   229→@router.delete("/{name}/permissions/{permission_id}", status_code=status.HTTP_204_NO_CONTENT)
   230→async def delete_permission(name: str, permission_id: int, db: AsyncSession = Depends(get_db)):
   231→    """Delete a permission."""
   232→    # Verify project exists
   233→    result = await db.execute(select(Project).where(Project.name == name))
   234→    project = result.scalar_one_or_none()
   235→
   236→    if not project:
   237→        raise HTTPException(
   238→            status_code=status.HTTP_404_NOT_FOUND,
   239→            detail=f"Project '{name}' not found"
   240→        )
   241→
   242→    # Get permission
   243→    result = await db.execute(
   244→        select(Permission).where(and_(
   245→            Permission.id == permission_id,
   246→            Permission.project_id == project.id
   247→        ))
   248→    )
   249→    permission = result.scalar_one_or_none()
   250→
   251→    if not permission:
   252→        raise HTTPException(
   253→            status_code=status.HTTP_404_NOT_FOUND,
   254→            detail=f"Permission {permission_id} not found in project '{name}'"
   255→        )
   256→
   257→    await db.delete(permission)
   258→    await db.commit()
   259→
   260→
   261→# ============================================================================
   262→# Permission Request Endpoints
   263→# ============================================================================
   264→
   265→@router.get("/{name}/permission-requests", response_model=PermissionRequestListResponse)
   266→async def list_permission_requests(
   267→    name: str,
   268→    status_filter: Optional[str] = None,
   269→    db: AsyncSession = Depends(get_db)
   270→):
   271→    """List permission requests for a project."""
   272→    # Verify project exists
   273→    result = await db.execute(select(Project).where(Project.name == name))
   274→    project = result.scalar_one_or_none()
   275→
   276→    if not project:
   277→        raise HTTPException(
   278→            status_code=status.HTTP_404_NOT_FOUND,
   279→            detail=f"Project '{name}' not found"
   280→        )
   281→
   282→    # Build query
   283→    query = select(PermissionRequest).where(PermissionRequest.project_id == project.id)
   284→
   285→    if status_filter:
   286→        query = query.where(PermissionRequest.status == status_filter)
   287→
   288→    query = query.order_by(PermissionRequest.requested_at.desc())
   289→
   290→    result = await db.execute(query)
   291→    requests = result.scalars().all()
   292→
   293→    return PermissionRequestListResponse(
   294→        requests=[PermissionRequestResponse.model_validate(r) for r in requests],
   295→        count=len(requests)
   296→    )
   297→
   298→
   299→@router.post("/{name}/permission-requests", response_model=PermissionRequestResponse, status_code=status.HTTP_201_CREATED)
   300→async def create_permission_request(name: str, request: PermissionRequestCreate, db: AsyncSession = Depends(get_db)):
   301→    """Create a new permission request (typically called by agents)."""
   302→    # Verify project exists
   303→    result = await db.execute(select(Project).where(Project.name == name))
   304→    project = result.scalar_one_or_none()
   305→
   306→    if not project:
   307→        raise HTTPException(
   308→            status_code=status.HTTP_404_NOT_FOUND,
   309→            detail=f"Project '{name}' not found"
   310→        )
   311→
   312→    # Create permission request
   313→    db_request = PermissionRequest(
   314→        project_id=project.id,
   315→        feature_id=request.feature_id,
   316→        agent_id=request.agent_id,
   317→        permission_type=request.permission_type,
   318→        permission_value=request.permission_value,
   319→        status="pending",
   320→    )
   321→    db.add(db_request)
   322→    await db.commit()
   323→    await db.refresh(db_request)
   324→
   325→    return PermissionRequestResponse.model_validate(db_request)
   326→
   327→
   328→@router.post("/{name}/permission-requests/{request_id}/grant", response_model=PermissionRequestResponse)
   329→async def grant_permission_request(name: str, request_id: int, db: AsyncSession = Depends(get_db)):
   330→    """Grant a pending permission request."""
   331→    # Verify project exists
   332→    result = await db.execute(select(Project).where(Project.name == name))
   333→    project = result.scalar_one_or_none()
   334→
   335→    if not project:
   336→        raise HTTPException(
   337→            status_code=status.HTTP_404_NOT_FOUND,
   338→            detail=f"Project '{name}' not found"
   339→        )
   340→
   341→    # Get permission request
   342→    result = await db.execute(
   343→        select(PermissionRequest).where(and_(
   344→            PermissionRequest.id == request_id,
   345→            PermissionRequest.project_id == project.id
   346→        ))
   347→    )
   348→    request = result.scalar_one_or_none()
   349→
   350→    if not request:
   351→        raise HTTPException(
   352→            status_code=status.HTTP_404_NOT_FOUND,
   353→            detail=f"Permission request {request_id} not found"
   354→        )
   355→
   356→    if request.status != "pending":
   357→        raise HTTPException(
   358→            status_code=status.HTTP_400_BAD_REQUEST,
   359→            detail=f"Permission request is already {request.status}"
   360→        )
   361→
   362→    # Update request status
   363→    request.status = "granted"
   364→    request.resolved_at = datetime.utcnow()
   365→
   366→    # Create the actual permission
   367→    db_permission = Permission(
   368→        project_id=project.id,
   369→        permission_type=request.permission_type,
   370→        permission_value=request.permission_value,
   371→        granted=True,
   372→    )
   373→    db.add(db_permission)
   374→
   375→    await db.commit()
   376→    await db.refresh(request)
   377→
   378→    return PermissionRequestResponse.model_validate(request)
   379→
   380→
   381→@router.post("/{name}/permission-requests/{request_id}/deny", response_model=PermissionRequestResponse)
   382→async def deny_permission_request(name: str, request_id: int, db: AsyncSession = Depends(get_db)):
   383→    """Deny a pending permission request."""
   384→    # Verify project exists
   385→    result = await db.execute(select(Project).where(Project.name == name))
   386→    project = result.scalar_one_or_none()
   387→
   388→    if not project:
   389→        raise HTTPException(
   390→            status_code=status.HTTP_404_NOT_FOUND,
   391→            detail=f"Project '{name}' not found"
   392→        )
   393→
   394→    # Get permission request
   395→    result = await db.execute(
   396→        select(PermissionRequest).where(and_(
   397→            PermissionRequest.id == request_id,
   398→            PermissionRequest.project_id == project.id
   399→        ))
   400→    )
   401→    request = result.scalar_one_or_none()
   402→
   403→    if not request:
   404→        raise HTTPException(
   405→            status_code=status.HTTP_404_NOT_FOUND,
   406→            detail=f"Permission request {request_id} not found"
   407→        )
   408→
   409→    if request.status != "pending":
   410→        raise HTTPException(
   411→            status_code=status.HTTP_400_BAD_REQUEST,
   412→            detail=f"Permission request is already {request.status}"
   413→        )
   414→
   415→    # Update request status
   416→    request.status = "denied"
   417→    request.resolved_at = datetime.utcnow()
   418→
   419→    await db.commit()
   420→    await db.refresh(request)
   421→
   422→    return PermissionRequestResponse.model_validate(request)
   423→

"""
Permissions Router
==================

API endpoints for permission management within projects.
"""

from datetime import datetime
from typing import Optional, List

from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy import select, and_
from sqlalchemy.ext.asyncio import AsyncSession

from ..database import get_db
from ..models import Project, Permission, PermissionRequest

router = APIRouter(prefix="/api/projects", tags=["permissions"])

# ============================================================================
# Pydantic Schemas
# ============================================================================

class PermissionResponse(BaseModel):
    """Schema for permission response."""
    id: int
    project_id: int
    permission_type: str
    permission_value: str
    granted: bool
    created_at: datetime

    class Config:
        from_attributes = True

class PermissionListResponse(BaseModel):
    """Schema for permission list response."""
    permissions: List[PermissionResponse]
    count: int

class PermissionCreate(BaseModel):
    """Schema for creating a permission."""
    permission_type: str = Field(..., min_length=1, max_length=50)
    permission_value: str = Field(..., min_length=1, max_length=500)
    granted: bool = True

class PermissionUpdate(BaseModel):
    """Schema for updating a permission."""
    granted: Optional[bool] = None

class PermissionRequestResponse(BaseModel):
    """Schema for permission request response."""
    id: int
    project_id: int
    feature_id: Optional[int]
    agent_id: str
    permission_type: str
    permission_value: str
    status: str
    requested_at: datetime
    resolved_at: Optional[datetime]

    class Config:
        from_attributes = True

class PermissionRequestListResponse(BaseModel):
    """Schema for permission request list response."""
    requests: List[PermissionRequestResponse]
    count: int

class PermissionRequestCreate(BaseModel):
    """Schema for creating a permission request."""
    agent_id: str = Field(..., min_length=1, max_length=1)  # "A" or "B"
    permission_type: str = Field(..., min_length=1, max_length=50)
    permission_value: str = Field(..., min_length=1, max_length=500)
    feature_id: Optional[int] = None

# ============================================================================
# Permission Endpoints
# ============================================================================

@router.get("/{name}/permissions", response_model=PermissionListResponse)
async def list_permissions(name: str, db: AsyncSession = Depends(get_db)):
    """List all permissions for a project."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permissions
    result = await db.execute(
        select(Permission)
        .where(Permission.project_id == project.id)
        .order_by(Permission.created_at.desc())
    )
    permissions = result.scalars().all()

    return PermissionListResponse(
        permissions=[PermissionResponse.model_validate(p) for p in permissions],
        count=len(permissions)
    )

@router.post("/{name}/permissions", response_model=PermissionResponse, status_code=status.HTTP_201_CREATED)
async def create_permission(name: str, permission: PermissionCreate, db: AsyncSession = Depends(get_db)):
    """Create a new permission for a project."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Check if permission already exists
    result = await db.execute(
        select(Permission).where(and_(
            Permission.project_id == project.id,
            Permission.permission_type == permission.permission_type,
            Permission.permission_value == permission.permission_value
        ))
    )
    existing = result.scalar_one_or_none()
    if existing:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=f"Permission already exists"
        )

    # Create permission
    db_permission = Permission(
        project_id=project.id,
        permission_type=permission.permission_type,
        permission_value=permission.permission_value,
        granted=permission.granted,
    )
    db.add(db_permission)
    await db.commit()
    await db.refresh(db_permission)

    return PermissionResponse.model_validate(db_permission)

@router.get("/{name}/permissions/{permission_id}", response_model=PermissionResponse)
async def get_permission(name: str, permission_id: int, db: AsyncSession = Depends(get_db)):
    """Get a specific permission by ID."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission
    result = await db.execute(
        select(Permission).where(and_(
            Permission.id == permission_id,
            Permission.project_id == project.id
        ))
    )
    permission = result.scalar_one_or_none()

    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission {permission_id} not found in project '{name}'"
        )

    return PermissionResponse.model_validate(permission)

@router.put("/{name}/permissions/{permission_id}", response_model=PermissionResponse)
async def update_permission(name: str, permission_id: int, permission_update: PermissionUpdate, db: AsyncSession = Depends(get_db)):
    """Update a permission."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission
    result = await db.execute(
        select(Permission).where(and_(
            Permission.id == permission_id,
            Permission.project_id == project.id
        ))
    )
    permission = result.scalar_one_or_none()

    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission {permission_id} not found in project '{name}'"
        )

    # Update granted status
    if permission_update.granted is not None:
        permission.granted = permission_update.granted

    await db.commit()
    await db.refresh(permission)

    return PermissionResponse.model_validate(permission)

@router.delete("/{name}/permissions/{permission_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_permission(name: str, permission_id: int, db: AsyncSession = Depends(get_db)):
    """Delete a permission."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission
    result = await db.execute(
        select(Permission).where(and_(
            Permission.id == permission_id,
            Permission.project_id == project.id
        ))
    )
    permission = result.scalar_one_or_none()

    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission {permission_id} not found in project '{name}'"
        )

    await db.delete(permission)
    await db.commit()

# ============================================================================
# Permission Request Endpoints
# ============================================================================

@router.get("/{name}/permission-requests", response_model=PermissionRequestListResponse)
async def list_permission_requests(
    name: str,
    status_filter: Optional[str] = None,
    db: AsyncSession = Depends(get_db)
):
    """List permission requests for a project."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Build query
    query = select(PermissionRequest).where(PermissionRequest.project_id == project.id)

    if status_filter:
        query = query.where(PermissionRequest.status == status_filter)

    query = query.order_by(PermissionRequest.requested_at.desc())

    result = await db.execute(query)
    requests = result.scalars().all()

    return PermissionRequestListResponse(
        requests=[PermissionRequestResponse.model_validate(r) for r in requests],
        count=len(requests)
    )

@router.post("/{name}/permission-requests", response_model=PermissionRequestResponse, status_code=status.HTTP_201_CREATED)
async def create_permission_request(name: str, request: PermissionRequestCreate, db: AsyncSession = Depends(get_db)):
    """Create a new permission request (typically called by agents)."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Create permission request
    db_request = PermissionRequest(
        project_id=project.id,
        feature_id=request.feature_id,
        agent_id=request.agent_id,
        permission_type=request.permission_type,
        permission_value=request.permission_value,
        status="pending",
    )
    db.add(db_request)
    await db.commit()
    await db.refresh(db_request)

    return PermissionRequestResponse.model_validate(db_request)

@router.post("/{name}/permission-requests/{request_id}/grant", response_model=PermissionRequestResponse)
async def grant_permission_request(name: str, request_id: int, db: AsyncSession = Depends(get_db)):
    """Grant a pending permission request."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission request
    result = await db.execute(
        select(PermissionRequest).where(and_(
            PermissionRequest.id == request_id,
            PermissionRequest.project_id == project.id
        ))
    )
    request = result.scalar_one_or_none()

    if not request:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission request {request_id} not found"
        )

    if request.status != "pending":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Permission request is already {request.status}"
        )

    # Update request status
    request.status = "granted"
    request.resolved_at = datetime.utcnow()

    # Create the actual permission
    db_permission = Permission(
        project_id=project.id,
        permission_type=request.permission_type,
        permission_value=request.permission_value,
        granted=True,
    )
    db.add(db_permission)

    await db.commit()
    await db.refresh(request)

    return PermissionRequestResponse.model_validate(request)

@router.post("/{name}/permission-requests/{request_id}/deny", response_model=PermissionRequestResponse)
async def deny_permission_request(name: str, request_id: int, db: AsyncSession = Depends(get_db)):
    """Deny a pending permission request."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission request
    result = await db.execute(
        select(PermissionRequest).where(and_(
            PermissionRequest.id == request_id,
            PermissionRequest.project_id == project.id
        ))
    )
    request = result.scalar_one_or_none()

    if not request:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission request {request_id} not found"
        )

    if request.status != "pending":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Permission request is already {request.status}"
        )

    # Update request status
    request.status = "denied"
    request.resolved_at = datetime.utcnow()

    await db.commit()
    await db.refresh(request)

    return PermissionRequestResponse.model_validate(request)

+    """Schema for creating a permission request."""

+    agent_id: str = Field(..., min_length=1, max_length=1)  # "A" or "B"

+    permission_type: str = Field(..., min_length=1, max_length=50)

+    permission_value: str = Field(..., min_length=1, max_length=500)

+async def create_permission_request(name: str, request: PermissionRequestCreate, db: AsyncSession = Depends(get_db)):

+    """Create a new permission request (typically called by agents)."""

+    result = await db.execute(select(Project).where(Project.name == name))

+    project = result.scalar_one_or_none()

+            status_code=status.HTTP_404_NOT_FOUND,

+            detail=f"Project '{name}' not found"

+        permission_type=request.permission_type,

+        permission_value=request.permission_value,

+    return PermissionRequestResponse.model_validate(db_request)

"""
Permissions Router
==================

API endpoints for permission management within projects.
"""

from datetime import datetime
from typing import Optional, List

from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy import select, and_
from sqlalchemy.ext.asyncio import AsyncSession

from ..database import get_db
from ..models import Project, Permission, PermissionRequest

router = APIRouter(prefix="/api/projects", tags=["permissions"])

# ============================================================================
# Pydantic Schemas
# ============================================================================

class PermissionResponse(BaseModel):
    """Schema for permission response."""
    id: int
    project_id: int
    permission_type: str
    permission_value: str
    granted: bool
    created_at: datetime

    class Config:
        from_attributes = True

class PermissionListResponse(BaseModel):
    """Schema for permission list response."""
    permissions: List[PermissionResponse]
    count: int

class PermissionCreate(BaseModel):
    """Schema for creating a permission."""
    permission_type: str = Field(..., min_length=1, max_length=50)
    permission_value: str = Field(..., min_length=1, max_length=500)
    granted: bool = True

class PermissionUpdate(BaseModel):
    """Schema for updating a permission."""
    granted: Optional[bool] = None

class PermissionRequestResponse(BaseModel):
    """Schema for permission request response."""
    id: int
    project_id: int
    feature_id: Optional[int]
    agent_id: str
    permission_type: str
    permission_value: str
    status: str
    requested_at: datetime
    resolved_at: Optional[datetime]

    class Config:
        from_attributes = True

class PermissionRequestListResponse(BaseModel):
    """Schema for permission request list response."""
    requests: List[PermissionRequestResponse]
    count: int

# ============================================================================
# Permission Endpoints
# ============================================================================

@router.get("/{name}/permissions", response_model=PermissionListResponse)
async def list_permissions(name: str, db: AsyncSession = Depends(get_db)):
    """List all permissions for a project."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permissions
    result = await db.execute(
        select(Permission)
        .where(Permission.project_id == project.id)
        .order_by(Permission.created_at.desc())
    )
    permissions = result.scalars().all()

    return PermissionListResponse(
        permissions=[PermissionResponse.model_validate(p) for p in permissions],
        count=len(permissions)
    )

@router.post("/{name}/permissions", response_model=PermissionResponse, status_code=status.HTTP_201_CREATED)
async def create_permission(name: str, permission: PermissionCreate, db: AsyncSession = Depends(get_db)):
    """Create a new permission for a project."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Check if permission already exists
    result = await db.execute(
        select(Permission).where(and_(
            Permission.project_id == project.id,
            Permission.permission_type == permission.permission_type,
            Permission.permission_value == permission.permission_value
        ))
    )
    existing = result.scalar_one_or_none()
    if existing:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=f"Permission already exists"
        )

    # Create permission
    db_permission = Permission(
        project_id=project.id,
        permission_type=permission.permission_type,
        permission_value=permission.permission_value,
        granted=permission.granted,
    )
    db.add(db_permission)
    await db.commit()
    await db.refresh(db_permission)

    return PermissionResponse.model_validate(db_permission)

@router.get("/{name}/permissions/{permission_id}", response_model=PermissionResponse)
async def get_permission(name: str, permission_id: int, db: AsyncSession = Depends(get_db)):
    """Get a specific permission by ID."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission
    result = await db.execute(
        select(Permission).where(and_(
            Permission.id == permission_id,
            Permission.project_id == project.id
        ))
    )
    permission = result.scalar_one_or_none()

    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission {permission_id} not found in project '{name}'"
        )

    return PermissionResponse.model_validate(permission)

@router.put("/{name}/permissions/{permission_id}", response_model=PermissionResponse)
async def update_permission(name: str, permission_id: int, permission_update: PermissionUpdate, db: AsyncSession = Depends(get_db)):
    """Update a permission."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission
    result = await db.execute(
        select(Permission).where(and_(
            Permission.id == permission_id,
            Permission.project_id == project.id
        ))
    )
    permission = result.scalar_one_or_none()

    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission {permission_id} not found in project '{name}'"
        )

    # Update granted status
    if permission_update.granted is not None:
        permission.granted = permission_update.granted

    await db.commit()
    await db.refresh(permission)

    return PermissionResponse.model_validate(permission)

@router.delete("/{name}/permissions/{permission_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_permission(name: str, permission_id: int, db: AsyncSession = Depends(get_db)):
    """Delete a permission."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission
    result = await db.execute(
        select(Permission).where(and_(
            Permission.id == permission_id,
            Permission.project_id == project.id
        ))
    )
    permission = result.scalar_one_or_none()

    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission {permission_id} not found in project '{name}'"
        )

    await db.delete(permission)
    await db.commit()

# ============================================================================
# Permission Request Endpoints
# ============================================================================

@router.get("/{name}/permission-requests", response_model=PermissionRequestListResponse)
async def list_permission_requests(
    name: str,
    status_filter: Optional[str] = None,
    db: AsyncSession = Depends(get_db)
):
    """List permission requests for a project."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Build query
    query = select(PermissionRequest).where(PermissionRequest.project_id == project.id)

    if status_filter:
        query = query.where(PermissionRequest.status == status_filter)

    query = query.order_by(PermissionRequest.requested_at.desc())

    result = await db.execute(query)
    requests = result.scalars().all()

    return PermissionRequestListResponse(
        requests=[PermissionRequestResponse.model_validate(r) for r in requests],
        count=len(requests)
    )

@router.post("/{name}/permission-requests/{request_id}/grant", response_model=PermissionRequestResponse)
async def grant_permission_request(name: str, request_id: int, db: AsyncSession = Depends(get_db)):
    """Grant a pending permission request."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission request
    result = await db.execute(
        select(PermissionRequest).where(and_(
            PermissionRequest.id == request_id,
            PermissionRequest.project_id == project.id
        ))
    )
    request = result.scalar_one_or_none()

    if not request:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission request {request_id} not found"
        )

    if request.status != "pending":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Permission request is already {request.status}"
        )

    # Update request status
    request.status = "granted"
    request.resolved_at = datetime.utcnow()

    # Create the actual permission
    db_permission = Permission(
        project_id=project.id,
        permission_type=request.permission_type,
        permission_value=request.permission_value,
        granted=True,
    )
    db.add(db_permission)

    await db.commit()
    await db.refresh(request)

    return PermissionRequestResponse.model_validate(request)

@router.post("/{name}/permission-requests/{request_id}/deny", response_model=PermissionRequestResponse)
async def deny_permission_request(name: str, request_id: int, db: AsyncSession = Depends(get_db)):
    """Deny a pending permission request."""
    # Verify project exists
    result = await db.execute(select(Project).where(Project.name == name))
    project = result.scalar_one_or_none()

    if not project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Project '{name}' not found"
        )

    # Get permission request
    result = await db.execute(
        select(PermissionRequest).where(and_(
            PermissionRequest.id == request_id,
            PermissionRequest.project_id == project.id
        ))
    )
    request = result.scalar_one_or_none()

    if not request:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Permission request {request_id} not found"
        )

    if request.status != "pending":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Permission request is already {request.status}"
        )

    # Update request status
    request.status = "denied"
    request.resolved_at = datetime.utcnow()

    await db.commit()
    await db.refresh(request)

    return PermissionRequestResponse.model_validate(request)


The file has been successfully updated. Let me verify the changes by checking the key sections.


79:class PermissionRequestCreate(BaseModel):
80-    """Schema for creating a permission request."""
81-    agent_id: str = Field(..., min_length=1, max_length=1)  # "A" or "B"
82-    permission_type: str = Field(..., min_length=1, max_length=50)
83-    permission_value: str = Field(..., min_length=1, max_length=500)
84-    feature_id: Optional[int] = None


300:async def create_permission_request(name: str, request: PermissionRequestCreate, db: AsyncSession = Depends(get_db)):
301-    """Create a new permission request (typically called by agents)."""
302-    # Verify project exists
303-    result = await db.execute(select(Project).where(Project.name == name))
304-    project = result.scalar_one_or_none()
305-
306-    if not project:
307-        raise HTTPException(
308-            status_code=status.HTTP_404_NOT_FOUND,
309-            detail=f"Project '{name}' not found"
310-        )
311-
312-    # Create permission request
313-    db_request = PermissionRequest(
314-        project_id=project.id,
315-        feature_id=request.feature_id,
316-        agent_id=request.agent_id,
317-        permission_type=request.permission_type,
318-        permission_value=request.permission_value,
319-        status="pending",
320-    )
321-    db.add(db_request)
322-    await db.commit()
323-    await db.refresh(db_request)
324-
325-    return PermissionRequestResponse.model_validate(db_request)


The file has been successfully updated with both changes:

1. **New schema class `PermissionRequestCreate`** (lines 79-84): Added after `PermissionRequestListResponse` with fields:
   - `agent_id`: string with min/max length of 1 (for "A" or "B")
   - `permission_type`: string with min/max length validation
   - `permission_value`: string with min/max length validation
   - `feature_id`: optional integer

2. **New endpoint `create_permission_request`** (lines 299-325): Added as a POST endpoint at `/{name}/permission-requests` that:
   - Returns `PermissionRequestResponse` with status code 201 (CREATED)
   - Verifies the project exists
   - Creates a new `PermissionRequest` record with status "pending"
   - Returns the newly created permission request

The changes are located at:
- **File**: `C:/Users/MikeSwanson/claude-projects/Autocode-remix/Autocode-fork/backend/app/routers/permissions.py`
- **Schema class**: Lines 79-84
- **Endpoint**: Lines 299-325