generated from coulomb/repo-seed
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>
This commit is contained in:
@@ -5,6 +5,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from api.database import engine
|
||||
from api.routers import decisions, extension_points, progress, state, tasks, technical_debt, topics, workstreams, workstream_dependencies
|
||||
from api.routers import domains, repos
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -16,7 +17,7 @@ async def lifespan(app: FastAPI):
|
||||
app = FastAPI(
|
||||
title="Custodian State Hub",
|
||||
description="Local-first state API for the Custodian agent system.",
|
||||
version="0.1.0",
|
||||
version="0.5.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@@ -27,6 +28,8 @@ app.add_middleware(
|
||||
allow_headers=["Content-Type"],
|
||||
)
|
||||
|
||||
app.include_router(domains.router)
|
||||
app.include_router(repos.router)
|
||||
app.include_router(topics.router)
|
||||
app.include_router(workstreams.router)
|
||||
app.include_router(workstream_dependencies.router)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from api.models.base import Base
|
||||
from api.models.topic import Topic, TopicStatus, Domain
|
||||
from api.models.domain import Domain
|
||||
from api.models.topic import Topic, TopicStatus
|
||||
from api.models.workstream import Workstream, WorkstreamStatus
|
||||
from api.models.workstream_dependency import WorkstreamDependency
|
||||
from api.models.task import Task, TaskStatus, TaskPriority
|
||||
@@ -7,10 +8,12 @@ from api.models.decision import Decision, DecisionType, DecisionStatus
|
||||
from api.models.progress_event import ProgressEvent
|
||||
from api.models.extension_point import ExtensionPoint, EPStatus
|
||||
from api.models.technical_debt import TechnicalDebt, TDStatus
|
||||
from api.models.managed_repo import ManagedRepo
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"Topic", "TopicStatus", "Domain",
|
||||
"Domain",
|
||||
"Topic", "TopicStatus",
|
||||
"Workstream", "WorkstreamStatus",
|
||||
"WorkstreamDependency",
|
||||
"Task", "TaskStatus", "TaskPriority",
|
||||
@@ -18,4 +21,5 @@ __all__ = [
|
||||
"ProgressEvent",
|
||||
"ExtensionPoint", "EPStatus",
|
||||
"TechnicalDebt", "TDStatus",
|
||||
"ManagedRepo",
|
||||
]
|
||||
|
||||
26
api/models/domain.py
Normal file
26
api/models/domain.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import String, Text
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from api.models.base import Base, TimestampMixin, new_uuid
|
||||
|
||||
|
||||
class Domain(Base, TimestampMixin):
|
||||
__tablename__ = "domains"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=new_uuid
|
||||
)
|
||||
slug: Mapped[str] = mapped_column(String(50), unique=True, nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="active")
|
||||
|
||||
topics: Mapped[list["Topic"]] = relationship( # noqa: F821
|
||||
"Topic", back_populates="domain", lazy="selectin"
|
||||
)
|
||||
repos: Mapped[list["ManagedRepo"]] = relationship( # noqa: F821
|
||||
"ManagedRepo", back_populates="domain", lazy="selectin"
|
||||
)
|
||||
31
api/models/managed_repo.py
Normal file
31
api/models/managed_repo.py
Normal file
@@ -0,0 +1,31 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import ForeignKey, String, Text
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from api.models.base import Base, TimestampMixin, new_uuid
|
||||
|
||||
|
||||
class ManagedRepo(Base, TimestampMixin):
|
||||
__tablename__ = "managed_repos"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=new_uuid
|
||||
)
|
||||
domain_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("domains.id", ondelete="RESTRICT"), nullable=False, index=True
|
||||
)
|
||||
slug: Mapped[str] = mapped_column(String(100), unique=True, nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
local_path: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
remote_url: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="active")
|
||||
topic_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("topics.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
|
||||
domain: Mapped["Domain"] = relationship( # noqa: F821
|
||||
"Domain", back_populates="repos", lazy="selectin"
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
import enum
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Enum, String, Text
|
||||
from sqlalchemy import Enum, ForeignKey, String, Text
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
@@ -14,15 +14,6 @@ class TopicStatus(str, enum.Enum):
|
||||
archived = "archived"
|
||||
|
||||
|
||||
class Domain(str, enum.Enum):
|
||||
custodian = "custodian"
|
||||
railiance = "railiance"
|
||||
markitect = "markitect"
|
||||
coulomb_social = "coulomb_social"
|
||||
personhood = "personhood"
|
||||
foerster_capabilities = "foerster_capabilities"
|
||||
|
||||
|
||||
class Topic(Base, TimestampMixin):
|
||||
__tablename__ = "topics"
|
||||
|
||||
@@ -32,11 +23,19 @@ class Topic(Base, TimestampMixin):
|
||||
slug: Mapped[str] = mapped_column(String(100), unique=True, nullable=False, index=True)
|
||||
title: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
domain: Mapped[Domain] = mapped_column(Enum(Domain), nullable=False)
|
||||
domain_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("domains.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
status: Mapped[TopicStatus] = mapped_column(
|
||||
Enum(TopicStatus), nullable=False, default=TopicStatus.active
|
||||
)
|
||||
|
||||
domain: Mapped["Domain"] = relationship( # noqa: F821
|
||||
"Domain", back_populates="topics", lazy="selectin"
|
||||
)
|
||||
workstreams: Mapped[list["Workstream"]] = relationship( # noqa: F821
|
||||
"Workstream", back_populates="topic", lazy="selectin"
|
||||
)
|
||||
@@ -46,3 +45,10 @@ class Topic(Base, TimestampMixin):
|
||||
progress_events: Mapped[list["ProgressEvent"]] = relationship( # noqa: F821
|
||||
"ProgressEvent", back_populates="topic", lazy="selectin"
|
||||
)
|
||||
|
||||
@property
|
||||
def domain_slug(self) -> str | None:
|
||||
"""Returns the domain slug string for serialization."""
|
||||
if self.domain is not None:
|
||||
return self.domain.slug
|
||||
return None
|
||||
|
||||
178
api/routers/domains.py
Normal file
178
api/routers/domains.py
Normal file
@@ -0,0 +1,178 @@
|
||||
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
|
||||
@@ -5,12 +5,19 @@ from sqlalchemy import 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 EPStatus, ExtensionPoint
|
||||
from api.schemas.extension_point import EPCreate, EPRead, EPUpdate
|
||||
|
||||
router = APIRouter(prefix="/extension-points", tags=["extension-points"])
|
||||
|
||||
|
||||
async def _get_valid_domain_slugs(session: AsyncSession) -> set[str]:
|
||||
"""Return the set of active domain slugs from the DB."""
|
||||
rows = await session.execute(select(Domain.slug).where(Domain.status == "active"))
|
||||
return {r[0] for r in rows.all()}
|
||||
|
||||
|
||||
@router.get("/", response_model=list[EPRead])
|
||||
async def list_eps(
|
||||
domain: str | None = None,
|
||||
@@ -35,6 +42,12 @@ async def create_ep(
|
||||
body: EPCreate,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> ExtensionPoint:
|
||||
valid_domains = await _get_valid_domain_slugs(session)
|
||||
if body.domain not in valid_domains:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail=f"Unknown domain '{body.domain}'. Valid domains: {sorted(valid_domains)}",
|
||||
)
|
||||
ep = ExtensionPoint(**body.model_dump())
|
||||
session.add(ep)
|
||||
await session.commit()
|
||||
|
||||
99
api/routers/repos.py
Normal file
99
api/routers/repos.py
Normal file
@@ -0,0 +1,99 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from api.database import get_session
|
||||
from api.models.domain import Domain
|
||||
from api.models.managed_repo import ManagedRepo
|
||||
from api.schemas.managed_repo import RepoCreate, RepoRead, RepoUpdate
|
||||
|
||||
router = APIRouter(prefix="/repos", tags=["repos"])
|
||||
|
||||
|
||||
@router.get("/", response_model=list[RepoRead])
|
||||
async def list_repos(
|
||||
domain: str | None = None,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> list[ManagedRepo]:
|
||||
q = select(ManagedRepo).order_by(ManagedRepo.name)
|
||||
if domain:
|
||||
domain_row = await session.execute(select(Domain).where(Domain.slug == domain))
|
||||
domain_obj = domain_row.scalar_one_or_none()
|
||||
if domain_obj is None:
|
||||
raise HTTPException(status_code=404, detail=f"Domain '{domain}' not found")
|
||||
q = q.where(ManagedRepo.domain_id == domain_obj.id)
|
||||
result = await session.execute(q)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
@router.post("/", response_model=RepoRead, status_code=status.HTTP_201_CREATED)
|
||||
async def register_repo(
|
||||
body: RepoCreate,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> ManagedRepo:
|
||||
domain_row = await session.execute(select(Domain).where(Domain.slug == body.domain_slug))
|
||||
domain_obj = domain_row.scalar_one_or_none()
|
||||
if domain_obj is None:
|
||||
raise HTTPException(status_code=404, detail=f"Domain '{body.domain_slug}' not found")
|
||||
|
||||
existing = await session.execute(select(ManagedRepo).where(ManagedRepo.slug == body.slug))
|
||||
if existing.scalar_one_or_none():
|
||||
raise HTTPException(status_code=409, detail=f"Repo slug '{body.slug}' already exists")
|
||||
|
||||
repo = ManagedRepo(
|
||||
domain_id=domain_obj.id,
|
||||
slug=body.slug,
|
||||
name=body.name,
|
||||
local_path=body.local_path,
|
||||
remote_url=body.remote_url,
|
||||
description=body.description,
|
||||
topic_id=body.topic_id,
|
||||
)
|
||||
session.add(repo)
|
||||
await session.commit()
|
||||
await session.refresh(repo)
|
||||
return repo
|
||||
|
||||
|
||||
@router.get("/{slug}/", response_model=RepoRead)
|
||||
async def get_repo(
|
||||
slug: str,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> ManagedRepo:
|
||||
return await _get_repo_by_slug(slug, session)
|
||||
|
||||
|
||||
@router.patch("/{slug}/", response_model=RepoRead)
|
||||
async def update_repo(
|
||||
slug: str,
|
||||
body: RepoUpdate,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> ManagedRepo:
|
||||
repo = await _get_repo_by_slug(slug, session)
|
||||
for field, value in body.model_dump(exclude_unset=True).items():
|
||||
setattr(repo, field, value)
|
||||
await session.commit()
|
||||
await session.refresh(repo)
|
||||
return repo
|
||||
|
||||
|
||||
@router.patch("/{slug}/archive", response_model=RepoRead)
|
||||
async def archive_repo(
|
||||
slug: str,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> ManagedRepo:
|
||||
repo = await _get_repo_by_slug(slug, session)
|
||||
repo.status = "archived"
|
||||
await session.commit()
|
||||
await session.refresh(repo)
|
||||
return repo
|
||||
|
||||
|
||||
async def _get_repo_by_slug(slug: str, session: AsyncSession) -> ManagedRepo:
|
||||
result = await session.execute(select(ManagedRepo).where(ManagedRepo.slug == slug))
|
||||
repo = result.scalar_one_or_none()
|
||||
if repo is None:
|
||||
raise HTTPException(status_code=404, detail=f"Repo '{slug}' not found")
|
||||
return repo
|
||||
@@ -7,12 +7,17 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from api.database import get_session, engine
|
||||
from api.models.decision import Decision, DecisionStatus, DecisionType
|
||||
from api.models.domain import Domain
|
||||
from api.models.extension_point import ExtensionPoint
|
||||
from api.models.managed_repo import ManagedRepo
|
||||
from api.models.progress_event import ProgressEvent
|
||||
from api.models.task import Task, TaskPriority, TaskStatus
|
||||
from api.models.technical_debt import TechnicalDebt
|
||||
from api.models.topic import Topic, TopicStatus
|
||||
from api.models.workstream import Workstream, WorkstreamStatus
|
||||
from api.models.workstream_dependency import WorkstreamDependency
|
||||
from api.schemas.decision import DecisionRead
|
||||
from api.schemas.domain import DomainSummary
|
||||
from api.schemas.progress_event import ProgressEventRead
|
||||
from api.schemas.state import (
|
||||
DecisionTotals,
|
||||
@@ -167,6 +172,9 @@ async def get_summary(session: AsyncSession = Depends(get_session)) -> StateSumm
|
||||
|
||||
next_steps = await _derive_next_steps(session)
|
||||
|
||||
# Domain summary stats
|
||||
domain_summaries = await _build_domain_summaries(session)
|
||||
|
||||
return StateSummary(
|
||||
generated_at=datetime.now(tz=timezone.utc),
|
||||
totals=totals,
|
||||
@@ -175,6 +183,7 @@ async def get_summary(session: AsyncSession = Depends(get_session)) -> StateSumm
|
||||
blocked_tasks=[TaskRead.model_validate(t) for t in blocked],
|
||||
recent_progress=[ProgressEventRead.model_validate(e) for e in recent],
|
||||
next_steps=next_steps,
|
||||
domains=domain_summaries,
|
||||
open_workstreams=[
|
||||
WorkstreamWithDeps(
|
||||
**WorkstreamRead.model_validate(w).model_dump(),
|
||||
@@ -191,6 +200,53 @@ async def get_summary(session: AsyncSession = Depends(get_session)) -> StateSumm
|
||||
)
|
||||
|
||||
|
||||
async def _build_domain_summaries(session: AsyncSession) -> list[DomainSummary]:
|
||||
"""Compute per-domain stats for the state summary."""
|
||||
domains_rows = await session.execute(
|
||||
select(Domain).where(Domain.status == "active").order_by(Domain.name)
|
||||
)
|
||||
domains = list(domains_rows.scalars().all())
|
||||
|
||||
# Repo counts per domain
|
||||
repo_counts = {r[0]: r[1] for r in await session.execute(
|
||||
select(ManagedRepo.domain_id, func.count())
|
||||
.where(ManagedRepo.status == "active")
|
||||
.group_by(ManagedRepo.domain_id)
|
||||
)}
|
||||
|
||||
# Active workstream counts per domain (join through topics)
|
||||
ws_per_domain = {}
|
||||
for domain_id, cnt in await session.execute(
|
||||
select(Topic.domain_id, func.count(Workstream.id))
|
||||
.join(Workstream, Workstream.topic_id == Topic.id)
|
||||
.where(Workstream.status == WorkstreamStatus.active)
|
||||
.group_by(Topic.domain_id)
|
||||
):
|
||||
ws_per_domain[domain_id] = cnt
|
||||
|
||||
# EP counts per domain slug
|
||||
ep_counts = {r[0]: r[1] for r in await session.execute(
|
||||
select(ExtensionPoint.domain, func.count()).group_by(ExtensionPoint.domain)
|
||||
)}
|
||||
|
||||
# TD counts per domain slug
|
||||
td_counts = {r[0]: r[1] for r in await session.execute(
|
||||
select(TechnicalDebt.domain, func.count()).group_by(TechnicalDebt.domain)
|
||||
)}
|
||||
|
||||
return [
|
||||
DomainSummary(
|
||||
slug=d.slug,
|
||||
name=d.name,
|
||||
repo_count=repo_counts.get(d.id, 0),
|
||||
active_workstream_count=ws_per_domain.get(d.id, 0),
|
||||
ep_count=ep_counts.get(d.slug, 0),
|
||||
td_count=td_counts.get(d.slug, 0),
|
||||
)
|
||||
for d in domains
|
||||
]
|
||||
|
||||
|
||||
_PRIORITY_RANK = {
|
||||
TaskPriority.critical: 0,
|
||||
TaskPriority.high: 1,
|
||||
@@ -231,10 +287,10 @@ async def _derive_next_steps(session: AsyncSession) -> list[NextStep]:
|
||||
if task.id in seen_task_ids:
|
||||
continue
|
||||
ws = await session.get(Workstream, decision.workstream_id)
|
||||
topic = await session.get(Topic, ws.topic_id) if ws else None
|
||||
domain_slug = await _get_domain_slug_for_workstream(ws, session)
|
||||
steps.append(NextStep(
|
||||
type="resolved_decision",
|
||||
domain=topic.domain if topic else None,
|
||||
domain=domain_slug,
|
||||
workstream_id=ws.id if ws else None,
|
||||
workstream_title=ws.title if ws else None,
|
||||
workstream_slug=ws.slug if ws else None,
|
||||
@@ -282,7 +338,7 @@ async def _derive_next_steps(session: AsyncSession) -> list[NextStep]:
|
||||
task = min(todo_tasks, key=lambda t: (_PRIORITY_RANK.get(t.priority, 99), t.created_at))
|
||||
if task.id in seen_task_ids:
|
||||
continue
|
||||
topic = await session.get(Topic, from_ws.topic_id)
|
||||
domain_slug = await _get_domain_slug_for_workstream(from_ws, session)
|
||||
blocker_slugs = ", ".join(
|
||||
(await session.get(Workstream, tid)).slug
|
||||
for tid in to_ws_ids
|
||||
@@ -290,7 +346,7 @@ async def _derive_next_steps(session: AsyncSession) -> list[NextStep]:
|
||||
)
|
||||
steps.append(NextStep(
|
||||
type="dependency_cleared",
|
||||
domain=topic.domain if topic else None,
|
||||
domain=domain_slug,
|
||||
workstream_id=from_ws.id,
|
||||
workstream_title=from_ws.title,
|
||||
workstream_slug=from_ws.slug,
|
||||
@@ -306,6 +362,17 @@ async def _derive_next_steps(session: AsyncSession) -> list[NextStep]:
|
||||
return steps
|
||||
|
||||
|
||||
async def _get_domain_slug_for_workstream(ws: Workstream | None, session: AsyncSession) -> str | None:
|
||||
"""Get the domain slug for a workstream via its topic."""
|
||||
if ws is None or ws.topic_id is None:
|
||||
return None
|
||||
topic = await session.get(Topic, ws.topic_id)
|
||||
if topic is None or topic.domain_id is None:
|
||||
return None
|
||||
domain = await session.get(Domain, topic.domain_id)
|
||||
return domain.slug if domain else None
|
||||
|
||||
|
||||
@router.get("/next_steps", response_model=list[NextStep])
|
||||
async def get_next_steps(session: AsyncSession = Depends(get_session)) -> list[NextStep]:
|
||||
"""Derive contextual next-action suggestions from current hub state.
|
||||
|
||||
@@ -5,12 +5,19 @@ from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from api.database import get_session
|
||||
from api.models.domain import Domain
|
||||
from api.models.technical_debt import TDStatus, TechnicalDebt
|
||||
from api.schemas.technical_debt import TDCreate, TDRead, TDUpdate
|
||||
|
||||
router = APIRouter(prefix="/technical-debt", tags=["technical-debt"])
|
||||
|
||||
|
||||
async def _get_valid_domain_slugs(session: AsyncSession) -> set[str]:
|
||||
"""Return the set of active domain slugs from the DB."""
|
||||
rows = await session.execute(select(Domain.slug).where(Domain.status == "active"))
|
||||
return {r[0] for r in rows.all()}
|
||||
|
||||
|
||||
@router.get("/", response_model=list[TDRead])
|
||||
async def list_td(
|
||||
domain: str | None = None,
|
||||
@@ -38,6 +45,12 @@ async def create_td(
|
||||
body: TDCreate,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> TechnicalDebt:
|
||||
valid_domains = await _get_valid_domain_slugs(session)
|
||||
if body.domain not in valid_domains:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail=f"Unknown domain '{body.domain}'. Valid domains: {sorted(valid_domains)}",
|
||||
)
|
||||
td = TechnicalDebt(**body.model_dump())
|
||||
session.add(td)
|
||||
await session.commit()
|
||||
|
||||
@@ -5,12 +5,22 @@ from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from api.database import get_session
|
||||
from api.models.domain import Domain
|
||||
from api.models.topic import Topic, TopicStatus
|
||||
from api.schemas.topic import TopicCreate, TopicRead, TopicUpdate, TopicWithWorkstreams
|
||||
|
||||
router = APIRouter(prefix="/topics", tags=["topics"])
|
||||
|
||||
|
||||
async def _resolve_domain_id(domain_slug: str, session: AsyncSession) -> uuid.UUID:
|
||||
"""Resolve a domain slug to its UUID. Raises 404 if not found."""
|
||||
result = await session.execute(select(Domain).where(Domain.slug == domain_slug))
|
||||
domain = result.scalar_one_or_none()
|
||||
if domain is None:
|
||||
raise HTTPException(status_code=404, detail=f"Domain '{domain_slug}' not found")
|
||||
return domain.id
|
||||
|
||||
|
||||
@router.get("/", response_model=list[TopicRead])
|
||||
async def list_topics(
|
||||
status: TopicStatus | None = None,
|
||||
@@ -29,7 +39,14 @@ async def create_topic(
|
||||
body: TopicCreate,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> Topic:
|
||||
topic = Topic(**body.model_dump())
|
||||
domain_id = await _resolve_domain_id(body.domain, session)
|
||||
topic = Topic(
|
||||
slug=body.slug,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
domain_id=domain_id,
|
||||
status=body.status,
|
||||
)
|
||||
session.add(topic)
|
||||
await session.commit()
|
||||
await session.refresh(topic)
|
||||
@@ -56,7 +73,10 @@ async def update_topic(
|
||||
topic = await session.get(Topic, topic_id)
|
||||
if topic is None:
|
||||
raise HTTPException(status_code=404, detail="Topic not found")
|
||||
for field, value in body.model_dump(exclude_unset=True).items():
|
||||
updates = body.model_dump(exclude_unset=True)
|
||||
if "domain" in updates:
|
||||
topic.domain_id = await _resolve_domain_id(updates.pop("domain"), session)
|
||||
for field, value in updates.items():
|
||||
setattr(topic, field, value)
|
||||
await session.commit()
|
||||
await session.refresh(topic)
|
||||
|
||||
61
api/schemas/domain.py
Normal file
61
api/schemas/domain.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class DomainCreate(BaseModel):
|
||||
slug: str
|
||||
name: str
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class DomainUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
status: str | None = None
|
||||
|
||||
|
||||
class DomainRename(BaseModel):
|
||||
new_slug: str
|
||||
new_name: str
|
||||
|
||||
|
||||
class RepoStub(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
id: uuid.UUID
|
||||
slug: str
|
||||
name: str
|
||||
local_path: str | None = None
|
||||
remote_url: str | None = None
|
||||
status: str
|
||||
|
||||
|
||||
class DomainRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
id: uuid.UUID
|
||||
slug: str
|
||||
name: str
|
||||
description: str | None = None
|
||||
status: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class DomainDetail(DomainRead):
|
||||
"""Domain with entity counts and repo list."""
|
||||
topic_count: int = 0
|
||||
workstream_count: int = 0
|
||||
ep_count: int = 0
|
||||
td_count: int = 0
|
||||
repos: list[RepoStub] = []
|
||||
|
||||
|
||||
class DomainSummary(BaseModel):
|
||||
"""Lightweight domain stats for the state summary."""
|
||||
slug: str
|
||||
name: str
|
||||
repo_count: int = 0
|
||||
active_workstream_count: int = 0
|
||||
ep_count: int = 0
|
||||
td_count: int = 0
|
||||
@@ -5,10 +5,6 @@ from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from api.models.extension_point import EPStatus
|
||||
|
||||
VALID_DOMAINS = {
|
||||
"custodian", "railiance", "markitect",
|
||||
"coulomb_social", "personhood", "foerster_capabilities",
|
||||
}
|
||||
VALID_PRIORITIES = {"low", "medium", "high", "critical"}
|
||||
|
||||
|
||||
|
||||
37
api/schemas/managed_repo.py
Normal file
37
api/schemas/managed_repo.py
Normal file
@@ -0,0 +1,37 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class RepoCreate(BaseModel):
|
||||
domain_slug: str
|
||||
slug: str
|
||||
name: str
|
||||
local_path: str | None = None
|
||||
remote_url: str | None = None
|
||||
description: str | None = None
|
||||
topic_id: uuid.UUID | None = None
|
||||
|
||||
|
||||
class RepoUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
local_path: str | None = None
|
||||
remote_url: str | None = None
|
||||
description: str | None = None
|
||||
topic_id: uuid.UUID | None = None
|
||||
|
||||
|
||||
class RepoRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
id: uuid.UUID
|
||||
domain_id: uuid.UUID
|
||||
slug: str
|
||||
name: str
|
||||
local_path: str | None = None
|
||||
remote_url: str | None = None
|
||||
description: str | None = None
|
||||
status: str
|
||||
topic_id: uuid.UUID | None = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
@@ -4,6 +4,7 @@ from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
|
||||
from api.schemas.decision import DecisionRead
|
||||
from api.schemas.domain import DomainSummary
|
||||
from api.schemas.progress_event import ProgressEventRead
|
||||
from api.schemas.task import TaskRead
|
||||
from api.schemas.topic import TopicWithWorkstreams
|
||||
@@ -75,3 +76,4 @@ class StateSummary(BaseModel):
|
||||
recent_progress: list[ProgressEventRead]
|
||||
open_workstreams: list[WorkstreamWithDeps]
|
||||
next_steps: list[NextStep] = []
|
||||
domains: list[DomainSummary] = []
|
||||
|
||||
@@ -3,22 +3,22 @@ from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from api.models.topic import Domain, TopicStatus
|
||||
from api.models.topic import TopicStatus
|
||||
|
||||
|
||||
class TopicCreate(BaseModel):
|
||||
slug: str
|
||||
title: str
|
||||
description: str | None = None
|
||||
domain: Domain
|
||||
domain: str # domain slug — resolved to domain_id in the router
|
||||
status: TopicStatus = TopicStatus.active
|
||||
|
||||
|
||||
class TopicUpdate(BaseModel):
|
||||
title: str | None = None
|
||||
description: str | None = None
|
||||
domain: Domain | None = None
|
||||
status: TopicStatus | None = None
|
||||
domain: str | None = None # domain slug — resolved to domain_id in the router
|
||||
|
||||
|
||||
class WorkstreamStub(BaseModel):
|
||||
@@ -37,7 +37,7 @@ class TopicRead(BaseModel):
|
||||
slug: str
|
||||
title: str
|
||||
description: str | None = None
|
||||
domain: Domain
|
||||
domain_slug: str | None = None # resolved from FK relationship via @property
|
||||
status: TopicStatus
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
Reference in New Issue
Block a user