"""refresh compound goal assumption prompt Revision ID: 20260516_agent_compound_goal_assumption Revises: 20260516_agent_hypothesis_competition Create Date: 2026-05-16 """ from __future__ import annotations import os from typing import Any from alembic import op import sqlalchemy as sa revision = "20260516_agent_compound_goal_assumption" down_revision = "20260516_agent_hypothesis_competition" branch_labels = None depends_on = None PROMPT_KEYS = ( "PROMPT_PMFLOW_AI_AGENT_GOAL_FRAME", "PROMPT_PMFLOW_AI_AGENT_STEP_PLANNER", ) REFRESH_NOTES = "Refreshed by 20260516_agent_compound_goal_assumption" def _table_exists(bind: Any, table_name: str) -> bool: return sa.inspect(bind).has_table(table_name) def _prompt_body(prompt_key: str) -> str: from app.config import ai_prompts return str(getattr(ai_prompts, prompt_key, "") or "").strip() def _refresh_active_prompt(bind: Any, *, tenant_id: int, prompt_key: str, body_snapshot: str) -> None: active = bind.execute( sa.text( """ SELECT id, body_snapshot FROM prompt_releases WHERE tenant_id = :tenant_id AND prompt_key = :prompt_key AND status = 'active' LIMIT 1 """ ), {"tenant_id": tenant_id, "prompt_key": prompt_key}, ).mappings().first() if active is not None and str(active.get("body_snapshot") or "").strip() == body_snapshot: return bind.execute( sa.text( """ UPDATE prompt_releases SET status = 'archived' WHERE tenant_id = :tenant_id AND prompt_key = :prompt_key AND status = 'active' """ ), {"tenant_id": tenant_id, "prompt_key": prompt_key}, ) max_version = bind.execute( sa.text( """ SELECT MAX(version) FROM prompt_releases WHERE tenant_id = :tenant_id AND prompt_key = :prompt_key """ ), {"tenant_id": tenant_id, "prompt_key": prompt_key}, ).scalar() bind.execute( sa.text( """ INSERT INTO prompt_releases (tenant_id, prompt_key, version, body_snapshot, status, notes, created_by, activated_by, activated_at) VALUES (:tenant_id, :prompt_key, :version, :body_snapshot, 'active', :notes, NULL, NULL, :activated_at) """ ), { "tenant_id": tenant_id, "prompt_key": prompt_key, "version": int(max_version or 0) + 1, "body_snapshot": body_snapshot, "notes": REFRESH_NOTES, "activated_at": "2026-05-16T00:00:00", }, ) def upgrade() -> None: bind = op.get_bind() if not _table_exists(bind, "prompt_releases"): return tenant_id = int(os.getenv("PMFLOW_PLATFORM_RUNTIME_TENANT_ID", "1") or "1") for prompt_key in PROMPT_KEYS: body_snapshot = _prompt_body(prompt_key) if body_snapshot: _refresh_active_prompt(bind, tenant_id=tenant_id, prompt_key=prompt_key, body_snapshot=body_snapshot) def downgrade() -> None: bind = op.get_bind() if not _table_exists(bind, "prompt_releases"): return tenant_id = int(os.getenv("PMFLOW_PLATFORM_RUNTIME_TENANT_ID", "1") or "1") bind.execute( sa.text( """ DELETE FROM prompt_releases WHERE tenant_id = :tenant_id AND notes = :notes """ ), {"tenant_id": tenant_id, "notes": REFRESH_NOTES}, )