Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
33b9688
fix(llc): batch subtree project moves, guard backlog loads by request…
mrveiss Nov 7, 2026
d4d6acb
feat(llc): hierarchy refusals are 422, and the rule table and violati…
mrveiss Nov 7, 2026
c39b62e
fix(llc): hierarchy report - 401 is not 'not admin', company change c…
mrveiss Nov 7, 2026
d9339cb
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
10d1427
fix(llc): article-neutral reason text; tests for cycle shapes, Postgr…
mrveiss Nov 7, 2026
8ad25ba
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
456a09b
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
1c8a9d5
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
9bb02a5
Merge origin/main into issue-20936 (#20936)
mrveiss Nov 8, 2026
5966930
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
90f870d
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
bc29652
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
499c67f
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
906714d
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
32a6f17
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
b4613af
Merge remote-tracking branch 'origin/main' into issue-20936
mrveiss Nov 9, 2026
b6653ff
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
21e6326
Merge remote-tracking branch 'origin/issue-20936' into issue-20936
mrveiss Nov 9, 2026
63d0193
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
96cbfb4
Merge main into issue-20936 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions autobot-backend/llc/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
from .templates import router as templates_router
from .tools import router as tools_router
from .work_item_comments import router as work_item_comments_router
from .work_item_hierarchy_routes import router as work_item_hierarchy_router
from .work_item_relations_routes import router as work_item_relations_router
from .work_items import router as work_items_router
from .workflows import router as workflows_router
Expand Down Expand Up @@ -79,6 +80,8 @@
router.include_router(roles_router)
router.include_router(tools_router)
router.include_router(sprints_router)
# Before work_items_router: its /{work_item_id} would swallow the literal hierarchy-* paths (#20936).
router.include_router(work_item_hierarchy_router)
router.include_router(work_items_router)
router.include_router(work_item_comments_router)
router.include_router(work_item_relations_router)
Expand Down
11 changes: 11 additions & 0 deletions autobot-backend/llc/api/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
from autobot_shared.auth.interactive_principal import is_interactive_human
from autobot_shared.logging_manager import get_logger

from ..services.work_item_hierarchy import HierarchyViolation

logger = get_logger(__name__)


Expand Down Expand Up @@ -244,3 +246,12 @@ def refused_transition(exc: Exception) -> HTTPException:
"""
logger.info("Rejected illegal work-item transition: %s", exc)
return HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))


def write_refusal(exc: ValueError) -> HTTPException:
"""A refused work-item create/update: a hierarchy-rule breach (incl. ``ProjectRequired``) is 422 (#20936).

Any other ``ValueError`` (e.g. an unknown approval category, GH#11206) stays 400.
"""
code = status.HTTP_422_UNPROCESSABLE_ENTITY if isinstance(exc, HierarchyViolation) else status.HTTP_400_BAD_REQUEST
return HTTPException(status_code=code, detail=str(exc))
104 changes: 104 additions & 0 deletions autobot-backend/llc/api/work_item_hierarchy_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""Work-item hierarchy rules and the read-only violation report (#20936, #18978).

``GET /work-items/hierarchy-rules`` serves the parent-type rule table; ``GET /work-items/hierarchy-violations``
returns the rows that already break it (company owners/admins and platform admins only). Neither writes.

This router is included BEFORE ``work_items.router`` (see ``api/__init__.py``): its literal paths would otherwise
be swallowed by that router's ``/{work_item_id}`` capture.
"""

import uuid
from typing import List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession

from api.user_management.dependencies import get_current_user, require_org_context
from autobot_shared.logging_manager import get_logger
from llc.deps import assert_company_access, get_session
from user_management.services import TenantContext

from ..services.authz import NotAuthorisedError, require_company_admin_unless_platform
from ..services.work_item_hierarchy import (
ALLOWED_PARENT_TYPES,
PROJECT_REQUIRED_TYPES,
find_hierarchy_violations,
)

logger = get_logger(__name__)
router = APIRouter(prefix="/work-items", tags=["llc-work-items"])


class HierarchyRule(BaseModel):
type: str
allowed_parent_types: List[str]
project_required: bool


class HierarchyRulesResponse(BaseModel):
rules: List[HierarchyRule]


class HierarchyViolationRow(BaseModel):
id: str
identifier: str
code: str # stable: the GUI renders its own text for it
reason: str # English, for logs and API consumers
type: str
parent_type: Optional[str] = None


class HierarchyViolationsResponse(BaseModel):
violations: List[HierarchyViolationRow]
count: int
truncated: bool = False # more rows break the rules than the report's limit returns


def hierarchy_rules() -> HierarchyRulesResponse:
"""The rule table as data, straight from the constants the writes are checked against."""
return HierarchyRulesResponse(
rules=[
HierarchyRule(
type=kind.value,
allowed_parent_types=sorted(p.value for p in parents),
project_required=kind in PROJECT_REQUIRED_TYPES,
)
for kind, parents in ALLOWED_PARENT_TYPES.items()
]
)


@router.get("/hierarchy-rules", response_model=HierarchyRulesResponse)
async def get_hierarchy_rules(
company_id: str = Query(...),
_current_user: dict = Depends(get_current_user),
ctx: TenantContext = Depends(require_org_context),
) -> HierarchyRulesResponse:
assert_company_access(ctx, company_id)
return hierarchy_rules()


@router.get("/hierarchy-violations", response_model=HierarchyViolationsResponse)
async def get_hierarchy_violations(
company_id: str = Query(...),
session: AsyncSession = Depends(get_session),
_current_user: dict = Depends(get_current_user),
ctx: TenantContext = Depends(require_org_context),
) -> HierarchyViolationsResponse:
assert_company_access(ctx, company_id)
try:
await require_company_admin_unless_platform(
session, uuid.UUID(str(company_id)), ctx.user_id, platform_admin=ctx.is_platform_admin
)
except NotAuthorisedError as exc:
logger.warning("Refused hierarchy-violations report for company %s: %s", company_id, exc)
raise HTTPException(status_code=403, detail="Only a company owner or admin may read the violation report")
rows, truncated = await find_hierarchy_violations(session, company_id)
return HierarchyViolationsResponse(
violations=[HierarchyViolationRow(**r) for r in rows], count=len(rows), truncated=truncated
)
10 changes: 5 additions & 5 deletions autobot-backend/llc/api/work_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
resolve_actor_role,
)
from ._common import actor_id as verified_user_id
from ._common import own_task_actor, refused_transition
from ._common import own_task_actor, refused_transition, write_refusal
from ._handoff_identity import handing_off_agent, member_reviewer
from .activity import ActivityLogEntry, ActivityLogResponse
from .github_webhooks import validate_github_pr_url
Expand Down Expand Up @@ -410,8 +410,8 @@ async def create_work_item(
labels=body.labels,
requires_approval_before=body.requires_approval_before,
)
except ValueError as exc: # e.g. unknown approval category (GH#11206)
raise HTTPException(status_code=400, detail=str(exc))
except ValueError as exc: # hierarchy breach -> 422; else 400, e.g. unknown approval category (GH#11206)
raise write_refusal(exc)
await session.commit()
return await _item_to_dict(item, session)

Expand Down Expand Up @@ -498,8 +498,8 @@ async def update_work_item(
fields = {k: v for k, v in body.model_dump(exclude_none=True).items()}
try:
item = await _service().update(session, work_item_id, **fields)
except ValueError as exc: # e.g. unknown approval category (GH#11206)
raise HTTPException(status_code=400, detail=str(exc))
except ValueError as exc: # hierarchy breach -> 422; else 400, e.g. unknown approval category (GH#11206)
raise write_refusal(exc)
if item is None:
raise HTTPException(status_code=404, detail="Work item not found")
await session.commit()
Expand Down
143 changes: 108 additions & 35 deletions autobot-backend/llc/services/work_item_hierarchy.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@
import uuid
from typing import Awaitable, Callable, Dict, FrozenSet, List, Optional, Tuple

from sqlalchemy import func, select, update
from sqlalchemy import and_, func, literal, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased

from autobot_shared.env_utils import env_int_clamped

from ..models.enums import WorkItemType
from ..models.sprint import LLCProject
Expand Down Expand Up @@ -43,6 +46,19 @@
# legacy rows, and the bound is what makes the walk terminate on cyclic data.
MAX_HIERARCHY_DEPTH = 32

# Violations one report returns; the query stops at this many (+1, to know there were more) in SQL (#20936).
HIERARCHY_VIOLATIONS_LIMIT = env_int_clamped("AUTOBOT_LLC_HIERARCHY_VIOLATIONS_LIMIT", 500, min_v=1, max_v=5000)

# Stable violation codes: the report's contract. The GUI renders each through an i18n key.
CYCLE = "parent_cycle"
PARENT_MISSING = "parent_missing"
PARENT_TYPE = "parent_type_not_allowed"
PROJECT_MISMATCH = "project_mismatch"
PROJECT_REQUIRED = "project_required"

# Ids per ``UPDATE ... WHERE id IN (...)`` when a subtree moves; well under the 32,767 bind-parameter limit.
SUBTREE_UPDATE_BATCH = 10_000


# ``WorkItemService.get`` -- the one place a work item is read by id, so it stays the one place to patch.
ItemGetter = Callable[..., Awaitable[Optional[LLCWorkItem]]]
Expand Down Expand Up @@ -203,13 +219,18 @@ async def move_subtree_to_project(
) -> int:
"""Set ``project_id`` on every descendant of *root_id* in *company_id*, at any depth. Returns the count.

The whole subtree is read before anything is written, so a move can never stop half way down.
The whole subtree is read before anything is written, so a move can never stop half way down. The
writes go out in batches of ``SUBTREE_UPDATE_BATCH`` ids in the caller's transaction: one ``IN (...)``
over more ids than the driver's bind-parameter limit (32,767) would fail the whole move.
"""
descendants = await _descendant_ids(session, root_id, company_id)
if descendants:
for start in range(0, len(descendants), SUBTREE_UPDATE_BATCH):
await session.execute(
update(LLCWorkItem)
.where(LLCWorkItem.id.in_(descendants), LLCWorkItem.company_id == company_id)
.where(
LLCWorkItem.id.in_(descendants[start : start + SUBTREE_UPDATE_BATCH]),
LLCWorkItem.company_id == company_id,
)
.values(project_id=project_id)
)
return len(descendants)
Expand Down Expand Up @@ -243,46 +264,98 @@ async def reparent(
return new_parent


async def find_hierarchy_violations(session: AsyncSession, company_id: str) -> List[Dict[str, str]]:
"""Read-only report of existing rows that break the rules (#17038: never rewritten)."""
rows = (
(await session.execute(select(LLCWorkItem).where(LLCWorkItem.company_id == uuid.UUID(str(company_id)))))
.scalars()
.all()
def _cycle_members(company: uuid.UUID):
"""Recursive CTE: ids whose parent chain returns to them, or runs deeper than ``MAX_HIERARCHY_DEPTH``."""
parent = aliased(LLCWorkItem)
base = (
select(LLCWorkItem.id.label("start"), parent.id.label("node"), literal(1).label("depth"))
.join(parent, parent.id == LLCWorkItem.parent_id)
.where(LLCWorkItem.company_id == company, parent.company_id == company)
.cte("hierarchy_walk", recursive=True)
)
by_id = {r.id: r for r in rows}
found = []
for row in rows:
reason = _row_violation(row, by_id.get(row.parent_id), by_id)
if reason:
found.append({"id": str(row.id), "identifier": row.identifier, "reason": reason})
return found
cur, nxt = aliased(LLCWorkItem), aliased(LLCWorkItem)
walk = base.union_all(
select(base.c.start, nxt.id, base.c.depth + 1)
.join(cur, cur.id == base.c.node)
.join(nxt, nxt.id == cur.parent_id)
.where(base.c.depth < MAX_HIERARCHY_DEPTH, base.c.node != base.c.start, nxt.company_id == company)
)
looped = or_(walk.c.node == walk.c.start, walk.c.depth >= MAX_HIERARCHY_DEPTH)
return select(walk.c.start).where(looped)


def _violation_filter(parent, cycle_ids):
"""SQL form of ``_row_violation``: a row matches iff it breaks at least one rule."""
bad_type = [
and_(LLCWorkItem.type == kind, parent.type.not_in(sorted(allowed, key=lambda t: t.value)))
for kind, allowed in ALLOWED_PARENT_TYPES.items()
]
return or_(
LLCWorkItem.id.in_(cycle_ids),
and_(LLCWorkItem.parent_id.is_not(None), parent.id.is_(None)),
and_(parent.id.is_not(None), or_(*bad_type)),
and_(
parent.id.is_not(None),
parent.project_id.is_not(None),
LLCWorkItem.project_id.is_distinct_from(parent.project_id),
),
and_(
LLCWorkItem.type.in_(sorted(PROJECT_REQUIRED_TYPES, key=lambda t: t.value)),
LLCWorkItem.project_id.is_(None),
),
)


def violations_statement(company: uuid.UUID, limit: int):
"""The one SELECT behind the report: rows breaking a rule, their parent, and whether they sit in a cycle."""
parent = aliased(LLCWorkItem)
cycle_ids = _cycle_members(company)
return (
select(LLCWorkItem, parent, LLCWorkItem.id.in_(cycle_ids))
.outerjoin(parent, and_(parent.id == LLCWorkItem.parent_id, parent.company_id == company))
.where(LLCWorkItem.company_id == company, _violation_filter(parent, cycle_ids))
.order_by(LLCWorkItem.identifier, LLCWorkItem.id)
.limit(limit + 1)
)


async def find_hierarchy_violations(
session: AsyncSession, company_id: str, limit: int = HIERARCHY_VIOLATIONS_LIMIT
) -> Tuple[List[Dict[str, Optional[str]]], bool]:
"""Read-only report of existing rows that break the rules (#17038: never rewritten).

Returns ``(rows, truncated)``. The rules are applied and the limit taken in SQL, so at most
``limit + 1`` rows leave the database; ``truncated`` says there were more than *limit*.
"""
stmt = violations_statement(uuid.UUID(str(company_id)), limit)
fetched = (await session.execute(stmt)).all()
return [_report_row(*r) for r in fetched[:limit]], len(fetched) > limit


def _in_cycle(row: LLCWorkItem, by_id: Dict[uuid.UUID, LLCWorkItem]) -> bool:
node = by_id.get(row.parent_id)
for _ in range(MAX_HIERARCHY_DEPTH):
if node is None:
return False
if node.id == row.id:
return True
node = by_id.get(node.parent_id)
return True
def _report_row(row: LLCWorkItem, parent: Optional[LLCWorkItem], in_cycle: bool) -> Dict[str, Optional[str]]:
code, reason = _row_violation(row, parent, in_cycle)
return {
"id": str(row.id),
"identifier": row.identifier,
"code": code,
"reason": reason,
"type": _type_of(row.type).value,
"parent_type": _type_of(parent.type).value if parent is not None else None,
}


def _row_violation(row: LLCWorkItem, parent: Optional[LLCWorkItem], by_id=None) -> Optional[str]:
def _row_violation(row: LLCWorkItem, parent: Optional[LLCWorkItem], in_cycle: bool) -> Tuple[str, str]:
"""The first rule *row* breaks, as ``(stable code, English text for logs)``. Mirrors ``_violation_filter``."""
kind = _type_of(row.type)
if by_id is not None and _in_cycle(row, by_id):
return "parent chain is cyclic or deeper than the allowed depth"
if in_cycle:
return CYCLE, "parent chain is cyclic or deeper than the allowed depth"
if row.parent_id is not None and parent is None:
return "parent is missing or in another company"
return PARENT_MISSING, "parent is missing or in another company"
if parent is not None and _type_of(parent.type) not in ALLOWED_PARENT_TYPES[kind]:
return f"a {kind.value} cannot sit under a {_type_of(parent.type).value}"
return PARENT_TYPE, f"a {kind.value} cannot sit under a {_type_of(parent.type).value}"
if parent is not None and parent.project_id and row.project_id != parent.project_id:
return "project differs from the parent's"
if kind in PROJECT_REQUIRED_TYPES and row.project_id is None:
return f"a {kind.value} has no project_id"
return None
return PROJECT_MISMATCH, "project differs from the parent's"
return PROJECT_REQUIRED, f"a {kind.value} has no project_id"


async def count_items_without_project(session: AsyncSession) -> Dict[str, int]:
Expand Down
Loading