feat(task-013): add draft assembly API, immutable versioning, and editor preview
This commit is contained in:
@@ -60,6 +60,7 @@ def get_article_detail(
|
||||
workflow_events = repository.articles.list_workflow_events(article_id)
|
||||
boundary_questions = repository.boundary_questions.list_for_article(article_id)
|
||||
plans = repository.article_plans.list_for_article(article_id)
|
||||
draft = repository.article_drafts.latest_for_article(article_id)
|
||||
research_manifests = repository.research_manifests.list_for_article(article_id)
|
||||
evidence = repository.evidence_items.list_for_article(article_id)
|
||||
claims = repository.claims.list_for_article(article_id)
|
||||
@@ -70,6 +71,7 @@ def get_article_detail(
|
||||
workflow_events=workflow_events,
|
||||
boundary_questions=boundary_questions,
|
||||
plan=plans[-1] if plans else None,
|
||||
draft=draft,
|
||||
evidence=evidence,
|
||||
claims=claims,
|
||||
agent_jobs=agent_jobs,
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from src.domain.contracts import (
|
||||
AgentJobStatus,
|
||||
AgentJobSummary,
|
||||
AgentJobType,
|
||||
ArticleWorkflowStatus,
|
||||
DraftAssembleResponse,
|
||||
DraftFaqItem,
|
||||
DraftListResponse,
|
||||
DraftResponse,
|
||||
DraftUpdateRequest,
|
||||
PlanReviewStatus,
|
||||
)
|
||||
|
||||
|
||||
def assemble_draft(repository: object, *, article_id: UUID) -> DraftAssembleResponse:
|
||||
article = repository.articles.get(article_id)
|
||||
approved_plan = _approved_plan(repository, article_id=article_id)
|
||||
if approved_plan is None or not approved_plan.sections:
|
||||
raise PermissionError("Approved plan with sections is required before draft assembly")
|
||||
|
||||
section_jobs = repository.agent_jobs.list_for_article(article_id)
|
||||
successful_jobs_by_section = _successful_jobs_by_section(section_jobs)
|
||||
missing_section_headings = [
|
||||
section.heading
|
||||
for section in approved_plan.sections
|
||||
if str(section.id) not in successful_jobs_by_section
|
||||
]
|
||||
if missing_section_headings:
|
||||
raise ValueError(
|
||||
"Missing successful section scaffolds for sections: "
|
||||
+ ", ".join(missing_section_headings)
|
||||
)
|
||||
|
||||
title = (
|
||||
approved_plan.recommended_title
|
||||
or article.working_title
|
||||
or article.primary_keyword
|
||||
or "Untitled draft"
|
||||
)
|
||||
meta_title = title
|
||||
meta_description = _trim_description(article.brief_description or title)
|
||||
|
||||
section_blocks: list[str] = []
|
||||
visual_placeholders: list[str] = []
|
||||
evidence_references: list[str] = []
|
||||
unsupported_warnings = _collect_job_warnings(section_jobs)
|
||||
|
||||
for section in approved_plan.sections:
|
||||
section_job = successful_jobs_by_section[str(section.id)]
|
||||
payload = section_job.payload
|
||||
section_blocks.append(_section_markdown(section.heading, payload))
|
||||
visual_placeholders.extend(
|
||||
_visual_placeholders_for_section(
|
||||
section_id=section.id,
|
||||
heading=section.heading,
|
||||
payload=payload,
|
||||
)
|
||||
)
|
||||
evidence_references.extend(_string_list(payload.get("used_evidence_ids")))
|
||||
|
||||
deduped_evidence_references = _dedupe_strings(evidence_references)
|
||||
deduped_unsupported_warnings = _dedupe_strings(unsupported_warnings)
|
||||
deduped_visual_placeholders = _dedupe_strings(visual_placeholders)
|
||||
faq_items = _build_faq_items(
|
||||
claims_to_prove=approved_plan.claims_to_prove,
|
||||
keyword=article.primary_keyword,
|
||||
)
|
||||
|
||||
draft_body = _assemble_body_markdown(
|
||||
title=title,
|
||||
meta_title=meta_title,
|
||||
meta_description=meta_description,
|
||||
section_blocks=section_blocks,
|
||||
evidence_references=deduped_evidence_references,
|
||||
visual_placeholders=deduped_visual_placeholders,
|
||||
faq_items=faq_items,
|
||||
unsupported_warnings=deduped_unsupported_warnings,
|
||||
)
|
||||
now = _now()
|
||||
next_version = repository.article_drafts.latest_version(article_id) + 1
|
||||
draft = repository.article_drafts.create_version(
|
||||
article_id=article_id,
|
||||
version=next_version,
|
||||
title=title,
|
||||
slug=_slugify(title),
|
||||
meta_title=meta_title,
|
||||
meta_description=meta_description,
|
||||
body_object_key=f"articles/{article_id}/drafts/v{next_version}.md",
|
||||
body_markdown=draft_body,
|
||||
faq_items=[item.model_dump(mode="json") for item in faq_items],
|
||||
visual_placeholders=deduped_visual_placeholders,
|
||||
evidence_references=[UUID(item_id) for item_id in deduped_evidence_references],
|
||||
unsupported_claim_warnings=deduped_unsupported_warnings,
|
||||
based_on_draft_id=None,
|
||||
status=ArticleWorkflowStatus.DRAFT_ASSEMBLED,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
repository.articles.update_status(
|
||||
article_id=article_id,
|
||||
status=ArticleWorkflowStatus.DRAFT_ASSEMBLED,
|
||||
updated_at=now,
|
||||
)
|
||||
repository.articles.create_workflow_event(
|
||||
article_id=article_id,
|
||||
event_type="DRAFT_ASSEMBLED",
|
||||
from_status=article.status,
|
||||
to_status=ArticleWorkflowStatus.DRAFT_ASSEMBLED,
|
||||
actor_user_id=None,
|
||||
payload={
|
||||
"draft_id": str(draft.id),
|
||||
"version": draft.version,
|
||||
"section_count": len(approved_plan.sections),
|
||||
},
|
||||
created_at=now,
|
||||
)
|
||||
return DraftAssembleResponse(draft=draft)
|
||||
|
||||
|
||||
def list_drafts(repository: object, *, article_id: UUID) -> DraftListResponse:
|
||||
repository.articles.get(article_id)
|
||||
return DraftListResponse(drafts=repository.article_drafts.list_for_article(article_id))
|
||||
|
||||
|
||||
def get_draft(repository: object, *, article_id: UUID, draft_id: UUID) -> DraftResponse:
|
||||
repository.articles.get(article_id)
|
||||
draft = repository.article_drafts.get(article_id=article_id, draft_id=draft_id)
|
||||
return DraftResponse(draft=draft)
|
||||
|
||||
|
||||
def update_draft(
|
||||
repository: object,
|
||||
*,
|
||||
article_id: UUID,
|
||||
draft_id: UUID,
|
||||
request: DraftUpdateRequest,
|
||||
) -> DraftResponse:
|
||||
repository.articles.get(article_id)
|
||||
base = repository.article_drafts.get(article_id=article_id, draft_id=draft_id)
|
||||
if _request_is_empty(request):
|
||||
raise ValueError("Draft update payload is empty")
|
||||
|
||||
next_version = repository.article_drafts.latest_version(article_id) + 1
|
||||
now = _now()
|
||||
title = request.title if request.title is not None else base.title
|
||||
draft = repository.article_drafts.create_version(
|
||||
article_id=article_id,
|
||||
version=next_version,
|
||||
title=title,
|
||||
slug=_slugify(title),
|
||||
meta_title=(
|
||||
request.meta_title if request.meta_title is not None else base.meta_title
|
||||
),
|
||||
meta_description=(
|
||||
request.meta_description
|
||||
if request.meta_description is not None
|
||||
else base.meta_description
|
||||
),
|
||||
body_object_key=f"articles/{article_id}/drafts/v{next_version}.md",
|
||||
body_markdown=(
|
||||
request.body_markdown
|
||||
if request.body_markdown is not None
|
||||
else base.body_markdown
|
||||
),
|
||||
faq_items=[
|
||||
item.model_dump(mode="json")
|
||||
for item in (
|
||||
request.faq_items
|
||||
if request.faq_items is not None
|
||||
else base.faq_items
|
||||
)
|
||||
],
|
||||
visual_placeholders=(
|
||||
request.visual_placeholders
|
||||
if request.visual_placeholders is not None
|
||||
else base.visual_placeholders
|
||||
),
|
||||
evidence_references=(
|
||||
request.evidence_references
|
||||
if request.evidence_references is not None
|
||||
else base.evidence_references
|
||||
),
|
||||
unsupported_claim_warnings=(
|
||||
request.unsupported_claim_warnings
|
||||
if request.unsupported_claim_warnings is not None
|
||||
else base.unsupported_claim_warnings
|
||||
),
|
||||
based_on_draft_id=base.id,
|
||||
status=base.status,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
repository.articles.create_workflow_event(
|
||||
article_id=article_id,
|
||||
event_type="DRAFT_VERSION_CREATED",
|
||||
from_status=ArticleWorkflowStatus.DRAFT_ASSEMBLED,
|
||||
to_status=ArticleWorkflowStatus.DRAFT_ASSEMBLED,
|
||||
actor_user_id=None,
|
||||
payload={
|
||||
"draft_id": str(draft.id),
|
||||
"version": draft.version,
|
||||
"based_on_draft_id": str(base.id),
|
||||
},
|
||||
created_at=now,
|
||||
)
|
||||
return DraftResponse(draft=draft)
|
||||
|
||||
|
||||
def _approved_plan(repository: object, *, article_id: UUID) -> object | None:
|
||||
plans = repository.article_plans.list_for_article(article_id)
|
||||
approved_plans = [
|
||||
plan for plan in plans if plan.status == PlanReviewStatus.APPROVED
|
||||
]
|
||||
if not approved_plans:
|
||||
return None
|
||||
approved_plans.sort(key=lambda plan: plan.version)
|
||||
return approved_plans[-1]
|
||||
|
||||
|
||||
def _successful_jobs_by_section(
|
||||
jobs: list[AgentJobSummary],
|
||||
) -> dict[str, AgentJobSummary]:
|
||||
sections: dict[str, AgentJobSummary] = {}
|
||||
for job in jobs:
|
||||
if job.job_type != AgentJobType.SECTION_SCAFFOLD:
|
||||
continue
|
||||
if job.status != AgentJobStatus.SUCCEEDED:
|
||||
continue
|
||||
section_id = _string_value(job.payload.get("section_id"))
|
||||
if not section_id:
|
||||
continue
|
||||
existing = sections.get(section_id)
|
||||
if existing is None or _job_sort_key(job) > _job_sort_key(existing):
|
||||
sections[section_id] = job
|
||||
return sections
|
||||
|
||||
|
||||
def _collect_job_warnings(jobs: list[AgentJobSummary]) -> list[str]:
|
||||
warnings: list[str] = []
|
||||
for job in jobs:
|
||||
if job.job_type != AgentJobType.SECTION_SCAFFOLD:
|
||||
continue
|
||||
heading = _string_value(job.payload.get("heading")) or _string_value(
|
||||
job.payload.get("artifact_label")
|
||||
)
|
||||
warnings.extend(
|
||||
_unsupported_claim_warnings(
|
||||
heading=heading or "section",
|
||||
raw_claims=job.payload.get("unsupported_claims"),
|
||||
)
|
||||
)
|
||||
return warnings
|
||||
|
||||
|
||||
def _job_sort_key(job: AgentJobSummary) -> tuple[int, str]:
|
||||
queued_at = job.queued_at.isoformat() if job.queued_at else ""
|
||||
return (job.attempt, queued_at)
|
||||
|
||||
|
||||
def _section_markdown(heading: str, payload: dict[str, Any]) -> str:
|
||||
section_markdown = _string_value(payload.get("draft_markdown")).strip()
|
||||
if not section_markdown:
|
||||
return f"## {heading}\n\nDraft content is missing for this section."
|
||||
if section_markdown.lstrip().startswith("#"):
|
||||
return section_markdown
|
||||
return f"## {heading}\n\n{section_markdown}"
|
||||
|
||||
|
||||
def _visual_placeholders_for_section(
|
||||
*,
|
||||
section_id: UUID,
|
||||
heading: str,
|
||||
payload: dict[str, Any],
|
||||
) -> list[str]:
|
||||
suggested_visuals = payload.get("suggested_visuals")
|
||||
placeholders: list[str] = []
|
||||
if isinstance(suggested_visuals, list):
|
||||
for index, visual in enumerate(suggested_visuals, start=1):
|
||||
label = _visual_label(visual, heading=heading, fallback_index=index)
|
||||
placeholders.append(
|
||||
f""
|
||||
)
|
||||
if placeholders:
|
||||
return placeholders
|
||||
return [f""]
|
||||
|
||||
|
||||
def _visual_label(value: Any, *, heading: str, fallback_index: int) -> str:
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
if isinstance(value, dict):
|
||||
for key in ("title", "caption", "prompt", "label"):
|
||||
key_value = value.get(key)
|
||||
if isinstance(key_value, str) and key_value.strip():
|
||||
return key_value.strip()
|
||||
return f"{heading} visual {fallback_index}"
|
||||
|
||||
|
||||
def _unsupported_claim_warnings(*, heading: str, raw_claims: Any) -> list[str]:
|
||||
if not isinstance(raw_claims, list):
|
||||
return []
|
||||
warnings: list[str] = []
|
||||
for claim in raw_claims:
|
||||
if isinstance(claim, str) and claim.strip():
|
||||
warnings.append(f"{heading}: {claim.strip()}")
|
||||
continue
|
||||
if isinstance(claim, dict):
|
||||
claim_text = claim.get("claim_text")
|
||||
if isinstance(claim_text, str) and claim_text.strip():
|
||||
warnings.append(f"{heading}: {claim_text.strip()}")
|
||||
return warnings
|
||||
|
||||
|
||||
def _build_faq_items(
|
||||
*,
|
||||
claims_to_prove: list[str],
|
||||
keyword: str | None,
|
||||
) -> list[DraftFaqItem]:
|
||||
faq_items: list[DraftFaqItem] = []
|
||||
for claim in claims_to_prove[:3]:
|
||||
text = claim.strip()
|
||||
if not text:
|
||||
continue
|
||||
faq_items.append(
|
||||
DraftFaqItem(
|
||||
question=f"What evidence supports: {text}?",
|
||||
answer="Evidence references are listed in the section and summary blocks.",
|
||||
)
|
||||
)
|
||||
if faq_items:
|
||||
return faq_items
|
||||
base_keyword = (keyword or "this topic").strip()
|
||||
return [
|
||||
DraftFaqItem(
|
||||
question=f"What should readers know about {base_keyword}?",
|
||||
answer="The draft sections provide context, implementation details, and references.",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _assemble_body_markdown(
|
||||
*,
|
||||
title: str,
|
||||
meta_title: str,
|
||||
meta_description: str,
|
||||
section_blocks: list[str],
|
||||
evidence_references: list[str],
|
||||
visual_placeholders: list[str],
|
||||
faq_items: list[DraftFaqItem],
|
||||
unsupported_warnings: list[str],
|
||||
) -> str:
|
||||
lines = [
|
||||
f"# {title}",
|
||||
"",
|
||||
f"> Meta title: {meta_title}",
|
||||
f"> Meta description: {meta_description}",
|
||||
"",
|
||||
]
|
||||
lines.extend("\n\n".join(section_blocks).splitlines())
|
||||
lines.extend(["", "## Evidence References", ""])
|
||||
if evidence_references:
|
||||
for evidence_id in evidence_references:
|
||||
lines.append(f"- `{evidence_id}`")
|
||||
else:
|
||||
lines.append("- No evidence references recorded.")
|
||||
|
||||
lines.extend(["", "## Visual Placeholders", ""])
|
||||
for placeholder in visual_placeholders:
|
||||
lines.append(placeholder)
|
||||
|
||||
lines.extend(["", "## FAQ", ""])
|
||||
for item in faq_items:
|
||||
lines.append(f"### {item.question}")
|
||||
lines.append("")
|
||||
lines.append(item.answer)
|
||||
lines.append("")
|
||||
|
||||
if unsupported_warnings:
|
||||
lines.extend(["## Unsupported Claim Warnings", ""])
|
||||
for warning in unsupported_warnings:
|
||||
lines.append(f"- {warning}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines).strip() + "\n"
|
||||
|
||||
|
||||
def _trim_description(value: str) -> str:
|
||||
normalized = " ".join(value.split())
|
||||
if len(normalized) <= 155:
|
||||
return normalized
|
||||
return normalized[:152].rstrip() + "..."
|
||||
|
||||
|
||||
def _slugify(value: str) -> str:
|
||||
normalized = value.strip().lower()
|
||||
normalized = re.sub(r"[^a-z0-9]+", "-", normalized)
|
||||
normalized = normalized.strip("-")
|
||||
if normalized:
|
||||
return normalized
|
||||
return "draft"
|
||||
|
||||
|
||||
def _string_list(value: Any) -> list[str]:
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
return [item for item in value if isinstance(item, str) and item]
|
||||
|
||||
|
||||
def _string_value(value: Any) -> str:
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def _dedupe_strings(values: list[str]) -> list[str]:
|
||||
deduped: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for value in values:
|
||||
if value in seen:
|
||||
continue
|
||||
seen.add(value)
|
||||
deduped.append(value)
|
||||
return deduped
|
||||
|
||||
|
||||
def _request_is_empty(request: DraftUpdateRequest) -> bool:
|
||||
return all(
|
||||
value is None
|
||||
for value in (
|
||||
request.title,
|
||||
request.meta_title,
|
||||
request.meta_description,
|
||||
request.body_markdown,
|
||||
request.faq_items,
|
||||
request.visual_placeholders,
|
||||
request.evidence_references,
|
||||
request.unsupported_claim_warnings,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
@@ -34,7 +34,12 @@ from .models import (
|
||||
ClaimSummary,
|
||||
CurrentUser,
|
||||
CurrentUserResponse,
|
||||
DraftAssembleResponse,
|
||||
DraftFaqItem,
|
||||
DraftListResponse,
|
||||
DraftResponse,
|
||||
DraftSummary,
|
||||
DraftUpdateRequest,
|
||||
EvidenceSummary,
|
||||
EvidenceCreateRequest,
|
||||
EvidenceMatrixResponse,
|
||||
@@ -102,7 +107,12 @@ __all__ = [
|
||||
"ClaimSupportStatus",
|
||||
"CurrentUser",
|
||||
"CurrentUserResponse",
|
||||
"DraftAssembleResponse",
|
||||
"DraftFaqItem",
|
||||
"DraftListResponse",
|
||||
"DraftResponse",
|
||||
"DraftSummary",
|
||||
"DraftUpdateRequest",
|
||||
"EvidenceSummary",
|
||||
"EvidenceCreateRequest",
|
||||
"EvidenceMatrixResponse",
|
||||
|
||||
@@ -361,6 +361,11 @@ class EvidenceMatrixResponse(ContractModel):
|
||||
insufficient_evidence_reasons: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class DraftFaqItem(ContractModel):
|
||||
question: str = Field(min_length=1)
|
||||
answer: str = Field(min_length=1)
|
||||
|
||||
|
||||
class DraftSummary(ContractModel):
|
||||
id: UUID
|
||||
article_id: UUID
|
||||
@@ -370,7 +375,14 @@ class DraftSummary(ContractModel):
|
||||
meta_title: str | None = None
|
||||
meta_description: str | None = None
|
||||
body_object_key: str | None = None
|
||||
body_markdown: str = ""
|
||||
faq_items: list[DraftFaqItem] = Field(default_factory=list)
|
||||
visual_placeholders: list[str] = Field(default_factory=list)
|
||||
evidence_references: list[UUID] = Field(default_factory=list)
|
||||
unsupported_claim_warnings: list[str] = Field(default_factory=list)
|
||||
based_on_draft_id: UUID | None = None
|
||||
status: ArticleWorkflowStatus
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
@@ -462,6 +474,29 @@ class AgentJobOutput(ContractModel):
|
||||
payload: JsonObject = Field(default_factory=dict)
|
||||
|
||||
|
||||
class DraftAssembleResponse(ContractModel):
|
||||
draft: DraftSummary
|
||||
|
||||
|
||||
class DraftListResponse(ContractModel):
|
||||
drafts: list[DraftSummary] = Field(default_factory=list)
|
||||
|
||||
|
||||
class DraftResponse(ContractModel):
|
||||
draft: DraftSummary
|
||||
|
||||
|
||||
class DraftUpdateRequest(ContractModel):
|
||||
title: str | None = Field(default=None, min_length=1)
|
||||
meta_title: str | None = None
|
||||
meta_description: str | None = None
|
||||
body_markdown: str | None = None
|
||||
faq_items: list[DraftFaqItem] | None = None
|
||||
visual_placeholders: list[str] | None = None
|
||||
evidence_references: list[UUID] | None = None
|
||||
unsupported_claim_warnings: list[str] | None = None
|
||||
|
||||
|
||||
class ArticleDetailResponse(ContractModel):
|
||||
article: ArticleSummary
|
||||
target_site: TargetSiteConfig | None = None
|
||||
|
||||
@@ -40,7 +40,12 @@ from .models import (
|
||||
ClaimSummary,
|
||||
CurrentUser,
|
||||
CurrentUserResponse,
|
||||
DraftAssembleResponse,
|
||||
DraftFaqItem,
|
||||
DraftListResponse,
|
||||
DraftResponse,
|
||||
DraftSummary,
|
||||
DraftUpdateRequest,
|
||||
EvidenceSummary,
|
||||
EvidenceCreateRequest,
|
||||
EvidenceMatrixResponse,
|
||||
@@ -132,6 +137,11 @@ CONTRACT_SCHEMA_MODELS: tuple[type[BaseModel], ...] = (
|
||||
ClaimSummary,
|
||||
EvidenceMatrixResponse,
|
||||
DraftSummary,
|
||||
DraftFaqItem,
|
||||
DraftAssembleResponse,
|
||||
DraftListResponse,
|
||||
DraftResponse,
|
||||
DraftUpdateRequest,
|
||||
AssetSummary,
|
||||
ReviewSummary,
|
||||
ReviewActionResponse,
|
||||
|
||||
@@ -18,6 +18,8 @@ from src.domain.contracts import (
|
||||
ClaimRiskLevel,
|
||||
ClaimSupportStatus,
|
||||
ClaimSummary,
|
||||
DraftFaqItem,
|
||||
DraftSummary,
|
||||
EvidenceSummary,
|
||||
PlanReviewStatus,
|
||||
PlanSectionSummary,
|
||||
@@ -52,6 +54,7 @@ class BackendRepository:
|
||||
self.articles = ArticlesRepository(self)
|
||||
self.boundary_questions = BoundaryQuestionsRepository(self)
|
||||
self.article_plans = ArticlePlansRepository(self)
|
||||
self.article_drafts = ArticleDraftsRepository(self)
|
||||
self.research_manifests = ResearchManifestsRepository(self)
|
||||
self.evidence_items = EvidenceItemsRepository(self)
|
||||
self.claims = ClaimsRepository(self)
|
||||
@@ -1014,6 +1017,181 @@ class ArticlePlansRepository:
|
||||
"""
|
||||
|
||||
|
||||
class ArticleDraftsRepository:
|
||||
def __init__(self, repository: BackendRepository) -> None:
|
||||
self._repository = repository
|
||||
|
||||
def create_version(
|
||||
self,
|
||||
*,
|
||||
article_id: UUID,
|
||||
version: int,
|
||||
title: str,
|
||||
slug: str,
|
||||
meta_title: str | None,
|
||||
meta_description: str | None,
|
||||
body_object_key: str | None,
|
||||
body_markdown: str,
|
||||
faq_items: list[JsonObject],
|
||||
visual_placeholders: list[str],
|
||||
evidence_references: list[UUID],
|
||||
unsupported_claim_warnings: list[str],
|
||||
based_on_draft_id: UUID | None,
|
||||
status: ArticleWorkflowStatus,
|
||||
created_at: datetime,
|
||||
updated_at: datetime,
|
||||
) -> DraftSummary:
|
||||
draft_id = uuid4()
|
||||
placeholder = self._repository.placeholder()
|
||||
json_cast = self._repository.json_cast()
|
||||
with self._repository.connection() as connection:
|
||||
connection.execute(
|
||||
f"""
|
||||
INSERT INTO article_drafts (
|
||||
id,
|
||||
article_id,
|
||||
version,
|
||||
title,
|
||||
slug,
|
||||
meta_title,
|
||||
meta_description,
|
||||
body_object_key,
|
||||
body_markdown,
|
||||
faq_items,
|
||||
visual_placeholders,
|
||||
evidence_references,
|
||||
unsupported_claim_warnings,
|
||||
based_on_draft_id,
|
||||
status,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder}{json_cast},
|
||||
{placeholder}{json_cast},
|
||||
{placeholder}{json_cast},
|
||||
{placeholder}{json_cast},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder},
|
||||
{placeholder}
|
||||
)
|
||||
""",
|
||||
(
|
||||
str(draft_id),
|
||||
str(article_id),
|
||||
version,
|
||||
title,
|
||||
slug,
|
||||
meta_title,
|
||||
meta_description,
|
||||
body_object_key,
|
||||
body_markdown,
|
||||
_json_value(faq_items),
|
||||
_json_value(visual_placeholders),
|
||||
_json_value([str(item_id) for item_id in evidence_references]),
|
||||
_json_value(unsupported_claim_warnings),
|
||||
_uuid_value(based_on_draft_id),
|
||||
status.value,
|
||||
_datetime_value(created_at),
|
||||
_datetime_value(updated_at),
|
||||
),
|
||||
)
|
||||
|
||||
return self.get(article_id=article_id, draft_id=draft_id)
|
||||
|
||||
def list_for_article(self, article_id: UUID) -> list[DraftSummary]:
|
||||
placeholder = self._repository.placeholder()
|
||||
with self._repository.connection() as connection:
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
SELECT {self._select_columns()}
|
||||
FROM article_drafts
|
||||
WHERE article_id = {placeholder}
|
||||
ORDER BY version DESC
|
||||
""",
|
||||
(str(article_id),),
|
||||
).fetchall()
|
||||
|
||||
return [_draft_summary_from_row(row) for row in rows]
|
||||
|
||||
def get(self, *, article_id: UUID, draft_id: UUID) -> DraftSummary:
|
||||
placeholder = self._repository.placeholder()
|
||||
with self._repository.connection() as connection:
|
||||
row = connection.execute(
|
||||
f"""
|
||||
SELECT {self._select_columns()}
|
||||
FROM article_drafts
|
||||
WHERE article_id = {placeholder} AND id = {placeholder}
|
||||
""",
|
||||
(str(article_id), str(draft_id)),
|
||||
).fetchone()
|
||||
|
||||
if row is None:
|
||||
raise LookupError(f"Draft not found: {draft_id}")
|
||||
return _draft_summary_from_row(row)
|
||||
|
||||
def latest_for_article(self, article_id: UUID) -> DraftSummary | None:
|
||||
placeholder = self._repository.placeholder()
|
||||
with self._repository.connection() as connection:
|
||||
row = connection.execute(
|
||||
f"""
|
||||
SELECT {self._select_columns()}
|
||||
FROM article_drafts
|
||||
WHERE article_id = {placeholder}
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(str(article_id),),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return _draft_summary_from_row(row)
|
||||
|
||||
def latest_version(self, article_id: UUID) -> int:
|
||||
placeholder = self._repository.placeholder()
|
||||
with self._repository.connection() as connection:
|
||||
row = connection.execute(
|
||||
f"""
|
||||
SELECT COALESCE(MAX(version), 0) AS version
|
||||
FROM article_drafts
|
||||
WHERE article_id = {placeholder}
|
||||
""",
|
||||
(str(article_id),),
|
||||
).fetchone()
|
||||
return int(_row_value(row, "version"))
|
||||
|
||||
def _select_columns(self) -> str:
|
||||
return """
|
||||
id,
|
||||
article_id,
|
||||
version,
|
||||
title,
|
||||
slug,
|
||||
meta_title,
|
||||
meta_description,
|
||||
body_object_key,
|
||||
body_markdown,
|
||||
faq_items,
|
||||
visual_placeholders,
|
||||
evidence_references,
|
||||
unsupported_claim_warnings,
|
||||
based_on_draft_id,
|
||||
status,
|
||||
created_at,
|
||||
updated_at
|
||||
"""
|
||||
|
||||
|
||||
class ResearchManifestsRepository:
|
||||
def __init__(self, repository: BackendRepository) -> None:
|
||||
self._repository = repository
|
||||
@@ -2176,6 +2354,35 @@ def _claim_from_row(row: Any) -> ClaimSummary:
|
||||
)
|
||||
|
||||
|
||||
def _draft_summary_from_row(row: Any) -> DraftSummary:
|
||||
return DraftSummary(
|
||||
id=_row_value(row, "id"),
|
||||
article_id=_row_value(row, "article_id"),
|
||||
version=_row_value(row, "version"),
|
||||
title=_row_value(row, "title"),
|
||||
slug=_row_value(row, "slug"),
|
||||
meta_title=_row_value(row, "meta_title"),
|
||||
meta_description=_row_value(row, "meta_description"),
|
||||
body_object_key=_row_value(row, "body_object_key"),
|
||||
body_markdown=_row_value(row, "body_markdown"),
|
||||
faq_items=[
|
||||
DraftFaqItem.model_validate(item)
|
||||
for item in _json_from_row(row, "faq_items")
|
||||
],
|
||||
visual_placeholders=_json_from_row(row, "visual_placeholders"),
|
||||
evidence_references=[
|
||||
UUID(value) for value in _json_from_row(row, "evidence_references")
|
||||
],
|
||||
unsupported_claim_warnings=_json_from_row(
|
||||
row, "unsupported_claim_warnings"
|
||||
),
|
||||
based_on_draft_id=_row_value(row, "based_on_draft_id"),
|
||||
status=_row_value(row, "status"),
|
||||
created_at=_row_value(row, "created_at"),
|
||||
updated_at=_row_value(row, "updated_at"),
|
||||
)
|
||||
|
||||
|
||||
def _agent_job_summary_from_row(row: Any) -> AgentJobSummary:
|
||||
return AgentJobSummary(
|
||||
id=_row_value(row, "id"),
|
||||
|
||||
@@ -215,12 +215,24 @@ POSTGRES_SCHEMA_STATEMENTS: tuple[str, ...] = (
|
||||
meta_title TEXT,
|
||||
meta_description TEXT,
|
||||
body_object_key TEXT,
|
||||
body_markdown TEXT NOT NULL DEFAULT '',
|
||||
faq_items JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
visual_placeholders JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
evidence_references JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
unsupported_claim_warnings JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
based_on_draft_id UUID REFERENCES article_drafts(id) ON DELETE SET NULL,
|
||||
status TEXT NOT NULL CHECK (status IN ({ARTICLE_STATUS_VALUES})),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (article_id, version)
|
||||
)
|
||||
""",
|
||||
"ALTER TABLE article_drafts ADD COLUMN IF NOT EXISTS body_markdown TEXT NOT NULL DEFAULT ''",
|
||||
"ALTER TABLE article_drafts ADD COLUMN IF NOT EXISTS faq_items JSONB NOT NULL DEFAULT '[]'::jsonb",
|
||||
"ALTER TABLE article_drafts ADD COLUMN IF NOT EXISTS visual_placeholders JSONB NOT NULL DEFAULT '[]'::jsonb",
|
||||
"ALTER TABLE article_drafts ADD COLUMN IF NOT EXISTS evidence_references JSONB NOT NULL DEFAULT '[]'::jsonb",
|
||||
"ALTER TABLE article_drafts ADD COLUMN IF NOT EXISTS unsupported_claim_warnings JSONB NOT NULL DEFAULT '[]'::jsonb",
|
||||
"ALTER TABLE article_drafts ADD COLUMN IF NOT EXISTS based_on_draft_id UUID REFERENCES article_drafts(id) ON DELETE SET NULL",
|
||||
f"""
|
||||
CREATE TABLE IF NOT EXISTS assets (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -525,6 +537,12 @@ SQLITE_SCHEMA_STATEMENTS: tuple[str, ...] = (
|
||||
meta_title TEXT,
|
||||
meta_description TEXT,
|
||||
body_object_key TEXT,
|
||||
body_markdown TEXT NOT NULL DEFAULT '',
|
||||
faq_items TEXT NOT NULL DEFAULT '[]',
|
||||
visual_placeholders TEXT NOT NULL DEFAULT '[]',
|
||||
evidence_references TEXT NOT NULL DEFAULT '[]',
|
||||
unsupported_claim_warnings TEXT NOT NULL DEFAULT '[]',
|
||||
based_on_draft_id TEXT,
|
||||
status TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
@@ -12,6 +12,7 @@ from src.presentation.routes.agent_jobs import router as agent_jobs_router
|
||||
from src.presentation.routes.articles import router as articles_router
|
||||
from src.presentation.routes.auth import router as auth_router
|
||||
from src.presentation.routes.boundary_questions import router as boundary_questions_router
|
||||
from src.presentation.routes.drafts import router as drafts_router
|
||||
from src.presentation.routes.evidence import router as evidence_router
|
||||
from src.presentation.routes.plans import router as plans_router
|
||||
from src.presentation.routes.sites import router as sites_router
|
||||
@@ -23,6 +24,7 @@ app.include_router(articles_router)
|
||||
app.include_router(boundary_questions_router)
|
||||
app.include_router(plans_router)
|
||||
app.include_router(evidence_router)
|
||||
app.include_router(drafts_router)
|
||||
app.include_router(agent_jobs_router)
|
||||
app.include_router(internal_agent_jobs_router)
|
||||
app.include_router(sites_router)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from src.application.drafts import assemble_draft, get_draft, list_drafts, update_draft
|
||||
from src.domain.auth import EDITOR_OR_ADMIN_ROLES
|
||||
from src.domain.contracts import (
|
||||
CurrentUser,
|
||||
DraftAssembleResponse,
|
||||
DraftListResponse,
|
||||
DraftResponse,
|
||||
DraftUpdateRequest,
|
||||
)
|
||||
from src.infrastructure.repositories import BackendRepository
|
||||
from src.presentation.dependencies import get_repository, require_roles
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["drafts"])
|
||||
|
||||
|
||||
@router.post(
|
||||
"/articles/{article_id}/draft/assemble",
|
||||
response_model=DraftAssembleResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def post_assemble_draft(
|
||||
article_id: UUID,
|
||||
_: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
|
||||
repository: BackendRepository = Depends(get_repository),
|
||||
) -> DraftAssembleResponse:
|
||||
try:
|
||||
return assemble_draft(repository, article_id=article_id)
|
||||
except LookupError as error:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
|
||||
except (PermissionError, ValueError) as error:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error)) from error
|
||||
|
||||
|
||||
@router.get(
|
||||
"/articles/{article_id}/drafts",
|
||||
response_model=DraftListResponse,
|
||||
)
|
||||
def get_article_drafts(
|
||||
article_id: UUID,
|
||||
_: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
|
||||
repository: BackendRepository = Depends(get_repository),
|
||||
) -> DraftListResponse:
|
||||
try:
|
||||
return list_drafts(repository, article_id=article_id)
|
||||
except LookupError as error:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
|
||||
|
||||
|
||||
@router.get(
|
||||
"/articles/{article_id}/drafts/{draft_id}",
|
||||
response_model=DraftResponse,
|
||||
)
|
||||
def get_article_draft(
|
||||
article_id: UUID,
|
||||
draft_id: UUID,
|
||||
_: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
|
||||
repository: BackendRepository = Depends(get_repository),
|
||||
) -> DraftResponse:
|
||||
try:
|
||||
return get_draft(repository, article_id=article_id, draft_id=draft_id)
|
||||
except LookupError as error:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/articles/{article_id}/drafts/{draft_id}",
|
||||
response_model=DraftResponse,
|
||||
)
|
||||
def patch_article_draft(
|
||||
article_id: UUID,
|
||||
draft_id: UUID,
|
||||
request: DraftUpdateRequest,
|
||||
_: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
|
||||
repository: BackendRepository = Depends(get_repository),
|
||||
) -> DraftResponse:
|
||||
try:
|
||||
return update_draft(
|
||||
repository,
|
||||
article_id=article_id,
|
||||
draft_id=draft_id,
|
||||
request=request,
|
||||
)
|
||||
except LookupError as error:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error)) from error
|
||||
Reference in New Issue
Block a user