Task 009 implement plan generation review gate

This commit is contained in:
2026-05-21 19:56:58 +03:00
parent b7e2fa34b2
commit 5b27d1a3ca
24 changed files with 2422 additions and 59 deletions
+3 -23
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
from datetime import UTC, datetime
from uuid import UUID, uuid4
from uuid import UUID
from src.domain.contracts import (
ArticleCreateRequest,
@@ -11,10 +11,6 @@ from src.domain.contracts import (
ArticleWorkflowStatus,
CurrentUser,
PublishingStatus,
ReviewActionResponse,
ReviewStatus,
ReviewSummary,
ReviewType,
)
@@ -63,31 +59,15 @@ def get_article_detail(
target_site = repository.target_sites.get_by_id(article.target_site_id)
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)
return ArticleDetailResponse(
article=article,
target_site=target_site,
workflow_events=workflow_events,
boundary_questions=boundary_questions,
plan=plans[-1] if plans else None,
)
def build_placeholder_plan_approval_response(
*,
article_id: UUID,
plan_id: UUID,
reviewer_id: UUID,
) -> ReviewActionResponse:
review = ReviewSummary(
id=uuid4(),
article_id=article_id,
review_type=ReviewType.PLAN,
status=ReviewStatus.APPROVED,
reviewer_id=reviewer_id,
notes=None,
created_at=_now(),
)
return ReviewActionResponse(review=review)
def _now() -> datetime:
return datetime.now(UTC)
+330
View File
@@ -0,0 +1,330 @@
from __future__ import annotations
from datetime import UTC, datetime
from uuid import UUID, uuid4
from src.domain.contracts import (
AgentJobListResponse,
AgentJobStatus,
AgentJobType,
ArticleWorkflowStatus,
CurrentUser,
PlanListResponse,
PlanResponse,
PlanReviewStatus,
PlanRevisionRequest,
PlanSummary,
PlanUpdateRequest,
ReviewActionResponse,
ReviewStatus,
ReviewSummary,
ReviewType,
)
def generate_plan(
repository: object,
*,
article_id: UUID,
current_user: CurrentUser,
) -> PlanResponse:
article = repository.articles.get(article_id)
if article.status not in {
ArticleWorkflowStatus.BOUNDARY_ANSWERS_SUBMITTED,
ArticleWorkflowStatus.PLAN_REVISION_REQUIRED,
}:
raise PermissionError("Boundary answers must be submitted before plan generation")
target_site = repository.target_sites.get_by_id(article.target_site_id)
questions = repository.boundary_questions.list_for_article(article_id)
version = repository.article_plans.latest_version(article_id) + 1
now = _now()
plan = repository.article_plans.create_version(
article_id=article_id,
version=version,
status=PlanReviewStatus.PENDING_REVIEW,
created_at=now,
**_plan_fixture(article=article, target_site=target_site, questions=questions),
)
repository.articles.update_status(
article_id=article_id,
status=ArticleWorkflowStatus.PLAN_REVIEW_REQUIRED,
updated_at=now,
)
repository.articles.create_workflow_event(
article_id=article_id,
event_type="PLAN_GENERATED",
from_status=article.status,
to_status=ArticleWorkflowStatus.PLAN_REVIEW_REQUIRED,
actor_user_id=current_user.id,
payload={"plan_id": str(plan.id), "plan_version": plan.version},
created_at=now,
)
return PlanResponse(plan=plan)
def list_plans(repository: object, *, article_id: UUID) -> PlanListResponse:
repository.articles.get(article_id)
return PlanListResponse(plans=repository.article_plans.list_for_article(article_id))
def get_plan(repository: object, *, article_id: UUID, plan_id: UUID) -> PlanResponse:
repository.articles.get(article_id)
return PlanResponse(plan=repository.article_plans.get(article_id=article_id, plan_id=plan_id))
def edit_plan(
repository: object,
*,
article_id: UUID,
plan_id: UUID,
request: PlanUpdateRequest,
current_user: CurrentUser,
) -> PlanResponse:
original = repository.article_plans.get(article_id=article_id, plan_id=plan_id)
payload = _plan_payload_from_summary(original)
update = request.model_dump(exclude_unset=True)
payload.update(update)
if request.sections is not None:
payload["sections"] = [
section.model_dump(mode="json") for section in request.sections
]
now = _now()
plan = repository.article_plans.create_version(
article_id=article_id,
version=repository.article_plans.latest_version(article_id) + 1,
status=PlanReviewStatus.PENDING_REVIEW,
created_at=now,
**payload,
)
repository.articles.create_workflow_event(
article_id=article_id,
event_type="PLAN_EDITED",
from_status=ArticleWorkflowStatus.PLAN_REVIEW_REQUIRED,
to_status=ArticleWorkflowStatus.PLAN_REVIEW_REQUIRED,
actor_user_id=current_user.id,
payload={
"previous_plan_id": str(original.id),
"new_plan_id": str(plan.id),
"plan_version": plan.version,
},
created_at=now,
)
return PlanResponse(plan=plan)
def request_plan_revision(
repository: object,
*,
article_id: UUID,
plan_id: UUID,
request: PlanRevisionRequest,
current_user: CurrentUser,
) -> ReviewActionResponse:
plan = repository.article_plans.update_status(
article_id=article_id,
plan_id=plan_id,
status=PlanReviewStatus.REVISION_REQUESTED,
)
now = _now()
repository.articles.update_status(
article_id=article_id,
status=ArticleWorkflowStatus.PLAN_REVISION_REQUIRED,
updated_at=now,
)
repository.articles.create_workflow_event(
article_id=article_id,
event_type="PLAN_REVISION_REQUESTED",
from_status=ArticleWorkflowStatus.PLAN_REVIEW_REQUIRED,
to_status=ArticleWorkflowStatus.PLAN_REVISION_REQUIRED,
actor_user_id=current_user.id,
payload={"plan_id": str(plan.id), "plan_version": plan.version, "notes": request.notes},
created_at=now,
)
return _review_response(
article_id=article_id,
reviewer_id=current_user.id,
status=ReviewStatus.CHANGES_REQUESTED,
notes=request.notes,
)
def approve_plan(
repository: object,
*,
article_id: UUID,
plan_id: UUID,
current_user: CurrentUser,
) -> ReviewActionResponse:
plan = repository.article_plans.update_status(
article_id=article_id,
plan_id=plan_id,
status=PlanReviewStatus.APPROVED,
)
now = _now()
repository.articles.update_status(
article_id=article_id,
status=ArticleWorkflowStatus.RESEARCH_RUNNING,
updated_at=now,
)
repository.articles.create_workflow_event(
article_id=article_id,
event_type="PLAN_APPROVED",
from_status=ArticleWorkflowStatus.PLAN_REVIEW_REQUIRED,
to_status=ArticleWorkflowStatus.RESEARCH_RUNNING,
actor_user_id=current_user.id,
payload={"plan_id": str(plan.id), "plan_version": plan.version},
created_at=now,
)
return _review_response(
article_id=article_id,
reviewer_id=current_user.id,
status=ReviewStatus.APPROVED,
notes=f"Approved plan version {plan.version}",
)
def start_research(
repository: object,
*,
article_id: UUID,
) -> AgentJobListResponse:
article = repository.articles.get(article_id)
approved = [
plan
for plan in repository.article_plans.list_for_article(article_id)
if plan.status == PlanReviewStatus.APPROVED
]
if article.status != ArticleWorkflowStatus.RESEARCH_RUNNING or not approved:
raise PermissionError("Plan must be approved before research can start")
job = repository.agent_jobs.create(
article_id=article_id,
parent_job_id=None,
attempt=1,
job_type=AgentJobType.RESEARCH,
agent_profile="fake-research",
status=AgentJobStatus.QUEUED,
input_files=[{"path": "inputs/approved-plan.json", "content_hash": None}],
queued_at=_now(),
)
return AgentJobListResponse(jobs=[job])
def _plan_fixture(*, article: object, target_site: object, questions: list[object]) -> dict[str, object]:
keyword = article.primary_keyword or article.working_title or "content workflow"
audience = next(
(question.answer for question in questions if question.category == "audience" and question.answer),
target_site.audience,
)
return {
"title_options": [
f"{keyword}: practical implementation guide",
f"How to evaluate {keyword}",
],
"recommended_title": article.working_title or f"{keyword} guide",
"reader_persona": audience,
"search_intent": f"Evaluate and implement {keyword}",
"thesis": f"A strong {keyword} article needs clear scope, evidence, and review gates.",
"claims_to_prove": [
"Governed workflows reduce editorial risk",
"Plan approval improves research quality",
],
"evidence_needs": ["Primary documentation", "Comparable implementation examples"],
"visual_needs": ["Workflow diagram", "Evidence checklist"],
"seo_notes": [f"Use {keyword} in title, intro, and comparison headings"],
"source_requirements": ["Prefer primary vendor or standards sources"],
"excluded_sources": ["Unsourced competitor claims"],
"tone": target_site.brand_voice,
"audience": audience,
"risks": ["Claims may need evidence review", "Scope can drift without exclusions"],
"sections": [
{
"heading": "Context and scope",
"purpose": "Define reader problem and article boundary",
"key_points": ["Current workflow", "Decision criteria"],
"evidence_needs": ["Brief", "Boundary answers"],
"claims_to_support": ["Governed workflows reduce editorial risk"],
"target_word_count": 400,
},
{
"heading": "Implementation workflow",
"purpose": "Explain how the workflow should operate",
"key_points": ["Roles", "Automation", "Review gates"],
"evidence_needs": ["Architecture notes"],
"claims_to_support": ["Plan approval improves research quality"],
"target_word_count": 600,
},
{
"heading": "Evidence and quality controls",
"purpose": "Describe source standards and claim checks",
"key_points": ["Source requirements", "Unsupported claim handling"],
"evidence_needs": ["Source policy"],
"claims_to_support": ["Governed workflows reduce editorial risk"],
"target_word_count": 500,
},
{
"heading": "Risks and next steps",
"purpose": "Prepare readers for implementation tradeoffs",
"key_points": ["Operational risks", "Rollout sequence"],
"evidence_needs": ["Comparable examples"],
"claims_to_support": ["Plan approval improves research quality"],
"target_word_count": 400,
},
],
}
def _plan_payload_from_summary(plan: PlanSummary) -> dict[str, object]:
return {
"title_options": plan.title_options,
"recommended_title": plan.recommended_title,
"reader_persona": plan.reader_persona,
"search_intent": plan.search_intent,
"thesis": plan.thesis,
"claims_to_prove": plan.claims_to_prove,
"evidence_needs": plan.evidence_needs,
"visual_needs": plan.visual_needs,
"seo_notes": plan.seo_notes,
"source_requirements": plan.source_requirements,
"excluded_sources": plan.excluded_sources,
"tone": plan.tone,
"audience": plan.audience,
"risks": plan.risks,
"sections": [
{
"heading": section.heading,
"purpose": section.purpose,
"key_points": section.key_points,
"evidence_needs": section.evidence_needs,
"claims_to_support": section.claims_to_support,
"target_word_count": section.target_word_count,
}
for section in plan.sections
],
}
def _review_response(
*,
article_id: UUID,
reviewer_id: UUID,
status: ReviewStatus,
notes: str | None,
) -> ReviewActionResponse:
return ReviewActionResponse(
review=ReviewSummary(
id=uuid4(),
article_id=article_id,
review_type=ReviewType.PLAN,
status=status,
reviewer_id=reviewer_id,
notes=notes,
created_at=_now(),
)
)
def _now() -> datetime:
return datetime.now(UTC)
@@ -37,7 +37,12 @@ from .models import (
DraftSummary,
EvidenceSummary,
PlanSectionSummary,
PlanSectionEditRequest,
PlanListResponse,
PlanResponse,
PlanRevisionRequest,
PlanSummary,
PlanUpdateRequest,
PublishCommitSummary,
PublishingRules,
ResearchArtifactManifestSummary,
@@ -94,8 +99,13 @@ __all__ = [
"DraftSummary",
"EvidenceSummary",
"PlanReviewStatus",
"PlanListResponse",
"PlanResponse",
"PlanRevisionRequest",
"PlanSectionEditRequest",
"PlanSectionSummary",
"PlanSummary",
"PlanUpdateRequest",
"PublishCommitSummary",
"PublishingRules",
"PublishingStatus",
@@ -214,6 +214,8 @@ class PlanSectionSummary(ContractModel):
sort_order: int = Field(ge=1)
heading: str = Field(min_length=1)
purpose: str | None = None
key_points: list[str] = Field(default_factory=list)
evidence_needs: list[str] = Field(default_factory=list)
claims_to_support: list[str] = Field(default_factory=list)
target_word_count: int | None = Field(default=None, ge=1)
@@ -223,15 +225,63 @@ class PlanSummary(ContractModel):
article_id: UUID
version: int = Field(ge=1)
status: PlanReviewStatus
title_options: list[str] = Field(default_factory=list)
recommended_title: str | None = None
reader_persona: str | None = None
search_intent: str | None = None
thesis: str | None = None
sections: list[PlanSectionSummary] = Field(default_factory=list)
claims_to_prove: list[str] = Field(default_factory=list)
evidence_needs: list[str] = Field(default_factory=list)
visual_needs: list[str] = Field(default_factory=list)
seo_notes: list[str] = Field(default_factory=list)
source_requirements: list[str] = Field(default_factory=list)
excluded_sources: list[str] = Field(default_factory=list)
tone: str | None = None
audience: str | None = None
risks: list[str] = Field(default_factory=list)
created_at: datetime
class PlanSectionEditRequest(ContractModel):
heading: str = Field(min_length=1)
purpose: str | None = None
key_points: list[str] = Field(default_factory=list)
evidence_needs: list[str] = Field(default_factory=list)
claims_to_support: list[str] = Field(default_factory=list)
target_word_count: int | None = Field(default=None, ge=1)
class PlanUpdateRequest(ContractModel):
title_options: list[str] | None = None
recommended_title: str | None = None
reader_persona: str | None = None
search_intent: str | None = None
thesis: str | None = None
sections: list[PlanSectionEditRequest] | None = None
claims_to_prove: list[str] | None = None
evidence_needs: list[str] | None = None
visual_needs: list[str] | None = None
seo_notes: list[str] | None = None
source_requirements: list[str] | None = None
excluded_sources: list[str] | None = None
tone: str | None = None
audience: str | None = None
risks: list[str] | None = None
class PlanRevisionRequest(ContractModel):
notes: str = Field(min_length=1)
class PlanResponse(ContractModel):
plan: PlanSummary
class PlanListResponse(ContractModel):
plans: list[PlanSummary]
class ResearchArtifactSummary(ContractModel):
artifact_type: str = Field(min_length=1)
source_url: str = Field(min_length=1)
@@ -43,7 +43,12 @@ from .models import (
DraftSummary,
EvidenceSummary,
PlanSectionSummary,
PlanSectionEditRequest,
PlanListResponse,
PlanResponse,
PlanRevisionRequest,
PlanSummary,
PlanUpdateRequest,
PublishCommitSummary,
PublishingRules,
ResearchArtifactManifestSummary,
@@ -104,7 +109,12 @@ CONTRACT_SCHEMA_MODELS: tuple[type[BaseModel], ...] = (
BoundaryQuestionResponse,
BoundaryQuestionListResponse,
PlanSectionSummary,
PlanSectionEditRequest,
PlanSummary,
PlanUpdateRequest,
PlanRevisionRequest,
PlanResponse,
PlanListResponse,
ResearchArtifactSummary,
ResearchArtifactManifestSummary,
EvidenceSummary,
@@ -15,6 +15,9 @@ from src.domain.contracts import (
AgentJobType,
ArticleSummary,
BoundaryQuestionSummary,
PlanReviewStatus,
PlanSectionSummary,
PlanSummary,
PublishingRules,
PublishingStatus,
ArticleWorkflowStatus,
@@ -42,6 +45,7 @@ class BackendRepository:
self.target_sites = TargetSitesRepository(self)
self.articles = ArticlesRepository(self)
self.boundary_questions = BoundaryQuestionsRepository(self)
self.article_plans = ArticlePlansRepository(self)
self.agent_jobs = AgentJobsRepository(self)
self.script_config_versions = ScriptConfigVersionsRepository(self)
self.script_config_version_events = ScriptConfigVersionAuditEventsRepository(self)
@@ -750,6 +754,257 @@ class BoundaryQuestionsRepository:
return self.get(article_id=article_id, question_id=question_id)
class ArticlePlansRepository:
def __init__(self, repository: BackendRepository) -> None:
self._repository = repository
def create_version(
self,
*,
article_id: UUID,
version: int,
status: PlanReviewStatus,
title_options: list[str],
recommended_title: str | None,
reader_persona: str | None,
search_intent: str | None,
thesis: str | None,
claims_to_prove: list[str],
evidence_needs: list[str],
visual_needs: list[str],
seo_notes: list[str],
source_requirements: list[str],
excluded_sources: list[str],
tone: str | None,
audience: str | None,
risks: list[str],
sections: list[JsonObject],
created_at: datetime,
) -> PlanSummary:
plan_id = uuid4()
placeholder = self._repository.placeholder()
json_cast = self._repository.json_cast()
with self._repository.connection() as connection:
connection.execute(
f"""
INSERT INTO article_plans (
id,
article_id,
version,
status,
title_options,
recommended_title,
reader_persona,
search_intent,
thesis,
claims_to_prove,
evidence_needs,
visual_needs,
seo_notes,
source_requirements,
excluded_sources,
tone,
audience,
risks,
created_at
)
VALUES (
{placeholder},
{placeholder},
{placeholder},
{placeholder},
{placeholder}{json_cast},
{placeholder},
{placeholder},
{placeholder},
{placeholder},
{placeholder}{json_cast},
{placeholder}{json_cast},
{placeholder}{json_cast},
{placeholder}{json_cast},
{placeholder}{json_cast},
{placeholder}{json_cast},
{placeholder},
{placeholder},
{placeholder}{json_cast},
{placeholder}
)
""",
(
str(plan_id),
str(article_id),
version,
status.value,
_json_value(title_options),
recommended_title,
reader_persona,
search_intent,
thesis,
_json_value(claims_to_prove),
_json_value(evidence_needs),
_json_value(visual_needs),
_json_value(seo_notes),
_json_value(source_requirements),
_json_value(excluded_sources),
tone,
audience,
_json_value(risks),
_datetime_value(created_at),
),
)
for index, section in enumerate(sections, start=1):
connection.execute(
f"""
INSERT INTO plan_sections (
id,
article_plan_id,
sort_order,
heading,
purpose,
key_points,
evidence_needs,
claims_to_support,
target_word_count
)
VALUES (
{placeholder},
{placeholder},
{placeholder},
{placeholder},
{placeholder},
{placeholder}{json_cast},
{placeholder}{json_cast},
{placeholder}{json_cast},
{placeholder}
)
""",
(
str(uuid4()),
str(plan_id),
index,
section["heading"],
section.get("purpose"),
_json_value(section.get("key_points", [])),
_json_value(section.get("evidence_needs", [])),
_json_value(section.get("claims_to_support", [])),
section.get("target_word_count"),
),
)
return self.get(article_id=article_id, plan_id=plan_id)
def list_for_article(self, article_id: UUID) -> list[PlanSummary]:
placeholder = self._repository.placeholder()
with self._repository.connection() as connection:
rows = connection.execute(
f"""
SELECT {self._select_columns()}
FROM article_plans
WHERE article_id = {placeholder}
ORDER BY version
""",
(str(article_id),),
).fetchall()
return [self._with_sections(row) for row in rows]
def get(self, *, article_id: UUID, plan_id: UUID) -> PlanSummary:
placeholder = self._repository.placeholder()
with self._repository.connection() as connection:
row = connection.execute(
f"""
SELECT {self._select_columns()}
FROM article_plans
WHERE article_id = {placeholder} AND id = {placeholder}
""",
(str(article_id), str(plan_id)),
).fetchone()
if row is None:
raise LookupError(f"Plan not found: {plan_id}")
return self._with_sections(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_plans
WHERE article_id = {placeholder}
""",
(str(article_id),),
).fetchone()
return int(_row_value(row, "version"))
def update_status(
self,
*,
article_id: UUID,
plan_id: UUID,
status: PlanReviewStatus,
) -> PlanSummary:
placeholder = self._repository.placeholder()
with self._repository.connection() as connection:
connection.execute(
f"""
UPDATE article_plans
SET status = {placeholder}
WHERE article_id = {placeholder} AND id = {placeholder}
""",
(status.value, str(article_id), str(plan_id)),
)
return self.get(article_id=article_id, plan_id=plan_id)
def _with_sections(self, row: Any) -> PlanSummary:
plan_id = _row_value(row, "id")
placeholder = self._repository.placeholder()
with self._repository.connection() as connection:
section_rows = connection.execute(
f"""
SELECT
id,
article_plan_id,
sort_order,
heading,
purpose,
key_points,
evidence_needs,
claims_to_support,
target_word_count
FROM plan_sections
WHERE article_plan_id = {placeholder}
ORDER BY sort_order
""",
(str(plan_id),),
).fetchall()
return _plan_summary_from_row(row, [_plan_section_from_row(item) for item in section_rows])
def _select_columns(self) -> str:
return """
id,
article_id,
version,
status,
title_options,
recommended_title,
reader_persona,
search_intent,
thesis,
claims_to_prove,
evidence_needs,
visual_needs,
seo_notes,
source_requirements,
excluded_sources,
tone,
audience,
risks,
created_at
"""
class AgentJobsRepository:
def __init__(self, repository: BackendRepository) -> None:
self._repository = repository
@@ -1418,6 +1673,48 @@ def _boundary_question_from_row(row: Any) -> BoundaryQuestionSummary:
)
def _plan_section_from_row(row: Any) -> PlanSectionSummary:
return PlanSectionSummary(
id=_row_value(row, "id"),
article_plan_id=_row_value(row, "article_plan_id"),
sort_order=_row_value(row, "sort_order"),
heading=_row_value(row, "heading"),
purpose=_row_value(row, "purpose"),
key_points=_json_from_row(row, "key_points"),
evidence_needs=_json_from_row(row, "evidence_needs"),
claims_to_support=_json_from_row(row, "claims_to_support"),
target_word_count=_row_value(row, "target_word_count"),
)
def _plan_summary_from_row(
row: Any,
sections: list[PlanSectionSummary],
) -> PlanSummary:
return PlanSummary(
id=_row_value(row, "id"),
article_id=_row_value(row, "article_id"),
version=_row_value(row, "version"),
status=_row_value(row, "status"),
title_options=_json_from_row(row, "title_options"),
recommended_title=_row_value(row, "recommended_title"),
reader_persona=_row_value(row, "reader_persona"),
search_intent=_row_value(row, "search_intent"),
thesis=_row_value(row, "thesis"),
sections=sections,
claims_to_prove=_json_from_row(row, "claims_to_prove"),
evidence_needs=_json_from_row(row, "evidence_needs"),
visual_needs=_json_from_row(row, "visual_needs"),
seo_notes=_json_from_row(row, "seo_notes"),
source_requirements=_json_from_row(row, "source_requirements"),
excluded_sources=_json_from_row(row, "excluded_sources"),
tone=_row_value(row, "tone"),
audience=_row_value(row, "audience"),
risks=_json_from_row(row, "risks"),
created_at=_row_value(row, "created_at"),
)
def _agent_job_summary_from_row(row: Any) -> AgentJobSummary:
return AgentJobSummary(
id=_row_value(row, "id"),
+33
View File
@@ -132,15 +132,33 @@ POSTGRES_SCHEMA_STATEMENTS: tuple[str, ...] = (
article_id UUID NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
version INTEGER NOT NULL,
status TEXT NOT NULL CHECK (status IN ({PLAN_REVIEW_STATUS_VALUES})),
title_options JSONB NOT NULL DEFAULT '[]'::jsonb,
recommended_title TEXT,
reader_persona TEXT,
search_intent TEXT,
thesis TEXT,
claims_to_prove JSONB NOT NULL DEFAULT '[]'::jsonb,
evidence_needs JSONB NOT NULL DEFAULT '[]'::jsonb,
visual_needs JSONB NOT NULL DEFAULT '[]'::jsonb,
seo_notes JSONB NOT NULL DEFAULT '[]'::jsonb,
source_requirements JSONB NOT NULL DEFAULT '[]'::jsonb,
excluded_sources JSONB NOT NULL DEFAULT '[]'::jsonb,
tone TEXT,
audience TEXT,
risks JSONB NOT NULL DEFAULT '[]'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (article_id, version)
)
""",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS title_options JSONB NOT NULL DEFAULT '[]'::jsonb",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS reader_persona TEXT",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS evidence_needs JSONB NOT NULL DEFAULT '[]'::jsonb",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS visual_needs JSONB NOT NULL DEFAULT '[]'::jsonb",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS seo_notes JSONB NOT NULL DEFAULT '[]'::jsonb",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS source_requirements JSONB NOT NULL DEFAULT '[]'::jsonb",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS excluded_sources JSONB NOT NULL DEFAULT '[]'::jsonb",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS tone TEXT",
"ALTER TABLE article_plans ADD COLUMN IF NOT EXISTS audience TEXT",
"""
CREATE TABLE IF NOT EXISTS plan_sections (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -148,11 +166,15 @@ POSTGRES_SCHEMA_STATEMENTS: tuple[str, ...] = (
sort_order INTEGER NOT NULL,
heading TEXT NOT NULL,
purpose TEXT,
key_points JSONB NOT NULL DEFAULT '[]'::jsonb,
evidence_needs JSONB NOT NULL DEFAULT '[]'::jsonb,
claims_to_support JSONB NOT NULL DEFAULT '[]'::jsonb,
target_word_count INTEGER,
UNIQUE (article_plan_id, sort_order)
)
""",
"ALTER TABLE plan_sections ADD COLUMN IF NOT EXISTS key_points JSONB NOT NULL DEFAULT '[]'::jsonb",
"ALTER TABLE plan_sections ADD COLUMN IF NOT EXISTS evidence_needs JSONB NOT NULL DEFAULT '[]'::jsonb",
"""
CREATE TABLE IF NOT EXISTS evidence_items (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -430,10 +452,19 @@ SQLITE_SCHEMA_STATEMENTS: tuple[str, ...] = (
article_id TEXT NOT NULL,
version INTEGER NOT NULL,
status TEXT NOT NULL,
title_options TEXT NOT NULL DEFAULT '[]',
recommended_title TEXT,
reader_persona TEXT,
search_intent TEXT,
thesis TEXT,
claims_to_prove TEXT NOT NULL DEFAULT '[]',
evidence_needs TEXT NOT NULL DEFAULT '[]',
visual_needs TEXT NOT NULL DEFAULT '[]',
seo_notes TEXT NOT NULL DEFAULT '[]',
source_requirements TEXT NOT NULL DEFAULT '[]',
excluded_sources TEXT NOT NULL DEFAULT '[]',
tone TEXT,
audience TEXT,
risks TEXT NOT NULL DEFAULT '[]',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (article_id, version)
@@ -446,6 +477,8 @@ SQLITE_SCHEMA_STATEMENTS: tuple[str, ...] = (
sort_order INTEGER NOT NULL,
heading TEXT NOT NULL,
purpose TEXT,
key_points TEXT NOT NULL DEFAULT '[]',
evidence_needs TEXT NOT NULL DEFAULT '[]',
claims_to_support TEXT NOT NULL DEFAULT '[]',
target_word_count INTEGER,
UNIQUE (article_plan_id, sort_order)
+2
View File
@@ -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.plans import router as plans_router
from src.presentation.routes.sites import router as sites_router
@@ -19,6 +20,7 @@ app = FastAPI(title="AI Content Pipeline Backend")
app.include_router(auth_router)
app.include_router(articles_router)
app.include_router(boundary_questions_router)
app.include_router(plans_router)
app.include_router(agent_jobs_router)
app.include_router(internal_agent_jobs_router)
app.include_router(sites_router)
@@ -8,7 +8,6 @@ from src.application.articles import (
create_article,
get_article_detail,
list_articles,
build_placeholder_plan_approval_response,
)
from src.domain.auth import EDITOR_OR_ADMIN_ROLES
from src.domain.contracts import (
@@ -17,7 +16,6 @@ from src.domain.contracts import (
ArticleDetailResponse,
ArticleListResponse,
CurrentUser,
ReviewActionResponse,
)
from src.infrastructure.repositories import BackendRepository
from src.presentation.dependencies import get_repository, require_roles
@@ -73,19 +71,3 @@ def get_article(
status_code=status.HTTP_404_NOT_FOUND,
detail="Not Found",
) from error
@router.post(
"/articles/{article_id}/plans/{plan_id}/approve",
response_model=ReviewActionResponse,
)
def approve_plan(
article_id: UUID,
plan_id: UUID,
current_user: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
) -> ReviewActionResponse:
return build_placeholder_plan_approval_response(
article_id=article_id,
plan_id=plan_id,
reviewer_id=current_user.id,
)
@@ -0,0 +1,159 @@
from __future__ import annotations
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status
from src.application.plans import (
approve_plan,
edit_plan,
generate_plan,
get_plan,
list_plans,
request_plan_revision,
start_research,
)
from src.domain.auth import EDITOR_OR_ADMIN_ROLES
from src.domain.contracts import (
AgentJobListResponse,
CurrentUser,
PlanListResponse,
PlanResponse,
PlanRevisionRequest,
PlanUpdateRequest,
ReviewActionResponse,
)
from src.infrastructure.repositories import BackendRepository
from src.presentation.dependencies import get_repository, require_roles
router = APIRouter(prefix="/api", tags=["plans"])
@router.post(
"/articles/{article_id}/plan/generate",
response_model=PlanResponse,
status_code=status.HTTP_201_CREATED,
)
def post_generate_plan(
article_id: UUID,
current_user: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
repository: BackendRepository = Depends(get_repository),
) -> PlanResponse:
try:
return generate_plan(repository, article_id=article_id, current_user=current_user)
except LookupError as error:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
except PermissionError as error:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error)) from error
@router.get("/articles/{article_id}/plans", response_model=PlanListResponse)
def get_plans(
article_id: UUID,
_: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
repository: BackendRepository = Depends(get_repository),
) -> PlanListResponse:
try:
return list_plans(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}/plans/{plan_id}", response_model=PlanResponse)
def get_plan_route(
article_id: UUID,
plan_id: UUID,
_: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
repository: BackendRepository = Depends(get_repository),
) -> PlanResponse:
try:
return get_plan(repository, article_id=article_id, plan_id=plan_id)
except LookupError as error:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
@router.patch(
"/articles/{article_id}/plans/{plan_id}",
response_model=PlanResponse,
status_code=status.HTTP_201_CREATED,
)
def patch_plan(
article_id: UUID,
plan_id: UUID,
request: PlanUpdateRequest,
current_user: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
repository: BackendRepository = Depends(get_repository),
) -> PlanResponse:
try:
return edit_plan(
repository,
article_id=article_id,
plan_id=plan_id,
request=request,
current_user=current_user,
)
except LookupError as error:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
@router.post(
"/articles/{article_id}/plans/{plan_id}/approve",
response_model=ReviewActionResponse,
)
def post_approve_plan(
article_id: UUID,
plan_id: UUID,
current_user: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
repository: BackendRepository = Depends(get_repository),
) -> ReviewActionResponse:
try:
return approve_plan(
repository,
article_id=article_id,
plan_id=plan_id,
current_user=current_user,
)
except LookupError as error:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
@router.post(
"/articles/{article_id}/plans/{plan_id}/request-revision",
response_model=ReviewActionResponse,
)
def post_request_plan_revision(
article_id: UUID,
plan_id: UUID,
request: PlanRevisionRequest,
current_user: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
repository: BackendRepository = Depends(get_repository),
) -> ReviewActionResponse:
try:
return request_plan_revision(
repository,
article_id=article_id,
plan_id=plan_id,
request=request,
current_user=current_user,
)
except LookupError as error:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") from error
@router.post(
"/articles/{article_id}/research/start",
response_model=AgentJobListResponse,
status_code=status.HTTP_202_ACCEPTED,
)
def post_start_research(
article_id: UUID,
_: CurrentUser = Depends(require_roles(EDITOR_OR_ADMIN_ROLES)),
repository: BackendRepository = Depends(get_repository),
) -> AgentJobListResponse:
try:
return start_research(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 as error:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error)) from error