Files
state-hub/api/routers/domains.py
tegwick fcd0f06536 feat(state-hub): implement v0.5 — dynamic domains & multi-repo
Replaces the hardcoded 6-domain PostgreSQL ENUM with a first-class
`domains` DB table, and adds a `managed_repos` table for multi-repo
support per domain.

P1 — Domain as a DB entity:
- Migration b1c2d3e4f5a6: creates `domains` table, migrates topics.domain
  ENUM column to domain_id FK, drops the domain ENUM type
- Domain ORM model (api/models/domain.py) + Pydantic schemas
- Domain API router: GET/POST /domains/, GET/PATCH /domains/{slug}/,
  rename and archive endpoints with EP/TD cascade on rename
- Topic model updated: domain_id FK + @property domain_slug for
  backwards-compatible JSON serialization (field renamed domain → domain_slug)
- TopicCreate/TopicRead updated; seed.py rewritten to use FK lookup

P2 — Multi-repo support:
- ManagedRepo ORM model (api/models/managed_repo.py) + schemas
- Repo API router: GET/POST /repos/, GET/PATCH /repos/{slug}/, archive
- Makefile: add-domain, rename-domain, add-repo, list-repos targets
- register_project.sh: verify domain via /domains/ API + POST /repos/

P3 — MCP tools & live validation:
- 6 new MCP tools: list_domains, create_domain, rename_domain,
  archive_domain, list_domain_repos, register_repo
- EP/TD routers: replace hardcoded VALID_DOMAINS set with per-request
  DB lookup — returns 422 with list of valid slugs on unknown domain
- State summary: adds domains: list[DomainSummary] (slug, name,
  repo_count, active_workstream_count, ep_count, td_count)
- TOOLS.md updated with domain management section

P4 — Dashboard:
- New domains.md page with KPI row + domain cards + repo lists
- domains.json.py + repos.json.py data loaders
- Domains page added to observablehq.config.js nav
- workstreams.md, extensions.md, techdept.md: domain_slug fix +
  dynamic domain list loaded from /domains/ API (no longer hardcoded)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-28 15:20:15 +01:00

179 lines
5.9 KiB
Python

import uuid
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from api.database import get_session
from api.models.domain import Domain
from api.models.extension_point import ExtensionPoint
from api.models.managed_repo import ManagedRepo
from api.models.technical_debt import TechnicalDebt
from api.models.topic import Topic
from api.models.workstream import Workstream, WorkstreamStatus
from api.schemas.domain import DomainCreate, DomainDetail, DomainRead, DomainRename, DomainUpdate, RepoStub
router = APIRouter(prefix="/domains", tags=["domains"])
@router.get("/", response_model=list[DomainRead])
async def list_domains(
status: str | None = Query(None, description="active | archived | all"),
session: AsyncSession = Depends(get_session),
) -> list[Domain]:
q = select(Domain).order_by(Domain.name)
if status and status != "all":
q = q.where(Domain.status == status)
elif status is None:
q = q.where(Domain.status == "active")
result = await session.execute(q)
return list(result.scalars().all())
@router.post("/", response_model=DomainRead, status_code=status.HTTP_201_CREATED)
async def create_domain(
body: DomainCreate,
session: AsyncSession = Depends(get_session),
) -> Domain:
existing = await session.execute(select(Domain).where(Domain.slug == body.slug))
if existing.scalar_one_or_none():
raise HTTPException(status_code=409, detail=f"Domain slug '{body.slug}' already exists")
domain = Domain(slug=body.slug, name=body.name, description=body.description)
session.add(domain)
await session.commit()
await session.refresh(domain)
return domain
@router.get("/{slug}/", response_model=DomainDetail)
async def get_domain(
slug: str,
session: AsyncSession = Depends(get_session),
) -> DomainDetail:
domain = await _get_domain_by_slug(slug, session)
# Count topics
topic_count_row = await session.execute(
select(func.count()).select_from(Topic).where(Topic.domain_id == domain.id)
)
topic_count = topic_count_row.scalar_one()
# Count active workstreams (via topics)
topic_ids_row = await session.execute(
select(Topic.id).where(Topic.domain_id == domain.id)
)
topic_ids = [r[0] for r in topic_ids_row.all()]
ws_count = 0
if topic_ids:
ws_count_row = await session.execute(
select(func.count()).select_from(Workstream)
.where(Workstream.topic_id.in_(topic_ids))
.where(Workstream.status == WorkstreamStatus.active)
)
ws_count = ws_count_row.scalar_one()
# Count EPs and TDs (domain is a string column there)
ep_count_row = await session.execute(
select(func.count()).select_from(ExtensionPoint)
.where(ExtensionPoint.domain == slug)
)
ep_count = ep_count_row.scalar_one()
td_count_row = await session.execute(
select(func.count()).select_from(TechnicalDebt)
.where(TechnicalDebt.domain == slug)
)
td_count = td_count_row.scalar_one()
# Repos
repos_row = await session.execute(
select(ManagedRepo).where(ManagedRepo.domain_id == domain.id)
.where(ManagedRepo.status == "active")
.order_by(ManagedRepo.name)
)
repos = list(repos_row.scalars().all())
return DomainDetail(
id=domain.id,
slug=domain.slug,
name=domain.name,
description=domain.description,
status=domain.status,
created_at=domain.created_at,
updated_at=domain.updated_at,
topic_count=topic_count,
workstream_count=ws_count,
ep_count=ep_count,
td_count=td_count,
repos=[RepoStub.model_validate(r) for r in repos],
)
@router.patch("/{slug}/rename", response_model=DomainRead)
async def rename_domain(
slug: str,
body: DomainRename,
session: AsyncSession = Depends(get_session),
) -> Domain:
domain = await _get_domain_by_slug(slug, session)
if body.new_slug != slug:
conflict = await session.execute(select(Domain).where(Domain.slug == body.new_slug))
if conflict.scalar_one_or_none():
raise HTTPException(status_code=409, detail=f"Slug '{body.new_slug}' already taken")
old_slug = domain.slug
domain.slug = body.new_slug
domain.name = body.new_name
# Cascade slug rename to EP/TD string columns
if old_slug != body.new_slug:
await session.execute(
ExtensionPoint.__table__.update()
.where(ExtensionPoint.domain == old_slug)
.values(domain=body.new_slug)
)
await session.execute(
TechnicalDebt.__table__.update()
.where(TechnicalDebt.domain == old_slug)
.values(domain=body.new_slug)
)
await session.commit()
await session.refresh(domain)
return domain
@router.patch("/{slug}/archive", response_model=DomainRead)
async def archive_domain(
slug: str,
session: AsyncSession = Depends(get_session),
) -> Domain:
domain = await _get_domain_by_slug(slug, session)
# Reject if any active topics exist for this domain
active_topics = await session.execute(
select(func.count()).select_from(Topic)
.where(Topic.domain_id == domain.id)
.where(Topic.status == "active")
)
if active_topics.scalar_one() > 0:
raise HTTPException(
status_code=409,
detail="Cannot archive domain with active topics. Archive or reassign topics first.",
)
domain.status = "archived"
await session.commit()
await session.refresh(domain)
return domain
async def _get_domain_by_slug(slug: str, session: AsyncSession) -> Domain:
result = await session.execute(select(Domain).where(Domain.slug == slug))
domain = result.scalar_one_or_none()
if domain is None:
raise HTTPException(status_code=404, detail=f"Domain '{slug}' not found")
return domain