初始化

This commit is contained in:
gozeros committed 2026-09-07 18:24:55 +08:00
1 parent 34474bd5fc
commit b638b541d0
3008 files changed
+837699

No files matched your search

@@ -0,0 +1,38 @@
[alembic]
script_location = %(here)s
# Default URL for offline mode / autogenerate.
# Runtime uses engine from DeerFlow config.
sqlalchemy.url = sqlite+aiosqlite:///./data/deerflow.db
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
@@ -0,0 +1,84 @@
"""Alembic environment for DeerFlow application tables.
ONLY manages DeerFlow's tables (runs, threads_meta, cron_jobs, users).
LangGraph's checkpointer tables are managed by LangGraph itself -- they
have their own schema lifecycle and must not be touched by Alembic.
"""
from __future__ import annotations
import asyncio
import logging
import os
from logging.config import fileConfig
from alembic import context
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
from deerflow.persistence.base import Base
# Import all models so metadata is populated.
try:
import deerflow.persistence.models as models # register ORM models with Base.metadata
_ = models
except ImportError:
# Models not available — migration will work with existing metadata only.
logging.getLogger(__name__).warning("Could not import deerflow.persistence.models; Alembic may not detect all tables")
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
render_as_batch=True,
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection):
render_as_batch = connection.dialect.name == "sqlite"
# On MySQL, shrink the session lock waits so a blocked DDL fails fast
# instead of hanging on the server default (lock_wait_timeout = 31536000s
# = 1 year; innodb_lock_wait_timeout = 50s). Without this, an idle
# transaction on another connection can freeze startup indefinitely.
# Tunable via DEER_FLOW_ALEMBIC_LOCK_WAIT (seconds, default 15).
if connection.dialect.name == "mysql":
try:
lock_wait = int(os.getenv("DEER_FLOW_ALEMBIC_LOCK_WAIT", "15"))
except ValueError:
lock_wait = 15
connection.execute(text(f"SET SESSION lock_wait_timeout = {lock_wait}"))
connection.execute(text(f"SET SESSION innodb_lock_wait_timeout = {lock_wait}"))
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=render_as_batch, # Required for SQLite ALTER TABLE support
)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
connectable = create_async_engine(config.get_main_option("sqlalchemy.url"))
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())
@@ -0,0 +1,35 @@
"""Add archived result to scheduled task runs.
Revision ID: 20260512_01
Revises:
Create Date: 2026-05-12
"""
from __future__ import annotations
from alembic import op
from sqlalchemy import inspect
import sqlalchemy as sa
from deerflow.persistence.types import PortableJSON
revision = "20260512_01"
down_revision = None
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
return any(column["name"] == column_name for column in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_column("scheduled_task_runs", "result_json"):
op.add_column("scheduled_task_runs", sa.Column("result_json", PortableJSON(), nullable=True))
def downgrade() -> None:
if _has_column("scheduled_task_runs", "result_json"):
op.drop_column("scheduled_task_runs", "result_json")
@@ -0,0 +1,36 @@
"""Add element_room_id to scheduled task delivery profiles.
Revision ID: 20260512_02
Revises: 20260512_01
Create Date: 2026-05-12
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260512_02"
down_revision = "20260512_01"
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
return any(column["name"] == column_name for column in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_column("scheduled_task_delivery_profiles", "element_room_id"):
op.add_column(
"scheduled_task_delivery_profiles",
sa.Column("element_room_id", sa.String(256), nullable=True),
)
def downgrade() -> None:
if _has_column("scheduled_task_delivery_profiles", "element_room_id"):
op.drop_column("scheduled_task_delivery_profiles", "element_room_id")
@@ -0,0 +1,47 @@
"""Create agents table.
Revision ID: 20260513_01
Revises: 20260512_02
Create Date: 2026-05-13
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260513_01"
down_revision = "20260512_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("agents"):
return
op.create_table(
"agents",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("name", sa.String(191), nullable=False),
sa.Column("description", sa.String(1024), nullable=False, server_default=""),
sa.Column("user_id", sa.String(64), nullable=True),
sa.Column("published", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_agents_name", "agents", ["name"])
op.create_index("ix_agents_user_id", "agents", ["user_id"])
op.create_index("ix_agents_published", "agents", ["published"])
def downgrade() -> None:
if _has_table("agents"):
op.drop_table("agents")
@@ -0,0 +1,66 @@
"""Publish/subscribe support for scheduled tasks.
Revision ID: 20260513_02
Revises: 20260513_01
Create Date: 2026-05-13
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260513_02"
down_revision = "20260513_01"
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
return any(column["name"] == column_name for column in inspector.get_columns(table_name))
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if not _has_column("scheduled_tasks", "published"):
op.add_column(
"scheduled_tasks",
sa.Column("published", sa.Boolean(), nullable=False, server_default=sa.false()),
)
op.create_index("ix_scheduled_tasks_published", "scheduled_tasks", ["published"])
if not _has_column("scheduled_tasks", "published_at"):
op.add_column(
"scheduled_tasks",
sa.Column("published_at", sa.DateTime(timezone=True), nullable=True),
)
if not _has_table("scheduled_task_subscriptions"):
op.create_table(
"scheduled_task_subscriptions",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("task_id", sa.String(64), nullable=False),
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column("notify_element", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("task_id", "user_id", name="uq_scheduled_task_subscriptions_task_user"),
)
op.create_index("ix_scheduled_task_subscriptions_task_id", "scheduled_task_subscriptions", ["task_id"])
op.create_index("ix_scheduled_task_subscriptions_user_id", "scheduled_task_subscriptions", ["user_id"])
def downgrade() -> None:
if _has_table("scheduled_task_subscriptions"):
op.drop_table("scheduled_task_subscriptions")
if _has_column("scheduled_tasks", "published_at"):
op.drop_column("scheduled_tasks", "published_at")
if _has_column("scheduled_tasks", "published"):
op.drop_index("ix_scheduled_tasks_published", table_name="scheduled_tasks")
op.drop_column("scheduled_tasks", "published")
@@ -0,0 +1,44 @@
"""Create recommended_questions table.
Revision ID: 20260514_01
Revises: 20260513_02
Create Date: 2026-05-14
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260514_01"
down_revision = "20260513_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("recommended_questions"):
return
op.create_table(
"recommended_questions",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("title", sa.String(256), nullable=False),
sa.Column("content", sa.Text(), nullable=False),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_recommended_questions_sort_order", "recommended_questions", ["sort_order"])
def downgrade() -> None:
if _has_table("recommended_questions"):
op.drop_table("recommended_questions")
@@ -0,0 +1,59 @@
"""Create llm_call_metrics table.
Revision ID: 20260514_02
Revises: 20260514_01
Create Date: 2026-05-14
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260514_02"
down_revision = "20260514_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("llm_call_metrics"):
return
op.create_table(
"llm_call_metrics",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("user_id", sa.String(64), nullable=True),
sa.Column("thread_id", sa.String(64), nullable=True),
sa.Column("run_id", sa.String(64), nullable=True),
sa.Column("agent_name", sa.String(128), nullable=True),
sa.Column("model_name", sa.String(128), nullable=True),
sa.Column("duration_ms", sa.Integer(), nullable=False, server_default="0"),
sa.Column("input_tokens", sa.Integer(), nullable=True),
sa.Column("output_tokens", sa.Integer(), nullable=True),
sa.Column("total_tokens", sa.Integer(), nullable=True),
sa.Column("tokens_per_sec", sa.Float(), nullable=True),
sa.Column("status", sa.String(16), nullable=False, server_default="success"),
sa.Column("error_type", sa.String(64), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
)
op.create_index("ix_llm_call_metrics_created_at", "llm_call_metrics", ["created_at"])
op.create_index("ix_llm_call_metrics_user_id", "llm_call_metrics", ["user_id"])
op.create_index("ix_llm_call_metrics_model_name", "llm_call_metrics", ["model_name"])
op.create_index("ix_llm_call_metrics_status", "llm_call_metrics", ["status"])
op.create_index("ix_llm_call_metrics_thread_id", "llm_call_metrics", ["thread_id"])
op.create_index("ix_llm_call_metrics_run_id", "llm_call_metrics", ["run_id"])
op.create_index("ix_llm_call_metrics_agent_name", "llm_call_metrics", ["agent_name"])
def downgrade() -> None:
if _has_table("llm_call_metrics"):
op.drop_table("llm_call_metrics")
@@ -0,0 +1,60 @@
"""Create tags and tag_assignments tables.
Revision ID: 20260515_01
Revises: 20260514_02
Create Date: 2026-05-15
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260515_01"
down_revision = "20260514_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if not _has_table("tags"):
op.create_table(
"tags",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("name", sa.String(159), nullable=False),
sa.Column("tag_type", sa.String(32), nullable=False),
sa.Column("color", sa.String(16), nullable=False, server_default="gray"),
sa.Column("description", sa.String(1024), nullable=False, server_default=""),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("tag_type", "name", name="uq_tags_type_name"),
)
op.create_index("ix_tags_tag_type", "tags", ["tag_type"])
if not _has_table("tag_assignments"):
op.create_table(
"tag_assignments",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("tag_id", sa.String(64), nullable=False),
sa.Column("target_type", sa.String(32), nullable=False),
sa.Column("target_id", sa.String(64), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("tag_id", "target_type", "target_id", name="uq_tag_assignments_tag_target"),
)
op.create_index("ix_tag_assignments_tag_id", "tag_assignments", ["tag_id"])
op.create_index("ix_tag_assignments_target_type", "tag_assignments", ["target_type"])
op.create_index("ix_tag_assignments_target_id", "tag_assignments", ["target_id"])
def downgrade() -> None:
if _has_table("tag_assignments"):
op.drop_table("tag_assignments")
if _has_table("tags"):
op.drop_table("tags")
@@ -0,0 +1,50 @@
"""Create ai_writing_sessions table.
Revision ID: 20260517_01
Revises: 20260515_01
Create Date: 2026-05-17
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260517_01"
down_revision = "20260515_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("ai_writing_sessions"):
return
op.create_table(
"ai_writing_sessions",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("user_id", sa.String(64), nullable=True),
sa.Column("title", sa.String(512), nullable=False, server_default=""),
sa.Column("user_intent", sa.String(512), nullable=True),
sa.Column("status", sa.String(32), nullable=False, server_default="in_progress"),
sa.Column("draft_title", sa.String(512), nullable=True),
sa.Column("draft_markdown", sa.Text, nullable=True),
sa.Column("completed_interventions", sa.Text, nullable=True),
sa.Column("review_result", sa.Text, nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_ai_writing_sessions_user_id", "ai_writing_sessions", ["user_id"])
op.create_index("ix_ai_writing_sessions_updated_at", "ai_writing_sessions", ["updated_at"])
def downgrade() -> None:
if _has_table("ai_writing_sessions"):
op.drop_table("ai_writing_sessions")
@@ -0,0 +1,117 @@
"""Create ai_writing_article_types table with default types.
Revision ID: 20260517_02
Revises: 20260517_01
Create Date: 2026-05-17
"""
from __future__ import annotations
import uuid
from datetime import UTC, datetime
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260517_02"
down_revision = "20260517_01"
branch_labels = None
depends_on = None
_DEFAULT_TYPES = [
{
"key": "news",
"label": "新闻资讯",
"description": "时效性强的新闻报道,注重事实准确、简洁客观",
"prompt_hint": "以新闻报道的风格写作,注重5W1H要素,语言简洁客观,突出时效性和事实准确性",
"default_word_count": 600,
"sort_order": 0,
},
{
"key": "analysis",
"label": "分析报道",
"description": "深入分析事件背景与影响,提供专业见解",
"prompt_hint": "以分析报道的风格写作,提供深度背景分析、多角度解读和专业见解,逻辑清晰",
"default_word_count": 1200,
"sort_order": 1,
},
{
"key": "feature",
"label": "深度特稿",
"description": "人物或事件的深度叙事,注重细节与故事性",
"prompt_hint": "以深度特稿的风格写作,注重叙事性和细节描写,人物刻画生动,故事性强,情感真实",
"default_word_count": 2000,
"sort_order": 2,
},
{
"key": "report",
"label": "调研报告",
"description": "数据驱动的专题研究报告,结构严谨",
"prompt_hint": "以调研报告的风格写作,数据详实,结构严谨(摘要/背景/发现/结论),语言专业规范",
"default_word_count": 3000,
"sort_order": 3,
},
]
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if not _has_table("ai_writing_article_types"):
op.create_table(
"ai_writing_article_types",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("key", sa.String(64), nullable=False, unique=True),
sa.Column("label", sa.String(128), nullable=False),
sa.Column("description", sa.Text, nullable=True),
sa.Column("prompt_hint", sa.Text, nullable=True),
sa.Column("default_word_count", sa.Integer, nullable=False, server_default="800"),
sa.Column("sort_order", sa.Integer, nullable=False, server_default="0"),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
# 预置默认文章类型(幂等,跳过已存在的 key)。
# 用 SQLAlchemy Core 构造而非裸 SQL:``key`` 是 MySQL 保留字,裸
# ``SELECT key`` 会触发 1064 语法错误。Core 编译器会按方言自动给保留字
# 加引号(MySQL 反引号 / Postgres 双引号),保持跨后端可移植。
article_types = sa.table(
"ai_writing_article_types",
sa.column("id", sa.String),
sa.column("key", sa.String),
sa.column("label", sa.String),
sa.column("description", sa.Text),
sa.column("prompt_hint", sa.Text),
sa.column("default_word_count", sa.Integer),
sa.column("sort_order", sa.Integer),
sa.column("created_at", sa.DateTime),
sa.column("updated_at", sa.DateTime),
)
conn = op.get_bind()
existing_keys = {row[0] for row in conn.execute(sa.select(article_types.c.key)).fetchall()}
now = datetime.now(UTC)
for t in _DEFAULT_TYPES:
if t["key"] not in existing_keys:
conn.execute(
article_types.insert().values(
id=str(uuid.uuid4()),
key=t["key"],
label=t["label"],
description=t["description"],
prompt_hint=t["prompt_hint"],
default_word_count=t["default_word_count"],
sort_order=t["sort_order"],
created_at=now,
updated_at=now,
)
)
def downgrade() -> None:
if _has_table("ai_writing_article_types"):
op.drop_table("ai_writing_article_types")
@@ -0,0 +1,39 @@
"""Add transcript column to ai_writing_sessions.
存储前端组装的完整对话时间线(progressEvents + completedInterventions),
供历史会话回显出与实时对话一致的富时间线。
Revision ID: 20260517_03
Revises: 20260517_02
Create Date: 2026-05-17
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260517_03"
down_revision = "20260517_02"
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
if table_name not in inspector.get_table_names():
return False
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_column("ai_writing_sessions", "transcript"):
return
op.add_column("ai_writing_sessions", sa.Column("transcript", sa.Text, nullable=True))
def downgrade() -> None:
if _has_column("ai_writing_sessions", "transcript"):
op.drop_column("ai_writing_sessions", "transcript")
@@ -0,0 +1,42 @@
"""Add detail column to skills table.
Revision ID: 20260518_01
Revises: 20260515_01
Create Date: 2026-05-18
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260518_01"
down_revision = "20260515_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
# ``skills`` may not exist yet on a brand-new DB — create_all handles that
# case with the column already present, so only patch existing tables.
if _has_table("skills") and not _has_column("skills", "detail"):
op.add_column("skills", sa.Column("detail", sa.Text(), nullable=True))
def downgrade() -> None:
if _has_column("skills", "detail"):
op.drop_column("skills", "detail")
@@ -0,0 +1,53 @@
"""Create thread_shares table (per-conversation share links).
Revision ID: 20260518_02
Revises: 20260518_01
Create Date: 2026-05-18
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260518_02"
down_revision = "20260518_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_table("thread_shares"):
op.create_table(
"thread_shares",
sa.Column("share_code", sa.String(32), primary_key=True),
sa.Column("owner_user_id", sa.String(64), nullable=False),
sa.Column("thread_id", sa.String(64), nullable=False),
sa.Column("revoked", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_thread_shares_owner_user_id", "thread_shares", ["owner_user_id"])
op.create_index("ix_thread_shares_thread_id", "thread_shares", ["thread_id"])
elif not _has_column("thread_shares", "thread_id"):
# An earlier all-conversations variant of this table — add the column.
op.add_column("thread_shares", sa.Column("thread_id", sa.String(64), nullable=False, server_default=""))
op.create_index("ix_thread_shares_thread_id", "thread_shares", ["thread_id"])
def downgrade() -> None:
if _has_table("thread_shares"):
op.drop_table("thread_shares")
@@ -0,0 +1,57 @@
"""Ensure thread_shares.thread_id exists (per-conversation share links).
Standalone migration so databases that already applied an earlier
all-conversations variant of ``20260518_02`` (which had no ``thread_id``
column) get the column added. Idempotent — a no-op when the column is
already present.
Revision ID: 20260518_03
Revises: 20260518_02
Create Date: 2026-05-18
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260518_03"
down_revision = "20260518_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(ix["name"] == index_name for ix in inspector.get_indexes(table_name))
def upgrade() -> None:
if not _has_table("thread_shares"):
# Fresh database — 20260518_02 already created the table with thread_id.
return
if not _has_column("thread_shares", "thread_id"):
op.add_column("thread_shares", sa.Column("thread_id", sa.String(64), nullable=False, server_default=""))
if not _has_index("thread_shares", "ix_thread_shares_thread_id"):
op.create_index("ix_thread_shares_thread_id", "thread_shares", ["thread_id"])
def downgrade() -> None:
# Leave the column in place — dropping it would break the share feature.
pass
@@ -0,0 +1,39 @@
"""Add retry_count to scheduled_task_runs.
Tracks how many recovery attempts a run has consumed so the scheduler can
cap retries on stuck/timed-out runs.
Revision ID: 20260518_04
Revises: 20260518_03
Create Date: 2026-05-18
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260518_04"
down_revision = "20260518_03"
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
return any(column["name"] == column_name for column in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_column("scheduled_task_runs", "retry_count"):
op.add_column(
"scheduled_task_runs",
sa.Column("retry_count", sa.Integer(), nullable=False, server_default="0"),
)
def downgrade() -> None:
if _has_column("scheduled_task_runs", "retry_count"):
op.drop_column("scheduled_task_runs", "retry_count")
@@ -0,0 +1,44 @@
"""Add mode to thread_shares.
Distinguishes "import" shares (recipient copies the conversation into their
account) from "view" shares (a public, read-only static page).
Revision ID: 20260518_05
Revises: 20260518_04
Create Date: 2026-05-18
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260518_05"
down_revision = "20260518_04"
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
if table_name not in inspector.get_table_names():
return True # table missing entirely — skip (created with the column)
return any(column["name"] == column_name for column in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_column("thread_shares", "mode"):
op.add_column(
"thread_shares",
sa.Column("mode", sa.String(16), nullable=False, server_default="import"),
)
def downgrade() -> None:
inspector = inspect(op.get_bind())
if "thread_shares" in inspector.get_table_names() and any(
column["name"] == "mode" for column in inspector.get_columns("thread_shares")
):
op.drop_column("thread_shares", "mode")
@@ -0,0 +1,28 @@
"""Merge the ai-writing and thread-shares migration heads.
Two independent migration branches diverged from ``20260515_01``: the AI
writing feature (``20260517_01..03``) and the thread-shares / scheduled-task
work (``20260518_01..05``). Merging the two branches into one repo left Alembic
with multiple heads, so ``upgrade head`` failed. This is a no-op merge revision
that joins both lineages — it changes no schema.
Revision ID: 20260518_06
Revises: 20260517_03, 20260518_05
Create Date: 2026-05-18
"""
from __future__ import annotations
revision = "20260518_06"
down_revision = ("20260517_03", "20260518_05")
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -0,0 +1,58 @@
"""Create tool_call_metrics table.
Revision ID: 20260518_07
Revises: 20260518_06
Create Date: 2026-05-18
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260518_07"
down_revision = "20260518_06"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("tool_call_metrics"):
return
op.create_table(
"tool_call_metrics",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("user_id", sa.String(64), nullable=True),
sa.Column("thread_id", sa.String(64), nullable=True),
sa.Column("run_id", sa.String(64), nullable=True),
sa.Column("agent_name", sa.String(128), nullable=True),
sa.Column("tool_name", sa.String(128), nullable=True),
sa.Column("skill_name", sa.String(128), nullable=True),
sa.Column("duration_ms", sa.Integer(), nullable=False, server_default="0"),
sa.Column("status", sa.String(16), nullable=False, server_default="success"),
sa.Column("error_category", sa.String(32), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
)
op.create_index("ix_tool_call_metrics_created_at", "tool_call_metrics", ["created_at"])
op.create_index("ix_tool_call_metrics_user_id", "tool_call_metrics", ["user_id"])
op.create_index("ix_tool_call_metrics_thread_id", "tool_call_metrics", ["thread_id"])
op.create_index("ix_tool_call_metrics_run_id", "tool_call_metrics", ["run_id"])
op.create_index("ix_tool_call_metrics_agent_name", "tool_call_metrics", ["agent_name"])
op.create_index("ix_tool_call_metrics_tool_name", "tool_call_metrics", ["tool_name"])
op.create_index("ix_tool_call_metrics_skill_name", "tool_call_metrics", ["skill_name"])
op.create_index("ix_tool_call_metrics_status", "tool_call_metrics", ["status"])
op.create_index("ix_tool_call_metrics_error_category", "tool_call_metrics", ["error_category"])
def downgrade() -> None:
if _has_table("tool_call_metrics"):
op.drop_table("tool_call_metrics")
@@ -0,0 +1,62 @@
"""Add skill_name column to tool_call_metrics.
``tool_call_metrics`` is created by ``create_all`` at startup. On deployments
where the table was materialised *before* the ``skill_name`` column existed,
neither ``create_all`` (it never ALTERs) nor revision ``20260518_07`` (it skips
when the table already exists) adds the column — leaving MySQL/Postgres with a
schema that the ORM model expects a column it does not have. This revision
patches the existing table.
Revision ID: 20260519_01
Revises: 20260518_07
Create Date: 2026-05-19
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260519_01"
down_revision = "20260518_07"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name))
def upgrade() -> None:
# Brand-new DBs: the table is created with the column already present
# (by create_all / revision 20260518_07) — nothing to patch.
if not _has_table("tool_call_metrics"):
return
if not _has_column("tool_call_metrics", "skill_name"):
op.add_column("tool_call_metrics", sa.Column("skill_name", sa.String(128), nullable=True))
if not _has_index("tool_call_metrics", "ix_tool_call_metrics_skill_name"):
op.create_index("ix_tool_call_metrics_skill_name", "tool_call_metrics", ["skill_name"])
def downgrade() -> None:
if _has_index("tool_call_metrics", "ix_tool_call_metrics_skill_name"):
op.drop_index("ix_tool_call_metrics_skill_name", table_name="tool_call_metrics")
if _has_column("tool_call_metrics", "skill_name"):
op.drop_column("tool_call_metrics", "skill_name")
@@ -0,0 +1,64 @@
"""Widen ai_writing_sessions.transcript to LONGTEXT on MySQL.
The ``transcript`` column stores the full AI-writing conversation timeline as a
JSON blob. It was originally created as ``TEXT``, which on MySQL caps at 64 KB —
a transcript with many progress events overflows it and the save endpoint
returns HTTP 500. This revision widens the column to ``LONGTEXT`` (4 GB) on
MySQL. SQLite/PostgreSQL ``TEXT`` is already unbounded, so they are left as-is.
Revision ID: 20260519_02
Revises: 20260519_01
Create Date: 2026-05-19
"""
from __future__ import annotations
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260519_02"
down_revision = "20260519_01"
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
if table_name not in inspector.get_table_names():
return False
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
bind = op.get_bind()
# Only MySQL has the 64 KB TEXT limit; other backends need no change.
if bind.dialect.name != "mysql":
return
if not _has_column("ai_writing_sessions", "transcript"):
return
op.alter_column(
"ai_writing_sessions",
"transcript",
type_=LONGTEXT(),
existing_nullable=True,
)
def downgrade() -> None:
bind = op.get_bind()
if bind.dialect.name != "mysql":
return
if not _has_column("ai_writing_sessions", "transcript"):
return
# Revert to TEXT. Rows longer than 64 KB would be truncated, but downgrade
# is a developer-only path.
import sqlalchemy as sa
op.alter_column(
"ai_writing_sessions",
"transcript",
type_=sa.Text(),
existing_nullable=True,
)
@@ -0,0 +1,83 @@
"""Homepage agent selector: ``user_agent_pin`` table + ``agents.featured_order``.
Adds two pieces backing the new chat-homepage agent picker:
- ``agents.featured_order`` (nullable INT) — admin-curated featured rank.
NULL = not shown on the selector. Non-NULL rows sort ascending.
- ``user_agent_pin`` — per-user pinned agents (user's "favorites"). Composite
PK ``(user_id, agent_id)`` so a user pins each agent at most once. Foreign
key to ``agents.id`` with ``ON DELETE CASCADE`` so deleting an agent also
removes every user's pin of it.
Revision ID: 20260520_01
Revises: 20260519_02
Create Date: 2026-05-20
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260520_01"
down_revision = "20260519_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name))
def upgrade() -> None:
# 1. agents.featured_order — ALTER existing table. Skipped on brand-new DBs
# where create_all already materialised the column.
if _has_table("agents") and not _has_column("agents", "featured_order"):
op.add_column("agents", sa.Column("featured_order", sa.Integer(), nullable=True))
if _has_table("agents") and not _has_index("agents", "ix_agents_featured_order"):
op.create_index("ix_agents_featured_order", "agents", ["featured_order"])
# 2. user_agent_pin — per-user pinned agents.
if not _has_table("user_agent_pin"):
op.create_table(
"user_agent_pin",
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column(
"agent_id",
sa.String(64),
sa.ForeignKey("agents.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("user_id", "agent_id", name="pk_user_agent_pin"),
)
op.create_index("ix_user_agent_pin_sort_order", "user_agent_pin", ["sort_order"])
def downgrade() -> None:
if _has_index("user_agent_pin", "ix_user_agent_pin_sort_order"):
op.drop_index("ix_user_agent_pin_sort_order", table_name="user_agent_pin")
if _has_table("user_agent_pin"):
op.drop_table("user_agent_pin")
if _has_index("agents", "ix_agents_featured_order"):
op.drop_index("ix_agents_featured_order", table_name="agents")
if _has_column("agents", "featured_order"):
op.drop_column("agents", "featured_order")
@@ -0,0 +1,66 @@
"""Widen ``agents.featured_order`` from INT to BIGINT.
The previous revision (``20260520_01``) created ``featured_order`` as plain
``INTEGER``. The frontend seeds the initial rank with ``Date.now()`` so admins
get "newest featured sinks to the bottom" with zero UI — but ms-resolution
timestamps (~1.78e12) overflow a 4-byte signed INT on MySQL, surfacing as
sqlalchemy.exc.DataError: (1264, "Out of range value for column 'featured_order'")
SQLite and PostgreSQL ``INTEGER`` is already 64-bit / arbitrary-precision and
needs no change, but the migration runs everywhere for schema parity.
Revision ID: 20260520_02
Revises: 20260520_01
Create Date: 2026-05-20
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260520_02"
down_revision = "20260520_01"
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
if table_name not in inspector.get_table_names():
return False
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_column("agents", "featured_order"):
return
bind = op.get_bind()
# SQLite has only INTEGER (dynamic precision) — alter_column would rebuild
# the table for nothing. PostgreSQL INTEGER is 32-bit too, so alter it.
if bind.dialect.name == "sqlite":
return
op.alter_column(
"agents",
"featured_order",
type_=sa.BigInteger(),
existing_nullable=True,
)
def downgrade() -> None:
if not _has_column("agents", "featured_order"):
return
bind = op.get_bind()
if bind.dialect.name == "sqlite":
return
# Any rows with values > 2^31-1 would be truncated. Downgrade is dev-only.
op.alter_column(
"agents",
"featured_order",
type_=sa.Integer(),
existing_nullable=True,
)
@@ -0,0 +1,61 @@
"""Drop ``user_agent_pin`` (homepage selector simplified to admin-only).
The original design split the homepage agent picker into two buckets:
admin-curated "featured" + per-user "pinned". Product feedback showed the
per-user side added complexity without clear value — admins now own the
single list shown to everyone. ``agents.featured_order`` is the only piece
that survives; this revision removes the now-unused pin table.
Revision ID: 20260520_03
Revises: 20260520_02
Create Date: 2026-05-20
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260520_03"
down_revision = "20260520_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name))
def upgrade() -> None:
if _has_index("user_agent_pin", "ix_user_agent_pin_sort_order"):
op.drop_index("ix_user_agent_pin_sort_order", table_name="user_agent_pin")
if _has_table("user_agent_pin"):
op.drop_table("user_agent_pin")
def downgrade() -> None:
if not _has_table("user_agent_pin"):
op.create_table(
"user_agent_pin",
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column(
"agent_id",
sa.String(64),
sa.ForeignKey("agents.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("user_id", "agent_id", name="pk_user_agent_pin"),
)
op.create_index("ix_user_agent_pin_sort_order", "user_agent_pin", ["sort_order"])
@@ -0,0 +1,44 @@
"""Create user_memory_configs table.
Replaces the per-user file-based memory config override
({base_dir}/users/{user_id}/memory_config.json) with a DB row.
Stores only hindsight.recall_budget — the single user-writable field
after the memory config simplification.
Revision ID: 20260521_01
Revises: 20260519_02
Create Date: 2026-05-21
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260521_01"
down_revision = "20260519_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("user_memory_configs"):
return
op.create_table(
"user_memory_configs",
sa.Column("user_id", sa.String(64), primary_key=True),
sa.Column("recall_budget", sa.String(16), nullable=True),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
def downgrade() -> None:
if _has_table("user_memory_configs"):
op.drop_table("user_memory_configs")
@@ -0,0 +1,24 @@
"""Merge agent pin/featured and user memory config migration heads.
Revision ID: 20260521_02
Revises: 20260520_03, 20260521_01
Create Date: 2026-05-21
"""
from __future__ import annotations
from collections.abc import Sequence
revision: str = "20260521_02"
down_revision: str | tuple[str, str] = ("20260520_03", "20260521_01")
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -0,0 +1,36 @@
"""Add description column to scheduled_tasks.
Revision ID: 20260522_01
Revises: 20260521_02
Create Date: 2026-05-22
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260522_01"
down_revision = "20260521_02"
branch_labels = None
depends_on = None
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
return any(column["name"] == column_name for column in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_column("scheduled_tasks", "description"):
op.add_column(
"scheduled_tasks",
sa.Column("description", sa.Text(), nullable=True),
)
def downgrade() -> None:
if _has_column("scheduled_tasks", "description"):
op.drop_column("scheduled_tasks", "description")
@@ -0,0 +1,62 @@
"""Add ``agents.is_private`` for the private-square (私密广场) feature.
A nullable-default bool column flagging agents that should live in the
password-gated private square instead of the regular public square.
Revision ID: 20260526_01
Revises: 20260522_01
Create Date: 2026-05-26
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260526_01"
down_revision = "20260522_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name))
def upgrade() -> None:
if _has_table("agents") and not _has_column("agents", "is_private"):
op.add_column(
"agents",
sa.Column(
"is_private",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
),
)
if _has_table("agents") and not _has_index("agents", "ix_agents_is_private"):
op.create_index("ix_agents_is_private", "agents", ["is_private"])
def downgrade() -> None:
if _has_index("agents", "ix_agents_is_private"):
op.drop_index("ix_agents_is_private", table_name="agents")
if _has_column("agents", "is_private"):
op.drop_column("agents", "is_private")
@@ -0,0 +1,45 @@
"""Add ``agent_favorites`` for the agent collection (收藏) feature.
Lets a user bookmark agents from the public square (广场) so they surface in
their "我的" tab without owning them. One row per (user, agent).
Revision ID: 20260528_01
Revises: 20260526_01
Create Date: 2026-05-28
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260528_01"
down_revision = "20260526_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if not _has_table("agent_favorites"):
op.create_table(
"agent_favorites",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column("agent_id", sa.String(64), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("user_id", "agent_id", name="uq_agent_favorites_user_agent"),
)
op.create_index("ix_agent_favorites_user_id", "agent_favorites", ["user_id"])
op.create_index("ix_agent_favorites_agent_id", "agent_favorites", ["agent_id"])
def downgrade() -> None:
if _has_table("agent_favorites"):
op.drop_table("agent_favorites")
@@ -0,0 +1,45 @@
"""Add ``user_custom_prompts`` for per-user saved prompts (常用提示词).
Bound to the user (not the browser) so prompts follow the account.
Revision ID: 20260528_02
Revises: 20260528_01
Create Date: 2026-05-28
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260528_02"
down_revision = "20260528_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if not _has_table("user_custom_prompts"):
op.create_table(
"user_custom_prompts",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column("title", sa.String(255), nullable=False, server_default=""),
sa.Column("content", sa.Text(), nullable=False),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_user_custom_prompts_user_id", "user_custom_prompts", ["user_id"])
def downgrade() -> None:
if _has_table("user_custom_prompts"):
op.drop_table("user_custom_prompts")
@@ -0,0 +1,39 @@
"""Create ``embed_sessions`` table for iframe embed status polling.
Revision ID: 20260602_01
Revises: 20260528_02
Create Date: 2026-06-02
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260602_01"
down_revision = "20260528_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if not _has_table("embed_sessions"):
op.create_table(
"embed_sessions",
sa.Column("session_id", sa.String(128), primary_key=True),
sa.Column("thread_id", sa.String(64), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_embed_sessions_thread_id", "embed_sessions", ["thread_id"])
def downgrade() -> None:
if _has_table("embed_sessions"):
op.drop_table("embed_sessions")
@@ -0,0 +1,49 @@
"""Add step3 column to roundtable_drafts.
Step 3「结果绘制」persistence: the generated report (HTML + metadata) is stored
inline in the draft so a reloaded draft can show the report without depending on
the ephemeral report thread. The column is LONGTEXT on MySQL (HTML can exceed the
64 KB TEXT cap) and plain TEXT (unbounded) elsewhere — matching ``PortableLongText``
on ``RoundtableDraftRow.step3``. ``create_all`` adds the column for brand-new DBs;
this revision patches DBs that already have the table.
Revision ID: 20260603_01
Revises: 20260602_01
Create Date: 2026-06-03
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260603_01"
down_revision = "20260602_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_drafts") and not _has_column("roundtable_drafts", "step3"):
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.add_column("roundtable_drafts", sa.Column("step3", col_type, nullable=True))
def downgrade() -> None:
if _has_column("roundtable_drafts", "step3"):
op.drop_column("roundtable_drafts", "step3")
@@ -0,0 +1,45 @@
"""Add ``agent_id`` to ``user_custom_prompts`` for per-agent prompt scoping.
NULL = global (shown for every agent); otherwise the prompt only surfaces when
that agent is selected.
Revision ID: 20260603_02
Revises: 20260603_01
Create Date: 2026-06-03
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260603_02"
down_revision = "20260603_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_table("user_custom_prompts"):
return
if not _has_column("user_custom_prompts", "agent_id"):
op.add_column("user_custom_prompts", sa.Column("agent_id", sa.String(64), nullable=True))
op.create_index("ix_user_custom_prompts_agent_id", "user_custom_prompts", ["agent_id"])
def downgrade() -> None:
if _has_table("user_custom_prompts") and _has_column("user_custom_prompts", "agent_id"):
op.drop_index("ix_user_custom_prompts_agent_id", table_name="user_custom_prompts")
op.drop_column("user_custom_prompts", "agent_id")
@@ -0,0 +1,42 @@
"""Add ``user_preferences`` for per-user UI toggles (account-bound).
Holds a single JSON blob per user — e.g. ``hide_admin_prompt_prefix`` so a user
can choose to use only their own prompts and hide the admin-configured prefix.
Revision ID: 20260603_03
Revises: 20260603_02
Create Date: 2026-06-03
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260603_03"
down_revision = "20260603_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if not _has_table("user_preferences"):
op.create_table(
"user_preferences",
sa.Column("user_id", sa.String(64), primary_key=True),
sa.Column("preferences", sa.JSON(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
def downgrade() -> None:
if _has_table("user_preferences"):
op.drop_table("user_preferences")
@@ -0,0 +1,56 @@
"""Per-user pinned agents.
Revision ID: 20260604_01
Revises: 20260603_03
Create Date: 2026-06-04
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260604_01"
down_revision = "20260603_03"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name))
def upgrade() -> None:
if not _has_table("agent_pins"):
op.create_table(
"agent_pins",
sa.Column("id", sa.String(64), nullable=False),
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column("agent_id", sa.String(64), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("user_id", "agent_id", name="uq_agent_pins_user_agent"),
)
if not _has_index("agent_pins", "ix_agent_pins_user_id"):
op.create_index("ix_agent_pins_user_id", "agent_pins", ["user_id"])
if not _has_index("agent_pins", "ix_agent_pins_agent_id"):
op.create_index("ix_agent_pins_agent_id", "agent_pins", ["agent_id"])
def downgrade() -> None:
if _has_index("agent_pins", "ix_agent_pins_agent_id"):
op.drop_index("ix_agent_pins_agent_id", table_name="agent_pins")
if _has_index("agent_pins", "ix_agent_pins_user_id"):
op.drop_index("ix_agent_pins_user_id", table_name="agent_pins")
if _has_table("agent_pins"):
op.drop_table("agent_pins")
@@ -0,0 +1,68 @@
"""Create roundtable_jobs table.
Backend background-orchestration jobs for the roundtable-planning Step 2「后台挂起」
feature: one row per server-side run of the leader→dispatch→consensus→report
pipeline. Big JSON columns (dispatch_chain / thread_ids / chain) are LONGTEXT on
MySQL (can exceed the 64 KB TEXT cap) and plain TEXT elsewhere — matching
``PortableLongText`` on ``RoundtableJobRow``. ``create_all`` adds the table for
brand-new DBs; this revision creates it on DBs that predate it.
Revision ID: 20260604_02
Revises: 20260603_01
Create Date: 2026-06-04
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260604_02"
down_revision = "20260603_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("roundtable_jobs"):
return
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.create_table(
"roundtable_jobs",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("draft_id", sa.String(64), nullable=True),
sa.Column("user_id", sa.String(64), nullable=True),
sa.Column("status", sa.String(32), nullable=False, server_default="queued"),
sa.Column("phase", sa.String(32), nullable=False, server_default="initializing"),
sa.Column("cycle", sa.Integer, nullable=False, server_default="0"),
sa.Column("dispatch_chain", long_text, nullable=True),
sa.Column("active_agent_id", sa.String(128), nullable=True),
sa.Column("consensus_percentage", sa.Integer, nullable=False, server_default="0"),
sa.Column("pending_clarification", sa.Text, nullable=True),
sa.Column("thread_ids", long_text, nullable=True),
sa.Column("coordinator_name", sa.String(128), nullable=True),
sa.Column("orchestration_mode", sa.String(16), nullable=False, server_default="recommend"),
sa.Column("chain", long_text, nullable=True),
sa.Column("error", sa.Text, nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_roundtable_jobs_draft_id", "roundtable_jobs", ["draft_id"])
op.create_index("ix_roundtable_jobs_user_id", "roundtable_jobs", ["user_id"])
op.create_index("ix_roundtable_jobs_status", "roundtable_jobs", ["status"])
op.create_index("ix_roundtable_jobs_updated_at", "roundtable_jobs", ["updated_at"])
def downgrade() -> None:
if _has_table("roundtable_jobs"):
op.drop_table("roundtable_jobs")
@@ -0,0 +1,46 @@
"""Add dialogues column to roundtable_jobs.
存研讨对话记录(leader 说明 + 各席位交付),使后台作业跑完 / 进行中用户都能看到
真实研讨内容(而非只有流程图进度)。LONGTEXT(对话可超 64 KB),匹配
``PortableLongText`` on ``RoundtableJobRow.dialogues``。
Revision ID: 20260605_01
Revises: 20260604_01
Create Date: 2026-06-05
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260605_01"
down_revision = "20260604_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_jobs") and not _has_column("roundtable_jobs", "dialogues"):
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.add_column("roundtable_jobs", sa.Column("dialogues", col_type, nullable=True))
def downgrade() -> None:
if _has_column("roundtable_jobs", "dialogues"):
op.drop_column("roundtable_jobs", "dialogues")
@@ -0,0 +1,46 @@
"""Add step3 column to roundtable_jobs.
把作业的 Step3 报告({html, generatedAt, model, summary})直接挂在 job 上,使前端
「多运行」模型(draft.step2.runs[])能从单个 job 读到完整结果(对话 + 报告)组装一个 run,
而不必依赖草稿顶层的单一 step3。LONGTEXT(HTML 可超 64 KB)。
Revision ID: 20260605_02
Revises: 20260605_01
Create Date: 2026-06-05
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260605_02"
down_revision = "20260605_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_jobs") and not _has_column("roundtable_jobs", "step3"):
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.add_column("roundtable_jobs", sa.Column("step3", col_type, nullable=True))
def downgrade() -> None:
if _has_column("roundtable_jobs", "step3"):
op.drop_column("roundtable_jobs", "step3")
@@ -0,0 +1,57 @@
"""Create roundtable_draft_shares table.
Per-draft share links for the roundtable-planning page, mirroring
``thread_shares`` but pointing at a ``roundtable_drafts`` row. ``import`` codes
copy the draft into the recipient's account; ``view`` codes back a public
read-only result-report page. ``create_all`` makes the table for brand-new DBs;
this revision patches DBs that already exist.
Revision ID: 20260606_01
Revises: 20260605_02
Create Date: 2026-06-06
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260606_01"
down_revision = "20260605_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("roundtable_draft_shares"):
return
op.create_table(
"roundtable_draft_shares",
sa.Column("share_code", sa.String(length=32), primary_key=True),
sa.Column("owner_user_id", sa.String(length=64), nullable=False),
sa.Column("draft_id", sa.String(length=64), nullable=False),
sa.Column("revoked", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("mode", sa.String(length=16), nullable=False, server_default="import"),
sa.Column("created_at", sa.DateTime(), nullable=False),
)
op.create_index(
"ix_roundtable_draft_shares_owner_user_id",
"roundtable_draft_shares",
["owner_user_id"],
)
op.create_index(
"ix_roundtable_draft_shares_draft_id",
"roundtable_draft_shares",
["draft_id"],
)
def downgrade() -> None:
if _has_table("roundtable_draft_shares"):
op.drop_table("roundtable_draft_shares")
@@ -0,0 +1,47 @@
"""Add ``agent_id`` to ``user_custom_prompts`` when the parallel branch was skipped.
Some deployments reached ``20260606_01`` via the roundtable-jobs migration branch
(``20260603_01`` → ``20260604_01`` jobs → …) without running the sibling branch
that adds ``agent_id`` (``20260603_02``). This idempotent fixup applies the
missing column for those DBs.
Revision ID: 20260607_01
Revises: 20260606_01
Create Date: 2026-06-07
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260607_01"
down_revision = "20260606_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_table("user_custom_prompts"):
return
if not _has_column("user_custom_prompts", "agent_id"):
op.add_column("user_custom_prompts", sa.Column("agent_id", sa.String(64), nullable=True))
op.create_index("ix_user_custom_prompts_agent_id", "user_custom_prompts", ["agent_id"])
def downgrade() -> None:
if _has_table("user_custom_prompts") and _has_column("user_custom_prompts", "agent_id"):
op.drop_index("ix_user_custom_prompts_agent_id", table_name="user_custom_prompts")
op.drop_column("user_custom_prompts", "agent_id")
@@ -0,0 +1,22 @@
"""Merge parallel migration branches (agent_pins + roundtable jobs fixup).
Revision ID: 20260607_02
Revises: 20260604_01, 20260607_01
Create Date: 2026-06-07
"""
from __future__ import annotations
revision = "20260607_02"
down_revision = ("20260604_01", "20260607_01")
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -0,0 +1,49 @@
"""Add stages column to roundtable_chains.
Layered orchestration (分层编排) for business chains: an optional list-of-lists of
agent_ids grouping the chain's seats into parallel stages (stages run serially).
NULL = linear chain. The column is LONGTEXT on MySQL (mirrors ``seats`` headroom)
and plain TEXT elsewhere — matching ``PortableLongText`` on
``RoundtableChainRow.stages``. ``create_all`` adds the column for brand-new DBs;
this revision patches DBs that already have the table.
Revision ID: 20260607_03
Revises: 20260607_02
Create Date: 2026-06-07
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260607_03"
down_revision = "20260607_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_chains") and not _has_column("roundtable_chains", "stages"):
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.add_column("roundtable_chains", sa.Column("stages", col_type, nullable=True))
def downgrade() -> None:
if _has_column("roundtable_chains", "stages"):
op.drop_column("roundtable_chains", "stages")
@@ -0,0 +1,85 @@
"""Create admin leaderboard daily snapshots and analytics indexes.
Revision ID: 20260608_01
Revises: 20260607_02
Create Date: 2026-06-08
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from deerflow.persistence.types import PortableJSON
revision = "20260608_01"
down_revision = "20260607_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name))
def _create_index(table_name: str, index_name: str, columns: list[str]) -> None:
if _has_table(table_name) and not _has_index(table_name, index_name):
op.create_index(index_name, table_name, columns)
def _drop_index(table_name: str, index_name: str) -> None:
if _has_table(table_name) and _has_index(table_name, index_name):
op.drop_index(index_name, table_name=table_name)
def upgrade() -> None:
if not _has_table("admin_leaderboard_daily_stats"):
op.create_table(
"admin_leaderboard_daily_stats",
sa.Column("stat_date", sa.String(10), nullable=False),
sa.Column("settings_hash", sa.String(64), nullable=False),
sa.Column("status", sa.String(16), nullable=False, server_default="ready"),
sa.Column("payload_json", PortableJSON(), nullable=True),
sa.Column("message", sa.Text(), nullable=True),
sa.Column("error", sa.Text(), nullable=True),
sa.Column("generated_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("stat_date", "settings_hash", name="pk_admin_leaderboard_daily_stats"),
)
op.create_index("ix_admin_leaderboard_daily_stats_status", "admin_leaderboard_daily_stats", ["status"])
op.create_index("ix_admin_leaderboard_daily_stats_updated_at", "admin_leaderboard_daily_stats", ["updated_at"])
_create_index("runs", "ix_runs_created_user_status", ["created_at", "user_id", "status"])
_create_index("runs", "ix_runs_user_created", ["user_id", "created_at"])
_create_index("runs", "ix_runs_thread_created", ["thread_id", "created_at"])
_create_index("tool_call_metrics", "ix_tool_call_metrics_created_user", ["created_at", "user_id"])
_create_index("tool_call_metrics", "ix_tool_call_metrics_run_created", ["run_id", "created_at"])
_create_index("llm_call_metrics", "ix_llm_call_metrics_created_user", ["created_at", "user_id"])
_create_index("llm_call_metrics", "ix_llm_call_metrics_run_created", ["run_id", "created_at"])
_create_index("threads_meta", "ix_threads_meta_created_user", ["created_at", "user_id"])
_create_index("threads_meta", "ix_threads_meta_user_created", ["user_id", "created_at"])
def downgrade() -> None:
_drop_index("threads_meta", "ix_threads_meta_user_created")
_drop_index("threads_meta", "ix_threads_meta_created_user")
_drop_index("llm_call_metrics", "ix_llm_call_metrics_run_created")
_drop_index("llm_call_metrics", "ix_llm_call_metrics_created_user")
_drop_index("tool_call_metrics", "ix_tool_call_metrics_run_created")
_drop_index("tool_call_metrics", "ix_tool_call_metrics_created_user")
_drop_index("runs", "ix_runs_thread_created")
_drop_index("runs", "ix_runs_user_created")
_drop_index("runs", "ix_runs_created_user_status")
if _has_table("admin_leaderboard_daily_stats"):
op.drop_table("admin_leaderboard_daily_stats")
@@ -0,0 +1,27 @@
"""Merge chain_stages and admin_leaderboard_daily_stats migration heads.
Two independent migrations diverged from ``20260607_02``: ``20260607_03``
(roundtable_chains.stages) and ``20260608_01`` (admin_leaderboard_daily_stats +
analytics indexes). This no-op merge revision joins both lineages so
``upgrade head`` succeeds.
Revision ID: 20260608_02
Revises: 20260607_03, 20260608_01
Create Date: 2026-06-08
"""
from __future__ import annotations
revision = "20260608_02"
down_revision = ("20260607_03", "20260608_01")
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -0,0 +1,58 @@
"""Add is_public column to roundtable_chains.
「发布」business chains: ``is_public=True`` makes a chain visible to **all
accounts** under the "公共" filter (read + select-into-roundtable only; edit /
delete stay owner-only). Defaults to ``0`` (private). ``create_all`` adds the
column for brand-new DBs; this revision patches DBs that already have the table.
Chained after the merge head ``20260608_02`` (chain_stages + leaderboard) so the
revision graph stays single-headed — otherwise ``alembic upgrade head`` aborts
with "multiple heads" and the auto-migrate on startup silently falls back to the
create_all schema (which lacks this column → 500 on list).
Revision ID: 20260608_03
Revises: 20260608_02
Create Date: 2026-06-08
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260608_03"
down_revision = "20260608_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_chains") and not _has_column("roundtable_chains", "is_public"):
op.add_column(
"roundtable_chains",
sa.Column("is_public", sa.Boolean(), nullable=False, server_default="0"),
)
op.create_index(
"ix_roundtable_chains_is_public", "roundtable_chains", ["is_public"]
)
def downgrade() -> None:
if _has_column("roundtable_chains", "is_public"):
with op.batch_alter_table("roundtable_chains") as batch:
batch.drop_index("ix_roundtable_chains_is_public")
op.drop_column("roundtable_chains", "is_public")
@@ -0,0 +1,56 @@
"""Add stage_goals column to roundtable_chains.
Per-stage goals (每阶段目标) for business chains: an optional list aligned by index
to ``stages`` where ``stage_goals[i]`` is the「本阶段目标」for ``stages[i]`` — what
that serial stage should produce / how it depends on the previous stage's output.
Injected to the coordinator dispatch prompt (and seat tasks as fallback) in dag-mode
only. NULL = no goals. The column is LONGTEXT on MySQL (mirrors ``stages`` headroom)
and plain TEXT elsewhere — matching ``PortableLongText`` on
``RoundtableChainRow.stage_goals``. ``create_all`` adds the column for brand-new DBs;
this revision patches DBs that already have the table.
Chained after ``20260608_03`` (chain is_public) so the revision graph stays
single-headed — otherwise ``alembic upgrade head`` aborts with "multiple heads" and
the auto-migrate on startup silently falls back to the create_all schema (which lacks
this column → 500 on list).
Revision ID: 20260608_04
Revises: 20260608_03
Create Date: 2026-06-08
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260608_04"
down_revision = "20260608_03"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_chains") and not _has_column("roundtable_chains", "stage_goals"):
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.add_column("roundtable_chains", sa.Column("stage_goals", col_type, nullable=True))
def downgrade() -> None:
if _has_column("roundtable_chains", "stage_goals"):
op.drop_column("roundtable_chains", "stage_goals")
@@ -0,0 +1,61 @@
"""Create parallel_agent_tasks table.
Saved runs of the standalone parallel multi-agent panel (Vue embeddable
component): task name + brief + agents snapshot + the resulting message list,
bound per user. ``brief`` / ``agents`` / ``messages`` are LONGTEXT on MySQL
(mirror ``roundtable_drafts`` headroom) and plain TEXT elsewhere — matching
``PortableLongText``. ``create_all`` builds the table for brand-new DBs; this
revision patches DBs that already exist.
Chained after ``20260608_04`` (chain stage_goals) so the revision graph stays
single-headed — otherwise ``alembic upgrade head`` aborts with "multiple heads"
and the startup auto-migrate silently falls back to the create_all schema.
Revision ID: 20260608_05
Revises: 20260608_04
Create Date: 2026-06-08
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260608_05"
down_revision = "20260608_04"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("parallel_agent_tasks"):
return
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.create_table(
"parallel_agent_tasks",
sa.Column("id", sa.String(length=64), primary_key=True, nullable=False),
sa.Column("user_id", sa.String(length=64), nullable=False),
sa.Column("title", sa.String(length=512), nullable=False, server_default=""),
sa.Column("brief", long_text, nullable=True),
sa.Column("agents", long_text, nullable=True),
sa.Column("messages", long_text, nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
)
op.create_index(
"ix_parallel_agent_tasks_user_id", "parallel_agent_tasks", ["user_id"]
)
def downgrade() -> None:
if _has_table("parallel_agent_tasks"):
op.drop_index("ix_parallel_agent_tasks_user_id", table_name="parallel_agent_tasks")
op.drop_table("parallel_agent_tasks")
@@ -0,0 +1,56 @@
"""Add coordinator_prompt column to roundtable_chains.
Per-chain「总控编排提示」: an optional free-text instruction the user writes for the
**coordinator (总控) agent** of a business chain — telling it how to dispatch / what to
do (overall orchestration strategy / style / constraints). Injected into the coordinator
per-stage dispatch prompt (``buildDagStageLeaderTask``) in **dag-mode only**. NULL = no
prompt. The column is LONGTEXT on MySQL (mirrors ``stage_goals`` headroom) and plain TEXT
elsewhere — matching ``PortableLongText`` on ``RoundtableChainRow.coordinator_prompt``.
``create_all`` adds the column for brand-new DBs; this revision patches DBs that already
have the table.
Chained after ``20260608_05`` (parallel_agent_tasks) so the revision graph stays
single-headed — otherwise ``alembic upgrade head`` aborts with "multiple heads" and the
startup auto-migrate silently falls back to the create_all schema (which lacks this
column → 500 on list).
Revision ID: 20260608_06
Revises: 20260608_05
Create Date: 2026-06-09
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260608_06"
down_revision = "20260608_05"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_chains") and not _has_column("roundtable_chains", "coordinator_prompt"):
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.add_column("roundtable_chains", sa.Column("coordinator_prompt", col_type, nullable=True))
def downgrade() -> None:
if _has_column("roundtable_chains", "coordinator_prompt"):
op.drop_column("roundtable_chains", "coordinator_prompt")
@@ -0,0 +1,42 @@
"""Add name_zh column to skills table.
Revision ID: 20260609_01
Revises: 20260608_01
Create Date: 2026-06-09
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260609_01"
down_revision = "20260608_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
# ``skills`` may not exist yet on a brand-new DB — create_all handles that
# case with the column already present, so only patch existing tables.
if _has_table("skills") and not _has_column("skills", "name_zh"):
op.add_column("skills", sa.Column("name_zh", sa.String(length=128), nullable=True))
def downgrade() -> None:
if _has_column("skills", "name_zh"):
op.drop_column("skills", "name_zh")
@@ -0,0 +1,30 @@
"""Merge the skill_name_zh and chain-stages migration heads.
Two lineages both descend from ``20260608_01`` (admin_leaderboard_daily_stats):
``20260608_02`` … ``20260608_06`` (the chain-stages / parallel-agent branch) and
``20260609_01`` (skills.name_zh), which branched directly off ``20260608_01``
instead of off the latest head. That left the graph with two heads and made
``alembic upgrade head`` fail with "Multiple head revisions are present". This
no-op merge revision joins both lineages so ``upgrade head`` resolves to a single
head again.
Revision ID: 20260609_02
Revises: 20260608_06, 20260609_01
Create Date: 2026-06-10
"""
from __future__ import annotations
revision = "20260609_02"
down_revision = ("20260608_06", "20260609_01")
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -0,0 +1,74 @@
"""Add ``agents.square_id`` and ``skills.square_id`` for the publish-square (发布广场) feature.
A nullable-default (server_default '') string column tagging which admin-
configured publish square an agent / skill is filed under. Pure organizational
category — independent of the ``published`` / ``is_private`` flags. Empty string
means "unassigned" and is resolved to the default square at read time.
Revision ID: 20260611_01
Revises: 20260609_02
Create Date: 2026-06-11
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260611_01"
down_revision = "20260609_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name))
def _add_square_id(table_name: str, index_name: str) -> None:
if _has_table(table_name) and not _has_column(table_name, "square_id"):
op.add_column(
table_name,
sa.Column(
"square_id",
sa.String(length=64),
nullable=False,
server_default="",
),
)
if _has_table(table_name) and not _has_index(table_name, index_name):
op.create_index(index_name, table_name, ["square_id"])
def _drop_square_id(table_name: str, index_name: str) -> None:
if _has_index(table_name, index_name):
op.drop_index(index_name, table_name=table_name)
if _has_column(table_name, "square_id"):
op.drop_column(table_name, "square_id")
def upgrade() -> None:
_add_square_id("agents", "ix_agents_square_id")
_add_square_id("skills", "ix_skills_square_id")
def downgrade() -> None:
_drop_square_id("skills", "ix_skills_square_id")
_drop_square_id("agents", "ix_agents_square_id")
@@ -0,0 +1,55 @@
"""Add task_id column to roundtable_drafts.
External task id (passed by the wujie-embedded roundtable drawer). When set, the
draft is keyed/shared by ``task_id`` and is no longer partitioned by ``user_id``
(read/write/delete ownership checks are relaxed for task-bound drafts — see
``sql.py``); when NULL the original per-user isolation is preserved.
``create_all`` adds the column for brand-new DBs; this revision patches DBs that
already have the table.
Note: this migration originally shared the revision id ``20260611_01`` with
``20260611_01_agents_skills_square_id`` (both branched off ``20260609_02``),
which corrupted the alembic DAG ("present more than once" + phantom heads). It
was renumbered to ``20260611_02`` and re-chained after that revision so the
history is linear and single-headed.
Revision ID: 20260611_02
Revises: 20260611_01
Create Date: 2026-06-11
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260611_02"
down_revision = "20260611_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_drafts") and not _has_column("roundtable_drafts", "task_id"):
op.add_column("roundtable_drafts", sa.Column("task_id", sa.String(128), nullable=True))
op.create_index("ix_roundtable_drafts_task_id", "roundtable_drafts", ["task_id"])
def downgrade() -> None:
if _has_column("roundtable_drafts", "task_id"):
op.drop_index("ix_roundtable_drafts_task_id", table_name="roundtable_drafts")
op.drop_column("roundtable_drafts", "task_id")
@@ -0,0 +1,47 @@
"""Add orchestration_plan column to roundtable_jobs.
后台挂起支持分层 DAG 编排(业务链并行):把前端 ``OrchestrationPlan``(stages /
阶段目标 / 总控提示词 / finalSynthesis)整份存进 job 行,驱动后端 ``_run_dag``
(stage 串行、stage 内并行)+ 前端大弹窗按 stage 分层画流程图 + resume 时重建计划。
LONGTEXT(计划 JSON 可超 64 KB)。
Revision ID: 20260612_01
Revises: 20260611_02
Create Date: 2026-06-12
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260612_01"
down_revision = "20260611_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_jobs") and not _has_column("roundtable_jobs", "orchestration_plan"):
col_type = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.add_column("roundtable_jobs", sa.Column("orchestration_plan", col_type, nullable=True))
def downgrade() -> None:
if _has_column("roundtable_jobs", "orchestration_plan"):
op.drop_column("roundtable_jobs", "orchestration_plan")
@@ -0,0 +1,50 @@
"""Add seat_mode column to roundtable_chains.
Per-chain「默认席位执行模式」: an optional short string (flash/thinking/pro/ultra, see
frontend ``lib/seat-mode.ts``) the user picks in the chain editor. When the chain is
selected into a roundtable discussion the picker defaults to it (still overridable per
run). NULL = unset → callers fall back to the default (pro). VARCHAR(16) on MySQL, plain
String elsewhere — matching ``String(16)`` on ``RoundtableChainRow.seat_mode``.
``create_all`` adds the column for brand-new DBs; the startup ``_ensure_orm_columns_sync``
sweep adds it to already-existing tables (sqlite/mysql/postgres). This revision keeps the
alembic graph consistent with the rest of the chain columns and documents the change.
Revision ID: 20260615_01
Revises: 20260612_01
Create Date: 2026-06-15
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260615_01"
down_revision = "20260612_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_chains") and not _has_column("roundtable_chains", "seat_mode"):
op.add_column("roundtable_chains", sa.Column("seat_mode", sa.String(length=16), nullable=True))
def downgrade() -> None:
if _has_column("roundtable_chains", "seat_mode"):
op.drop_column("roundtable_chains", "seat_mode")
@@ -0,0 +1,91 @@
"""岗位 (position) subscription system.
New tables ``positions`` + ``position_tag_bindings``; new column
``users.position_id``; ``origin`` / ``position_id`` on ``agent_favorites`` and
``scheduled_task_subscriptions``.
Note: the running app also auto-adds these via ``_ensure_orm_columns_sync`` and
``create_all`` on startup; this migration keeps the alembic history consistent
per the repo convention (see backend/CLAUDE.md → Schema Migrations).
Revision ID: 20260616_01
Revises: 20260612_01
Create Date: 2026-06-16
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260616_01"
down_revision = "20260612_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return any(col["name"] == column_name for col in inspect(op.get_bind()).get_columns(table_name))
def upgrade() -> None:
if not _has_table("positions"):
op.create_table(
"positions",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("name", sa.String(191), nullable=False),
sa.Column("description", sa.String(1024), nullable=False, server_default=""),
sa.Column("is_default", sa.Boolean(), nullable=False, server_default=sa.text("0")),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("name", name="uq_positions_name"),
)
op.create_index("ix_positions_is_default", "positions", ["is_default"])
if not _has_table("position_tag_bindings"):
op.create_table(
"position_tag_bindings",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("position_id", sa.String(64), nullable=False),
sa.Column("resource_type", sa.String(32), nullable=False),
sa.Column("tag_id", sa.String(64), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("position_id", "resource_type", "tag_id", name="uq_position_tag_bindings"),
)
op.create_index("ix_position_tag_bindings_position_id", "position_tag_bindings", ["position_id"])
op.create_index("ix_position_tag_bindings_resource_type", "position_tag_bindings", ["resource_type"])
op.create_index("ix_position_tag_bindings_tag_id", "position_tag_bindings", ["tag_id"])
op.create_index("ix_position_tag_bindings_position_type", "position_tag_bindings", ["position_id", "resource_type"])
if _has_table("users") and not _has_column("users", "position_id"):
op.add_column("users", sa.Column("position_id", sa.String(64), nullable=True))
op.create_index("ix_users_position_id", "users", ["position_id"])
for table in ("agent_favorites", "scheduled_task_subscriptions"):
if _has_table(table) and not _has_column(table, "origin"):
op.add_column(table, sa.Column("origin", sa.String(16), nullable=False, server_default="user"))
if _has_table(table) and not _has_column(table, "position_id"):
op.add_column(table, sa.Column("position_id", sa.String(64), nullable=True))
op.create_index(f"ix_{table}_position_id", table, ["position_id"])
def downgrade() -> None:
for table in ("agent_favorites", "scheduled_task_subscriptions"):
if _has_column(table, "position_id"):
op.drop_column(table, "position_id")
if _has_column(table, "origin"):
op.drop_column(table, "origin")
if _has_column("users", "position_id"):
op.drop_column("users", "position_id")
if _has_table("position_tag_bindings"):
op.drop_table("position_tag_bindings")
if _has_table("positions"):
op.drop_table("positions")
@@ -0,0 +1,84 @@
"""Knowledge directories + editable extraction templates.
New column ``knowledge_notes.folder``; new tables ``knowledge_folders`` and
``knowledge_extract_templates``.
Note: the running app also auto-adds the column + tables via
``_ensure_orm_columns_sync`` / ``create_all`` on startup; this migration keeps
the alembic history consistent per the repo convention (see backend/CLAUDE.md →
Schema Migrations).
Revision ID: 20260616_02
Revises: 20260616_01
Create Date: 2026-06-16
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects import mysql
revision = "20260616_02"
down_revision = "20260616_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return any(col["name"] == column_name for col in inspect(op.get_bind()).get_columns(table_name))
def upgrade() -> None:
if _has_table("knowledge_notes") and not _has_column("knowledge_notes", "folder"):
op.add_column("knowledge_notes", sa.Column("folder", sa.String(512), nullable=True))
op.create_index("ix_knowledge_notes_folder", "knowledge_notes", ["folder"], mysql_length=191)
if not _has_table("knowledge_folders"):
op.create_table(
"knowledge_folders",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("path", sa.String(512), nullable=False),
sa.Column("name", sa.String(256), nullable=False),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("created_by", sa.String(128), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("uq_knowledge_folders_path", "knowledge_folders", ["path"], unique=True, mysql_length=191)
if not _has_table("knowledge_extract_templates"):
op.create_table(
"knowledge_extract_templates",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("name", sa.String(256), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("scope", sa.String(16), nullable=False, server_default="both"),
sa.Column("system_prompt", sa.Text().with_variant(mysql.LONGTEXT(), "mysql"), nullable=False),
sa.Column("is_default", sa.Boolean(), nullable=False, server_default=sa.text("0")),
sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.text("1")),
sa.Column("created_by", sa.String(128), nullable=True),
sa.Column("updated_by", sa.String(128), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_knowledge_extract_templates_scope", "knowledge_extract_templates", ["scope"])
op.create_index("ix_knowledge_extract_templates_is_default", "knowledge_extract_templates", ["is_default"])
op.create_index("ix_knowledge_extract_templates_created_at", "knowledge_extract_templates", ["created_at"])
op.create_index("uq_knowledge_extract_templates_name", "knowledge_extract_templates", ["name"], unique=True, mysql_length=191)
def downgrade() -> None:
if _has_table("knowledge_extract_templates"):
op.drop_table("knowledge_extract_templates")
if _has_table("knowledge_folders"):
op.drop_table("knowledge_folders")
if _has_column("knowledge_notes", "folder"):
op.drop_column("knowledge_notes", "folder")
@@ -0,0 +1,45 @@
"""Add always_on (常驻/免压缩) column to skills table.
Revision ID: 20260616_03
Revises: 20260616_04
Create Date: 2026-06-16
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260616_03"
down_revision = "20260616_04"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
# ``skills`` may not exist yet on a brand-new DB — create_all handles that
# case with the column already present, so only patch existing tables.
if _has_table("skills") and not _has_column("skills", "always_on"):
op.add_column(
"skills",
sa.Column("always_on", sa.Boolean(), nullable=False, server_default="0"),
)
def downgrade() -> None:
if _has_column("skills", "always_on"):
op.drop_column("skills", "always_on")
@@ -0,0 +1,60 @@
"""我的技能 (skill favorites) table.
New table ``skill_favorites`` — the per-user "我的技能" collection, mirroring
``agent_favorites``. A 岗位 (position) materializes its skill tag bindings into
this table (``origin='position'``) so granted skills land in the member's 我的
list while the browse-all 广场 stays complete.
Note: the running app also auto-creates this table via ``create_all`` on
startup (new tables are always created, even on existing DBs); this migration
keeps the alembic history consistent per the repo convention (see
backend/CLAUDE.md → Schema Migrations).
Note: this migration originally shared the revision id ``20260616_02`` with
``20260616_02_knowledge_folders_templates`` (both branched off ``20260616_01``),
which corrupted the alembic DAG ("present more than once" + phantom heads). It
was renumbered to ``20260616_04`` and re-chained after that revision so the
history is linear and single-headed.
Revision ID: 20260616_04
Revises: 20260616_02
Create Date: 2026-06-16
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260616_04"
down_revision = "20260616_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def upgrade() -> None:
if not _has_table("skill_favorites"):
op.create_table(
"skill_favorites",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column("skill_name", sa.String(64), nullable=False),
sa.Column("origin", sa.String(16), nullable=False, server_default="user"),
sa.Column("position_id", sa.String(64), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("user_id", "skill_name", name="uq_skill_favorites_user_skill"),
)
op.create_index("ix_skill_favorites_user_id", "skill_favorites", ["user_id"])
op.create_index("ix_skill_favorites_skill_name", "skill_favorites", ["skill_name"])
op.create_index("ix_skill_favorites_position_id", "skill_favorites", ["position_id"])
def downgrade() -> None:
if _has_table("skill_favorites"):
op.drop_table("skill_favorites")
@@ -0,0 +1,30 @@
"""Merge the chain-seat-mode and skill-always-on migration heads.
Two lineages both descend from ``20260612_01`` (roundtable_jobs orchestration
plan): ``20260615_01`` (chain seat mode) branched directly off it, while the
``20260616_*`` line (positions → knowledge folders/templates → skill_favorites →
skill always_on) is the other branch. That left the graph with two heads
(``20260615_01`` and ``20260616_03``) so ``alembic upgrade head`` failed with
"Multiple head revisions are present". This no-op merge revision joins both
lineages so ``upgrade head`` resolves to a single head again.
Revision ID: 20260617_01
Revises: 20260615_01, 20260616_03
Create Date: 2026-06-17
"""
from __future__ import annotations
revision = "20260617_01"
down_revision = ("20260615_01", "20260616_03")
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -0,0 +1,79 @@
"""Separate, unpartitioned storage for taskId-deeplink roundtable 聊天记录.
Two changes:
1. New table ``roundtable_task_drafts`` — the dedicated store for roundtable
sessions opened via a taskId deep-link (无界嵌入抽屉). Keyed **only by
``task_id``** (one task → many records), never partitioned by user
(``created_by`` is audit-only). Physically separate from ``roundtable_drafts``
so personal history and task records never mix. (On a brand-new DB the table
is created by ``create_all``; this revision patches existing DBs.)
2. ``roundtable_jobs.task_id`` column — marks a background job as task-scoped so
its progress/dialogues are shared by task (read 不分权) and its final report is
written back to the ``roundtable_task_drafts`` store.
The matching data move (existing ``roundtable_drafts`` rows with a ``task_id`` →
``roundtable_task_drafts``) is a one-off, run via
``scripts/migrate_roundtable_task_drafts.py`` (alembic auto-upgrade is disabled at
runtime — see ``persistence/engine.py``).
Revision ID: 20260618_01
Revises: 20260617_01
Create Date: 2026-06-18
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260618_01"
down_revision = "20260617_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if not _has_table("roundtable_task_drafts"):
op.create_table(
"roundtable_task_drafts",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("task_id", sa.String(128), nullable=False),
sa.Column("created_by", sa.String(64), nullable=True),
sa.Column("title", sa.String(512), nullable=False, server_default=""),
sa.Column("furthest_step", sa.Integer, nullable=False, server_default="1"),
sa.Column("step1", sa.Text().with_variant(sa.dialects.mysql.LONGTEXT(), "mysql"), nullable=True),
sa.Column("step2", sa.Text().with_variant(sa.dialects.mysql.LONGTEXT(), "mysql"), nullable=True),
sa.Column("step3", sa.Text().with_variant(sa.dialects.mysql.LONGTEXT(), "mysql"), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
)
op.create_index("ix_roundtable_task_drafts_task_id", "roundtable_task_drafts", ["task_id"])
if _has_table("roundtable_jobs") and not _has_column("roundtable_jobs", "task_id"):
op.add_column("roundtable_jobs", sa.Column("task_id", sa.String(128), nullable=True))
op.create_index("ix_roundtable_jobs_task_id", "roundtable_jobs", ["task_id"])
def downgrade() -> None:
if _has_column("roundtable_jobs", "task_id"):
op.drop_index("ix_roundtable_jobs_task_id", table_name="roundtable_jobs")
op.drop_column("roundtable_jobs", "task_id")
if _has_table("roundtable_task_drafts"):
op.drop_index("ix_roundtable_task_drafts_task_id", table_name="roundtable_task_drafts")
op.drop_table("roundtable_task_drafts")
@@ -0,0 +1,70 @@
"""Create roundtable_diagnostics table.
会商全流程诊断日志(第一/二/三步 + 后台执行器 + 进程内网关各处报错与关键事件),
管理员诊断页的数据源。全局/共享,不按 user 分权。
On a brand-new DB the table is created by ``create_all``; this revision patches
existing DBs (alembic auto-upgrade is disabled at runtime — see
``persistence/engine.py`` — so operators run this / the column_additions SQL).
Revision ID: 20260619_01
Revises: 20260618_01
Create Date: 2026-06-19
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260619_01"
down_revision = "20260618_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def upgrade() -> None:
if _has_table("roundtable_diagnostics"):
return
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
op.create_table(
"roundtable_diagnostics",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("scope", sa.String(16), nullable=False, server_default="background"),
sa.Column("stage", sa.String(32), nullable=False, server_default="job"),
sa.Column("level", sa.String(16), nullable=False, server_default="info"),
sa.Column("event", sa.String(64), nullable=False, server_default=""),
sa.Column("message", sa.Text(), nullable=True),
sa.Column("detail", long_text, nullable=True),
sa.Column("job_id", sa.String(64), nullable=True),
sa.Column("draft_id", sa.String(64), nullable=True),
sa.Column("task_id", sa.String(128), nullable=True),
sa.Column("user_id", sa.String(64), nullable=True),
sa.Column("agent_id", sa.String(128), nullable=True),
sa.Column("agent_name", sa.String(255), nullable=True),
sa.Column("cycle", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
)
op.create_index("ix_roundtable_diagnostics_scope", "roundtable_diagnostics", ["scope"])
op.create_index("ix_roundtable_diagnostics_stage", "roundtable_diagnostics", ["stage"])
op.create_index("ix_roundtable_diagnostics_level", "roundtable_diagnostics", ["level"])
op.create_index("ix_roundtable_diagnostics_job_id", "roundtable_diagnostics", ["job_id"])
op.create_index("ix_roundtable_diagnostics_draft_id", "roundtable_diagnostics", ["draft_id"])
op.create_index("ix_roundtable_diagnostics_task_id", "roundtable_diagnostics", ["task_id"])
op.create_index("ix_roundtable_diagnostics_user_id", "roundtable_diagnostics", ["user_id"])
op.create_index("ix_roundtable_diagnostics_created_at", "roundtable_diagnostics", ["created_at"])
def downgrade() -> None:
if _has_table("roundtable_diagnostics"):
op.drop_table("roundtable_diagnostics")
@@ -0,0 +1,34 @@
"""Placeholder for a locally-stamped revision that never landed in git.
Some existing databases (including local sqlite) have ``alembic_version``
stamped at ``20260620_01``. That file was never committed; ``20260620_02``
(gather_first) originally revised ``20260619_01`` directly, so
``alembic upgrade head`` failed with ``Can't locate revision identified by
'20260620_01'`` and later schema patches (including ``task_buttons.login_params_json``)
never ran.
This no-op restores the missing node so those DBs can walk
``20260620_01 → 20260620_02 → … → head``. Fresh DBs at ``20260619_01`` just
pass through. ``20260620_02`` is still idempotent (``_has_column``), so a DB
that already applied gather_first under the old id is safe to re-run.
Revision ID: 20260620_01
Revises: 20260619_01
Create Date: 2026-06-20
"""
from __future__ import annotations
revision = "20260620_01"
down_revision = "20260619_01"
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -0,0 +1,54 @@
"""Add gather_first column to roundtable_chains.
Per-chain「研讨前并行取数」opt-in switch: when true, selecting the chain into a roundtable
discussion first runs one **parallel data-gathering round** over all seats (each seat only
calls its skills to fetch facts, no deliberation); the collected material is injected as
shared context into the discussion rounds, front-loading the slow skill latency in parallel
so the (possibly serial) discussion phase runs faster. Default false → existing behavior
unchanged. BOOLEAN NOT NULL DEFAULT 0, matching ``RoundtableChainRow.gather_first``.
``create_all`` adds the column for brand-new DBs; the startup ``_ensure_orm_columns_sync``
sweep adds it to already-existing tables (sqlite/mysql/postgres). This revision keeps the
alembic graph consistent with the rest of the chain columns and documents the change.
Revision ID: 20260620_02
Revises: 20260620_01
Create Date: 2026-06-20
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260620_02"
down_revision = "20260620_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_chains") and not _has_column("roundtable_chains", "gather_first"):
op.add_column(
"roundtable_chains",
sa.Column("gather_first", sa.Boolean(), nullable=False, server_default="0"),
)
def downgrade() -> None:
if _has_column("roundtable_chains", "gather_first"):
op.drop_column("roundtable_chains", "gather_first")
@@ -0,0 +1,52 @@
"""Add login_params_json column to task_buttons.
按钮管理「外部链接」按钮新增「追加登录参数」能力(与应用管理一致):``url`` 外链在
拼好地址后,可再依次追加 ``?{key}={value}``,``value`` 由前端运行时从 ``userInfo``
按 ``source`` 解析(``other`` 时取字面 ``custom_value``)。整列以 JSON 存一个
``[{key, source, custom_value}, ...]`` 列表,默认空 → 旧按钮行为不变。
ORM: ``TaskButtonRow.login_params_json = PortableJSON()``(SQLite/PG 原生 JSON,
MySQL 落 TEXT)。``create_all`` 给全新库建列;已有库由启动期
``_ensure_orm_columns_sync`` 补列。本 revision 保持 alembic 图一致并留档。
Revision ID: 20260625_01
Revises: 20260620_02
Create Date: 2026-06-25
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260625_01"
down_revision = "20260620_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("task_buttons") and not _has_column("task_buttons", "login_params_json"):
op.add_column(
"task_buttons",
sa.Column("login_params_json", sa.Text(), nullable=True),
)
def downgrade() -> None:
if _has_column("task_buttons", "login_params_json"):
op.drop_column("task_buttons", "login_params_json")
@@ -0,0 +1,61 @@
"""Add append_auth / auth_token_param / auth_name_param to task_buttons.
These back the「追加登录态」option on task-workspace jump buttons (按钮管理):
a ``url`` button can append the login token (``token``) + username (``username``)
to its external link so the target system can identify the current user.
Revision ID: 20260625_02
Revises: 20260625_01
Create Date: 2026-06-25
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260625_02"
down_revision = "20260625_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
# ``task_buttons`` may not exist yet on a brand-new DB — create_all handles
# that case with the columns already present, so only patch existing tables.
if _has_table("task_buttons"):
if not _has_column("task_buttons", "append_auth"):
op.add_column(
"task_buttons",
sa.Column("append_auth", sa.Boolean(), nullable=False, server_default="0"),
)
if not _has_column("task_buttons", "auth_token_param"):
op.add_column(
"task_buttons",
sa.Column("auth_token_param", sa.String(length=64), nullable=True, server_default="token"),
)
if not _has_column("task_buttons", "auth_name_param"):
op.add_column(
"task_buttons",
sa.Column("auth_name_param", sa.String(length=64), nullable=True, server_default="username"),
)
def downgrade() -> None:
for col in ("auth_name_param", "auth_token_param", "append_auth"):
if _has_column("task_buttons", col):
op.drop_column("task_buttons", col)
@@ -0,0 +1,54 @@
"""Add users.approved (登录白名单放行标记).
Backs the login-whitelist feature (黑名单模式): when system setting
``login_whitelist.enabled`` is on, only users an admin has explicitly
「取消放行」 (``approved=False``) are blocked; everyone else — including brand-new
accounts that have never logged in (which default to ``approved=True``) — may log
in. Admins always pass.
Existing rows are backfilled to TRUE (``server_default="1"``) so flipping the
switch on for the first time never locks out users who already had accounts.
Revision ID: 20260625_03
Revises: 20260625_02
Create Date: 2026-06-25
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260625_03"
down_revision = "20260625_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
# A brand-new DB gets the column from create_all; only patch existing tables.
if _has_table("users") and not _has_column("users", "approved"):
op.add_column(
"users",
# server_default="1" backfills existing rows to 已放行 (avoid lockout).
sa.Column("approved", sa.Boolean(), nullable=False, server_default="1"),
)
def downgrade() -> None:
if _has_column("users", "approved"):
op.drop_column("users", "approved")
@@ -0,0 +1,56 @@
"""Add users.login_password (per-account 登录口令, 明文).
Backs the 白名单管理「设置登录口令」feature: an admin assigns an individual
plaintext password to a specific account, and that account's username login
(``POST /api/v1/auth/login/username``) then requires a matching ``?password=``
(it takes precedence over the global shared-password gate). The column is
nullable — NULL/empty means "no personal password" and the account keeps the
existing shared-gate / passwordless behavior.
Stored in plaintext on purpose: the password rides in the login URL's query
string anyway, and keeping it readable lets the admin re-copy the full login
link ``…/login/<username>?password=xxxx`` at any time. The ``/users`` list that
exposes it is admin-only.
Revision ID: 20260625_04
Revises: 20260625_03
Create Date: 2026-06-27
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260625_04"
down_revision = "20260625_03"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
# A brand-new DB gets the column from create_all; only patch existing tables.
if _has_table("users") and not _has_column("users", "login_password"):
op.add_column(
"users",
sa.Column("login_password", sa.String(length=255), nullable=True),
)
def downgrade() -> None:
if _has_column("users", "login_password"):
op.drop_column("users", "login_password")
@@ -0,0 +1,90 @@
"""Stop position-granted favorites from collecting built-ins/chain seats.
Built-in agents and agents used as business-chain seats should only enter
"mine" when a user explicitly clicks the favorite action. This migration
removes historical automatic ``origin='position'`` rows for those agents while
preserving user-created favorites (``origin='user'``) and ordinary
position-granted agent favorites.
Revision ID: 20260701_01
Revises: 20260625_04
Create Date: 2026-07-01
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260701_01"
down_revision = "20260625_04"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if not (
_has_table("agent_favorites")
and _has_column("agent_favorites", "origin")
and _has_column("agent_favorites", "agent_id")
):
return
favorites = sa.table(
"agent_favorites",
sa.column("agent_id", sa.String(64)),
sa.column("origin", sa.String(16)),
)
cleanup_conditions = []
if _has_table("agents") and _has_column("agents", "user_id"):
agents = sa.table(
"agents",
sa.column("id", sa.String(64)),
sa.column("user_id", sa.String(64)),
)
cleanup_conditions.append(
favorites.c.agent_id.in_(sa.select(agents.c.id).where(agents.c.user_id.is_(None)))
)
if _has_table("roundtable_chains") and _has_column("roundtable_chains", "seats"):
chains = sa.table(
"roundtable_chains",
sa.column("seats", sa.Text()),
)
cleanup_conditions.append(
sa.select(sa.literal(1))
.select_from(chains)
.where(
sa.or_(
chains.c.seats.like(sa.literal('%"agent_id": "') + favorites.c.agent_id + sa.literal('"%')),
chains.c.seats.like(sa.literal('%"agent_id":"') + favorites.c.agent_id + sa.literal('"%')),
)
)
.exists()
)
if not cleanup_conditions:
return
op.get_bind().execute(
favorites.delete().where(
favorites.c.origin == "position",
sa.or_(*cleanup_conditions),
)
)
def downgrade() -> None:
# Data cleanup only; removed auto-grants are not reconstructable.
pass
@@ -0,0 +1,87 @@
"""Create standalone position-collaboration sessions and nodes.
The tables only index the task / intent / frozen business-chain workflow.
Conversation messages remain in LangGraph checkpoints and artifacts stay in the
existing thread artifact store, so this migration intentionally has no message
or file columns beyond lightweight snapshots and manifests.
Revision ID: 20260721_01
Revises: 20260701_01
Create Date: 2026-07-21
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260721_01"
down_revision = "20260701_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def upgrade() -> None:
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
if not _has_table("position_roundtable_sessions"):
op.create_table(
"position_roundtable_sessions",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column("external_task_id", sa.String(128), nullable=True),
sa.Column("task_snapshot", long_text, nullable=True),
sa.Column("chain_id", sa.String(64), nullable=True),
sa.Column("chain_snapshot", long_text, nullable=True),
sa.Column("intent_thread_id", sa.String(128), nullable=True),
sa.Column("intent_snapshot", long_text, nullable=True),
sa.Column("status", sa.String(32), nullable=False, server_default="intent_pending"),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
)
op.create_index("ix_position_roundtable_sessions_user_id", "position_roundtable_sessions", ["user_id"])
op.create_index(
"ix_position_roundtable_sessions_external_task_id",
"position_roundtable_sessions",
["external_task_id"],
)
op.create_index("ix_position_roundtable_sessions_chain_id", "position_roundtable_sessions", ["chain_id"])
op.create_index("ix_position_roundtable_sessions_status", "position_roundtable_sessions", ["status"])
if not _has_table("position_roundtable_nodes"):
op.create_table(
"position_roundtable_nodes",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("session_id", sa.String(64), sa.ForeignKey("position_roundtable_sessions.id", ondelete="CASCADE"), nullable=False),
sa.Column("node_key", sa.String(256), nullable=False),
sa.Column("stage_index", sa.Integer(), nullable=False),
sa.Column("seat_index", sa.Integer(), nullable=False),
sa.Column("agent_id", sa.String(128), nullable=False),
sa.Column("position_id", sa.String(64), nullable=True),
sa.Column("thread_id", sa.String(128), nullable=True, unique=True),
sa.Column("status", sa.String(32), nullable=False, server_default="locked"),
sa.Column("latest_answer", long_text, nullable=True),
sa.Column("artifact_manifest", long_text, nullable=True),
sa.Column("revision", sa.Integer(), nullable=False, server_default="0"),
sa.Column("upstream_revision", long_text, nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint("session_id", "node_key", name="uq_position_roundtable_nodes_session_key"),
)
op.create_index("ix_position_roundtable_nodes_session_id", "position_roundtable_nodes", ["session_id"])
op.create_index("ix_position_roundtable_nodes_agent_id", "position_roundtable_nodes", ["agent_id"])
op.create_index("ix_position_roundtable_nodes_position_id", "position_roundtable_nodes", ["position_id"])
op.create_index("ix_position_roundtable_nodes_status", "position_roundtable_nodes", ["status"])
def downgrade() -> None:
if _has_table("position_roundtable_nodes"):
op.drop_table("position_roundtable_nodes")
if _has_table("position_roundtable_sessions"):
op.drop_table("position_roundtable_sessions")
@@ -0,0 +1,54 @@
"""Add rejection metadata to position roundtable nodes.
Revision ID: 20260721_02
Revises: 20260721_01
Create Date: 2026-07-21
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260721_02"
down_revision = "20260721_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return column_name in {column["name"] for column in inspect(op.get_bind()).get_columns(table_name)}
def upgrade() -> None:
table = "position_roundtable_nodes"
if not _has_table(table):
return
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
if not _has_column(table, "rejection_count"):
op.add_column(
table,
sa.Column("rejection_count", sa.Integer(), nullable=False, server_default="0"),
)
if not _has_column(table, "last_rejection"):
op.add_column(table, sa.Column("last_rejection", long_text, nullable=True))
if not _has_column(table, "invalidated_by"):
op.add_column(table, sa.Column("invalidated_by", sa.String(256), nullable=True))
def downgrade() -> None:
table = "position_roundtable_nodes"
if not _has_table(table):
return
for column in ("invalidated_by", "last_rejection", "rejection_count"):
if _has_column(table, column):
op.drop_column(table, column)
@@ -0,0 +1,49 @@
"""Add builtin summary/action-plan snapshots to position roundtable sessions.
Revision ID: 20260721_03
Revises: 20260721_02
Create Date: 2026-07-21
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260721_03"
down_revision = "20260721_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return column_name in {column["name"] for column in inspect(op.get_bind()).get_columns(table_name)}
def upgrade() -> None:
table = "position_roundtable_sessions"
if not _has_table(table):
return
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
if not _has_column(table, "summary_snapshot"):
op.add_column(table, sa.Column("summary_snapshot", long_text, nullable=True))
if not _has_column(table, "action_plan_snapshot"):
op.add_column(table, sa.Column("action_plan_snapshot", long_text, nullable=True))
def downgrade() -> None:
table = "position_roundtable_sessions"
if not _has_table(table):
return
for column in ("action_plan_snapshot", "summary_snapshot"):
if _has_column(table, column):
op.drop_column(table, column)
@@ -0,0 +1,47 @@
"""Persist position-roundtable built-in agent thread ids.
Revision ID: 20260721_04
Revises: 20260721_03
Create Date: 2026-07-21
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260721_04"
down_revision = "20260721_03"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return column_name in {column["name"] for column in inspect(op.get_bind()).get_columns(table_name)}
def upgrade() -> None:
table = "position_roundtable_sessions"
if not _has_table(table):
return
if not _has_column(table, "summary_thread_id"):
op.add_column(table, sa.Column("summary_thread_id", sa.String(length=128), nullable=True))
if not _has_column(table, "action_plan_thread_id"):
op.add_column(table, sa.Column("action_plan_thread_id", sa.String(length=128), nullable=True))
def downgrade() -> None:
table = "position_roundtable_sessions"
if not _has_table(table):
return
for column in ("action_plan_thread_id", "summary_thread_id"):
if _has_column(table, column):
op.drop_column(table, column)
@@ -0,0 +1,69 @@
"""Persist complete position-roundtable conversation recovery snapshots.
Revision ID: 20260723_05
Revises: 20260721_04
Create Date: 2026-07-23
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260723_05"
down_revision = "20260721_04"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return column_name in {
column["name"] for column in inspect(op.get_bind()).get_columns(table_name)
}
def upgrade() -> None:
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
session_table = "position_roundtable_sessions"
if _has_table(session_table):
for column in (
"intent_conversation",
"summary_conversation",
"action_plan_conversation",
):
if not _has_column(session_table, column):
op.add_column(
session_table,
sa.Column(column, long_text, nullable=True),
)
node_table = "position_roundtable_nodes"
if _has_table(node_table) and not _has_column(node_table, "conversation_snapshot"):
op.add_column(
node_table,
sa.Column("conversation_snapshot", long_text, nullable=True),
)
def downgrade() -> None:
node_table = "position_roundtable_nodes"
if _has_table(node_table) and _has_column(node_table, "conversation_snapshot"):
op.drop_column(node_table, "conversation_snapshot")
session_table = "position_roundtable_sessions"
if _has_table(session_table):
for column in (
"action_plan_conversation",
"summary_conversation",
"intent_conversation",
):
if _has_column(session_table, column):
op.drop_column(session_table, column)
@@ -0,0 +1,45 @@
"""Add configurable position-roundtable roles.
Revision ID: 20260729_01
Revises: 20260723_05
Create Date: 2026-07-29
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260729_01"
down_revision = "20260723_05"
branch_labels = None
depends_on = None
def _has_table(name: str) -> bool:
return name in inspect(op.get_bind()).get_table_names()
def upgrade() -> None:
if _has_table("position_roles"):
return
op.create_table(
"position_roles",
sa.Column("id", sa.String(length=128), primary_key=True),
sa.Column("name", sa.String(length=128), nullable=False, unique=True),
sa.Column("description", sa.String(length=512), nullable=False, server_default=""),
sa.Column("role_type", sa.String(length=32), nullable=False, server_default="standard"),
sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.true()),
sa.Column("is_builtin", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("updated_by", sa.String(length=64), nullable=True),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_position_roles_name", "position_roles", ["name"])
op.create_index("ix_position_roles_role_type", "position_roles", ["role_type"])
def downgrade() -> None:
if _has_table("position_roles"):
op.drop_table("position_roles")
@@ -0,0 +1,69 @@
"""Index optional task-scoped position-roundtable history.
Revision ID: 20260808_01
Revises: 20260729_01
Create Date: 2026-08-08
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260808_01"
down_revision = "20260729_01"
branch_labels = None
depends_on = None
_TABLE = "position_roundtable_sessions"
_INDEX = "ix_position_roundtable_sessions_task_updated"
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return any(
column["name"] == column_name
for column in inspect(op.get_bind()).get_columns(table_name)
)
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
return index_name in {
index["name"] for index in inspect(op.get_bind()).get_indexes(table_name)
}
def upgrade() -> None:
if not _has_table(_TABLE):
return
# Historical records must stay in the original personal mode. New records
# set this flag only when a route taskId explicitly requests sharing.
if not _has_column(_TABLE, "task_scoped"):
op.add_column(
_TABLE,
sa.Column(
"task_scoped",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
),
)
if not _has_index(_TABLE, _INDEX):
op.create_index(_INDEX, _TABLE, ["external_task_id", "updated_at"])
def downgrade() -> None:
if not _has_table(_TABLE):
return
if _has_index(_TABLE, _INDEX):
op.drop_index(_INDEX, table_name=_TABLE)
if _has_column(_TABLE, "task_scoped"):
op.drop_column(_TABLE, "task_scoped")
@@ -0,0 +1,61 @@
"""Add optimistic-lock version column to position_roundtable_nodes.
Revision ID: 20260813_01
Revises: 20260808_01
Create Date: 2026-08-13
背景:``complete_node_turn`` 把「本节点 done → 下游 invalidate → 解锁下一 stage」
拆成多个独立事务的 ``update_node``,并发下后写覆盖先写,节点状态被打错(卡 locked /
invalidated_by 残留),导致下一阶段 ``_handoff_context`` 拿不到上游产物(断链)。
新增 ``version`` 列供 ``update_node`` 做乐观锁(``WHERE version=?``),并把状态转移
收敛进单一 ``FOR UPDATE`` 事务(``recompute_chain_state``),彻底消除 TOCTOU。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260813_01"
down_revision = "20260808_01"
branch_labels = None
depends_on = None
_TABLE = "position_roundtable_nodes"
_COLUMN = "version"
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return any(
column["name"] == column_name
for column in inspect(op.get_bind()).get_columns(table_name)
)
def upgrade() -> None:
if not _has_table(_TABLE):
return
if not _has_column(_TABLE, _COLUMN):
op.add_column(
_TABLE,
sa.Column(
_COLUMN,
sa.Integer(),
nullable=False,
server_default="0",
),
)
def downgrade() -> None:
if not _has_table(_TABLE):
return
if _has_column(_TABLE, _COLUMN):
op.drop_column(_TABLE, _COLUMN)
@@ -0,0 +1,48 @@
"""Add optimistic-lock ``version`` column to both roundtable draft tables.
Revision ID: 20260813_02
Revises: 20260813_01
Create Date: 2026-08-13
为 ``roundtable_drafts``(个人草稿)与 ``roundtable_task_drafts``(任务草稿)各加一列
``version INTEGER NOT NULL DEFAULT 0``,配合 ``update_draft(expected_version=...)`` 乐观锁,
消除后台作业 ``_write_run_to_draft`` 的 step2.runs 读-改-写丢失更新。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260813_02"
down_revision = "20260813_01"
branch_labels = None
depends_on = None
_TABLES = ("roundtable_drafts", "roundtable_task_drafts")
def _has_column(table_name: str, column_name: str) -> bool:
bind = op.get_bind()
if table_name not in inspect(bind).get_table_names():
return False
return any(
column["name"] == column_name
for column in inspect(bind).get_columns(table_name)
)
def upgrade() -> None:
for table in _TABLES:
if not _has_column(table, "version"):
op.add_column(
table,
sa.Column("version", sa.Integer(), nullable=False, server_default="0"),
)
def downgrade() -> None:
for table in _TABLES:
if _has_column(table, "version"):
op.drop_column(table, "version")
@@ -0,0 +1,88 @@
"""Add session version column and command idempotency table.
Revision ID: 20260813_03
Revises: 20260813_02
Create Date: 2026-08-13
岗位会商并发根治(命令式状态机)的两项 DB 支撑:
1. ``position_roundtable_sessions.version`` — session 级乐观锁版本号,保护
「确定意图 / 激活链 / 归档」等 session 级写操作,配合 ``apply_node_command``
的单一 ``FOR UPDATE`` 事务消除两个用户同时激活/归档同一 session 的竞态。
2. ``position_roundtable_commands`` — 命令幂等记录表。网络重试 / 双击 /
beforeunload beacon 可能把同一命令送达多次;靠 ``UNIQUE(session_id,
node_key, command_id)`` 让数据库天然去重,第二次到达时直接返回上次
``result_json``,绝不重复推进状态机。``payload_hash`` 防止客户端误复用
command_id 发送不同参数(同 command_id 但 hash 不同 → 409)。
``create_all`` 会为全新 DB 建表/补列;本迁移只补丁已存在的 DB。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260813_03"
down_revision = "20260813_02"
branch_labels = None
depends_on = None
_SESSIONS_TABLE = "position_roundtable_sessions"
_COMMANDS_TABLE = "position_roundtable_commands"
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return any(
column["name"] == column_name
for column in inspect(op.get_bind()).get_columns(table_name)
)
def upgrade() -> None:
# 1) sessions.version
if _has_table(_SESSIONS_TABLE) and not _has_column(_SESSIONS_TABLE, "version"):
op.add_column(
_SESSIONS_TABLE,
sa.Column("version", sa.Integer(), nullable=False, server_default="0"),
)
# 2) position_roundtable_commands
# result_json 与模型的 PortableLongText 对齐:MySQL 用 LONGTEXT,其余用 TEXT。
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
if not _has_table(_COMMANDS_TABLE):
op.create_table(
_COMMANDS_TABLE,
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("session_id", sa.String(length=64), nullable=False),
sa.Column("node_key", sa.String(length=256), nullable=False, server_default=""),
sa.Column("command_id", sa.String(length=64), nullable=False),
sa.Column("command_type", sa.String(length=32), nullable=False),
sa.Column("payload_hash", sa.String(length=64), nullable=False),
sa.Column("result_json", long_text, nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint(
"session_id", "node_key", "command_id",
name="uq_position_roundtable_commands_session_node_cmd",
),
)
op.create_index(
"ix_position_roundtable_commands_session_id",
_COMMANDS_TABLE,
["session_id"],
)
def downgrade() -> None:
if _has_table(_COMMANDS_TABLE):
op.drop_table(_COMMANDS_TABLE)
if _has_table(_SESSIONS_TABLE) and _has_column(_SESSIONS_TABLE, "version"):
op.drop_column(_SESSIONS_TABLE, "version")
@@ -0,0 +1,51 @@
"""Add ``draft_persist_pending`` flag to roundtable jobs.
Revision ID: 20260813_04
Revises: 20260813_03
Create Date: 2026-08-13
后台作业 ``_write_run_to_draft`` 的乐观锁重试全部耗尽后,不再退化为
last-write-wins 盲写,而是把 ``draft_persist_pending`` 置 1;由 outbox 补偿器
(Phase 3)负责投影结果到草稿,保证「研讨结果不丢」的一致性来自 DB 标记而非运气。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260813_04"
down_revision = "20260813_03"
branch_labels = None
depends_on = None
_TABLE = "roundtable_jobs"
def _has_column(table_name: str, column_name: str) -> bool:
bind = op.get_bind()
if table_name not in inspect(bind).get_table_names():
return False
return any(
column["name"] == column_name
for column in inspect(bind).get_columns(table_name)
)
def upgrade() -> None:
if not _has_column(_TABLE, "draft_persist_pending"):
op.add_column(
_TABLE,
sa.Column(
"draft_persist_pending",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
),
)
def downgrade() -> None:
if _has_column(_TABLE, "draft_persist_pending"):
op.drop_column(_TABLE, "draft_persist_pending")
@@ -0,0 +1,115 @@
"""Add lease / dedupe / snapshot columns to roundtable jobs (Phase 3).
Revision ID: 20260813_05
Revises: 20260813_04
Create Date: 2026-08-13
把「后台作业不双跑 / 崩溃可接管 / resume·cancel 串行」的一致性收敛到 DB:
- ``active_dedupe_key``:**唯一索引**。作业活跃(非终态)时存
``sha256(scope)``(scope = draft_id + task_id|user_id),进入终态时清 NULL。
MySQL/SQLite 的唯一索引都允许多个 NULL —— 于是「同一 scope 至多一个活跃作业」
由唯一键强制,INSERT 冲突即幂等命中,**不再依赖 GET_LOCK 命名锁**。
- ``request_id`` / ``request_hash``:前端启动请求的幂等键与入参指纹(审计 /
排查用;去重本身由 active_dedupe_key 负责)。
- ``input_snapshot``:启动入参的完整 JSON 快照 —— dispatcher 在**任意 worker**
领取 queued/租约过期作业时据此重建 StartParams(跨进程可接管的前提)。
- ``lease_owner`` / ``lease_until``:租约。条件 UPDATE 抢占(queued 或租约过期),
心跳续租;worker 崩溃后租约自然过期,其它 worker 接管 —— 恢复能力来自 DB 而非
进程内存。
- ``attempt`` / ``version``:接管次数计数 + 行级 CAS 版本(条件 UPDATE 乐观锁)。
``draft_persist_pending`` 已在 20260813_04 加入,此处不重复。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects import mysql
revision = "20260813_05"
down_revision = "20260813_04"
branch_labels = None
depends_on = None
_TABLE = "roundtable_jobs"
_DEDUPE_INDEX = "uq_roundtable_jobs_active_dedupe_key"
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
return any(
column["name"] == column_name
for column in inspect(op.get_bind()).get_columns(table_name)
)
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
try:
return any(ix["name"] == index_name for ix in inspect(op.get_bind()).get_indexes(table_name))
except Exception: # pragma: no cover - 方言差异兜底
return False
def _longtext() -> sa.types.TypeEngine:
"""SQLite/PostgreSQL 用 TEXT(无上限),MySQL 用 LONGTEXT(避免 64KB 截断)。"""
return sa.Text().with_variant(mysql.LONGTEXT(), "mysql")
def upgrade() -> None:
if not _has_table(_TABLE):
return
if not _has_column(_TABLE, "request_id"):
op.add_column(_TABLE, sa.Column("request_id", sa.String(64), nullable=True))
if not _has_column(_TABLE, "request_hash"):
op.add_column(_TABLE, sa.Column("request_hash", sa.String(64), nullable=True))
if not _has_column(_TABLE, "active_dedupe_key"):
op.add_column(_TABLE, sa.Column("active_dedupe_key", sa.String(64), nullable=True))
if not _has_index(_TABLE, _DEDUPE_INDEX):
op.create_index(_DEDUPE_INDEX, _TABLE, ["active_dedupe_key"], unique=True)
if not _has_column(_TABLE, "input_snapshot"):
op.add_column(_TABLE, sa.Column("input_snapshot", _longtext(), nullable=True))
if not _has_column(_TABLE, "lease_owner"):
op.add_column(_TABLE, sa.Column("lease_owner", sa.String(64), nullable=True))
if not _has_column(_TABLE, "lease_until"):
op.add_column(_TABLE, sa.Column("lease_until", sa.DateTime(), nullable=True))
if not _has_column(_TABLE, "attempt"):
op.add_column(
_TABLE,
sa.Column("attempt", sa.Integer(), nullable=False, server_default=sa.text("0")),
)
if not _has_column(_TABLE, "version"):
op.add_column(
_TABLE,
sa.Column("version", sa.Integer(), nullable=False, server_default=sa.text("0")),
)
def downgrade() -> None:
if not _has_table(_TABLE):
return
if _has_index(_TABLE, _DEDUPE_INDEX):
op.drop_index(_DEDUPE_INDEX, table_name=_TABLE)
for col in (
"version",
"attempt",
"lease_until",
"lease_owner",
"input_snapshot",
"active_dedupe_key",
"request_hash",
"request_id",
):
if _has_column(_TABLE, col):
op.drop_column(_TABLE, col)
@@ -0,0 +1,77 @@
"""intent_turns: intent-determination turn single-flight table (Phase 4).
Revision ID: 20260813_06
Revises: 20260813_05
Create Date: 2026-08-13
新建 ``intent_turns`` 表:第一步「确定意图」对话每回合对 ``(thread_id, client_turn_id)``
的占用记录。前端每回合生成稳定 ``client_turn_id``(重试 / 双击复用),后端用
``UNIQUE(thread_id, client_turn_id)`` 跨 worker 单飞 + 幂等回放,杜绝并发下「同一回合
被启两个 run → 双发意图 / 重复澄清卡」(用户报的「确定意图接口报错」)。
为什么需要它:进程内 ``RunManager`` 是每 worker 内存态,多 worker 下看不到彼此的 run,
同 thread 的两个请求若落到不同 worker 会各启一个 run(没有任何 409)—— 单飞只能靠 DB。
防变动既有库:全新部署由 ``create_all`` 建表;既有库由本迁移 + ``_ensure_orm_columns_sync``
兜底(表不存在则建)。所有步骤带 ``_has_table``/``_has_index`` 守卫,可重复执行。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260813_06"
down_revision = "20260813_05"
branch_labels = None
depends_on = None
_TABLE = "intent_turns"
_UQ = "uq_intent_turns_thread_client"
def _has_table(name: str) -> bool:
bind = op.get_bind()
insp = sa.inspect(bind)
return name in insp.get_table_names()
def _has_index(table: str, name: str) -> bool:
bind = op.get_bind()
insp = sa.inspect(bind)
return any(ix["name"] == name for ix in insp.get_indexes(table))
def upgrade() -> None:
if _has_table(_TABLE):
# 既有库(极少见,纯防御):补唯一索引即可。
if not _has_index(_TABLE, _UQ):
op.create_index(_UQ, _TABLE, ["thread_id", "client_turn_id"], unique=True)
return
op.create_table(
_TABLE,
sa.Column("id", sa.String(length=64), nullable=False),
sa.Column("thread_id", sa.String(length=128), nullable=False),
sa.Column("client_turn_id", sa.String(length=64), nullable=False),
sa.Column("message_hash", sa.String(length=64), nullable=False),
sa.Column("status", sa.String(length=16), nullable=False, server_default=sa.text("running")),
sa.Column("result_json", sa.Text().with_variant(sa.dialects.mysql.LONGTEXT(), "mysql"), nullable=True),
sa.Column("error", sa.Text(), nullable=True),
sa.Column("lease_owner", sa.String(length=64), nullable=True),
sa.Column("lease_until", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_intent_turns_thread_id", _TABLE, ["thread_id"])
op.create_index(_UQ, _TABLE, ["thread_id", "client_turn_id"], unique=True)
def downgrade() -> None:
if _has_index(_TABLE, _UQ):
op.drop_index(_UQ, table_name=_TABLE)
if _has_index(_TABLE, "ix_intent_turns_thread_id"):
op.drop_index("ix_intent_turns_thread_id", table_name=_TABLE)
if _has_table(_TABLE):
op.drop_table(_TABLE)
@@ -0,0 +1,42 @@
"""Add version column to roundtable_artifact_submissions for CAS.
Revision ID: 20260813_07
Revises: 20260813_06
Create Date: 2026-08-13
Phase 5 CAS: submit/cancel 带 expected_version,并发时旧 cancel 不得撤销新提交。
version 列有 server_default='0',既有行自动得 0,无需数据回填。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260813_07"
down_revision = "20260813_06"
branch_labels = None
depends_on = None
_TABLE = "roundtable_artifact_submissions"
_COL = "version"
def _has_column(bind, table: str, column: str) -> bool:
inspector = sa.inspect(bind)
return any(col["name"] == column for col in inspector.get_columns(table))
def upgrade() -> None:
bind = op.get_bind()
if not _has_column(bind, _TABLE, _COL):
op.add_column(
_TABLE,
sa.Column(_COL, sa.Integer(), nullable=False, server_default=sa.text("0")),
)
def downgrade() -> None:
bind = op.get_bind()
if _has_column(bind, _TABLE, _COL):
op.drop_column(_TABLE, _COL)
@@ -0,0 +1,43 @@
"""Create durable undo snapshots for whole-document AI rewrites.
Revision ID: 20260816_01
Revises: 20260813_07
Create Date: 2026-08-16
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260816_01"
down_revision = "20260813_07"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
if sa.inspect(bind).has_table("document_rewrite_versions"):
return
op.create_table(
"document_rewrite_versions",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("user_id", sa.String(length=64), nullable=True, index=True),
sa.Column("source_type", sa.String(length=32), nullable=False, index=True),
sa.Column("source_id", sa.String(length=128), nullable=False, index=True),
sa.Column("source_path", sa.String(length=1024), nullable=True),
sa.Column("original_content", sa.Text(), nullable=False),
sa.Column("original_hash", sa.String(length=64), nullable=False),
sa.Column("committed_hash", sa.String(length=64), nullable=False),
sa.Column("instruction", sa.Text(), nullable=True),
sa.Column("model_name", sa.String(length=256), nullable=True),
sa.Column("reverted_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
)
def downgrade() -> None:
bind = op.get_bind()
if sa.inspect(bind).has_table("document_rewrite_versions"):
op.drop_table("document_rewrite_versions")
@@ -0,0 +1,52 @@
"""Add compact_menu_overrides.menu_type (简介模式菜单分套).
Two website deployments keep independent compact/sidebar-summary left menus.
Type ``A`` is the historical default; type ``B`` is stored under a prefixed
``node_id`` so it never collides on databases that still use ``node_id`` as
the sole primary key.
ORM: ``CompactMenuOverrideRow.menu_type = String(32), NOT NULL, default A``.
``create_all`` gives new DBs the column; existing DBs are patched by this
revision and by startup ``_ensure_orm_columns_sync``.
Revision ID: 20260819_01
Revises: 20260816_01
Create Date: 2026-08-19
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260819_01"
down_revision = "20260816_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("compact_menu_overrides") and not _has_column("compact_menu_overrides", "menu_type"):
op.add_column(
"compact_menu_overrides",
sa.Column("menu_type", sa.String(length=32), nullable=False, server_default="A"),
)
def downgrade() -> None:
if _has_column("compact_menu_overrides", "menu_type"):
op.drop_column("compact_menu_overrides", "menu_type")
@@ -0,0 +1,51 @@
"""Add enabled column to roundtable_chains.
Per-chain 启停 switch: True = 可在选链弹窗 / 公共入口里选用;False = 停用(管理列表
仍可见,但不可选入研讨)。Default True → existing chains stay enabled. BOOLEAN NOT
NULL DEFAULT 1, matching ``RoundtableChainRow.enabled``.
``create_all`` adds the column for brand-new DBs; the startup ``_ensure_orm_columns_sync``
sweep adds it to already-existing tables (sqlite/mysql/postgres). This revision keeps the
alembic graph consistent with the rest of the chain columns and documents the change.
Revision ID: 20260819_02
Revises: 20260819_01
Create Date: 2026-08-19
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260819_02"
down_revision = "20260819_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("roundtable_chains") and not _has_column("roundtable_chains", "enabled"):
op.add_column(
"roundtable_chains",
sa.Column("enabled", sa.Boolean(), nullable=False, server_default="1"),
)
def downgrade() -> None:
if _has_column("roundtable_chains", "enabled"):
op.drop_column("roundtable_chains", "enabled")
@@ -0,0 +1,51 @@
"""Create administrator-managed exact-match fixed questions.
Revision ID: 20260821_03
Revises: 20260821_01
Create Date: 2026-08-21
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
revision = "20260821_03"
down_revision = "20260821_01"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
if sa.inspect(bind).has_table("fixed_questions"):
return
long_text = sa.Text().with_variant(mysql.LONGTEXT(), "mysql")
op.create_table(
"fixed_questions",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("question", sa.Text(), nullable=False),
sa.Column("question_hash", sa.String(length=64), nullable=False),
sa.Column("answer", long_text, nullable=False),
sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.true()),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("updated_by", sa.String(length=64), nullable=True),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint(
"question_hash",
name="uq_fixed_questions_question_hash",
),
)
op.create_index(
"ix_fixed_questions_question_hash",
"fixed_questions",
["question_hash"],
unique=False,
)
def downgrade() -> None:
bind = op.get_bind()
if sa.inspect(bind).has_table("fixed_questions"):
op.drop_table("fixed_questions")
@@ -0,0 +1,49 @@
"""Add structure_mode to report_structures.
Per-structure 结构约束: ``fixed`` (固定大纲) vs ``adaptive`` (弹性大纲).
Existing rows stay ``adaptive`` so current writing behaviour is unchanged.
``create_all`` adds the column for brand-new DBs; the startup
``_ensure_orm_columns_sync`` sweep adds it to already-existing tables.
Revision ID: 20260821_01
Revises: 20260819_02
Create Date: 2026-08-21
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260821_01"
down_revision = "20260819_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("report_structures") and not _has_column("report_structures", "structure_mode"):
op.add_column(
"report_structures",
sa.Column("structure_mode", sa.String(length=16), nullable=False, server_default="adaptive"),
)
def downgrade() -> None:
if _has_column("report_structures", "structure_mode"):
op.drop_column("report_structures", "structure_mode")
@@ -0,0 +1,44 @@
"""Add configurable fixed-answer streaming speed.
Revision ID: 20260821_04
Revises: 20260821_03
Create Date: 2026-08-21
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260821_04"
down_revision = "20260821_03"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("fixed_questions"):
return
columns = {column["name"] for column in inspector.get_columns("fixed_questions")}
if "tokens_per_second" not in columns:
op.add_column(
"fixed_questions",
sa.Column(
"tokens_per_second",
sa.Integer(),
nullable=False,
server_default="100",
),
)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("fixed_questions"):
return
columns = {column["name"] for column in inspector.get_columns("fixed_questions")}
if "tokens_per_second" in columns:
op.drop_column("fixed_questions", "tokens_per_second")
@@ -0,0 +1,52 @@
"""Add retrieval_directions to report_structures.
Optional 检索方向 list on each 报告结构. Empty / NULL keeps today's
collector query-planning; a non-empty list tells material collection to
search along those facets.
ORM: ``ReportStructureRow.retrieval_directions = PortableJSON()``
(SQLite/PG native JSON, MySQL TEXT). ``create_all`` adds the column on
brand-new DBs; existing tables are patched by startup
``_ensure_orm_columns_sync`` (nullable, no server_default required).
Revision ID: 20260822_01
Revises: 20260821_01
Create Date: 2026-08-22
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260822_01"
down_revision = "20260821_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("report_structures") and not _has_column("report_structures", "retrieval_directions"):
op.add_column(
"report_structures",
sa.Column("retrieval_directions", sa.Text(), nullable=True),
)
def downgrade() -> None:
if _has_column("report_structures", "retrieval_directions"):
op.drop_column("report_structures", "retrieval_directions")
@@ -0,0 +1,52 @@
"""Add retrieval_skills to report_structures.
Optional 检索来源 list of skill names on each 报告结构. Empty / NULL keeps
today's collector tools; a non-empty list tells material collection to
call those skills.
ORM: ``ReportStructureRow.retrieval_skills = PortableJSON()``
(SQLite/PG native JSON, MySQL TEXT). ``create_all`` adds the column on
brand-new DBs; existing tables are patched by startup
``_ensure_orm_columns_sync`` (nullable, no server_default required).
Revision ID: 20260822_02
Revises: 20260822_01
Create Date: 2026-08-22
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260822_02"
down_revision = "20260822_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
if _has_table("report_structures") and not _has_column("report_structures", "retrieval_skills"):
op.add_column(
"report_structures",
sa.Column("retrieval_skills", sa.Text(), nullable=True),
)
def downgrade() -> None:
if _has_column("report_structures", "retrieval_skills"):
op.drop_column("report_structures", "retrieval_skills")
@@ -0,0 +1,143 @@
"""Add DeerFlow-local WeKnora Wiki mirror and vector index.
Revision ID: 20260823_01
Revises: 20260821_04
Create Date: 2026-08-23
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
revision = "20260823_01"
down_revision = "20260821_04"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
columns = {column["name"] for column in inspector.get_columns("llmwiki_knowledge_bases")}
if "wiki_index_enabled" not in columns:
op.add_column("llmwiki_knowledge_bases", sa.Column("wiki_index_enabled", sa.Boolean(), nullable=False, server_default=sa.true()))
if "external_search_enabled" not in columns:
op.add_column("llmwiki_knowledge_bases", sa.Column("external_search_enabled", sa.Boolean(), nullable=False, server_default=sa.false()))
if "external_search_updated_at" not in columns:
op.add_column("llmwiki_knowledge_bases", sa.Column("external_search_updated_at", sa.DateTime(timezone=True), nullable=True))
mapping_indexes = {index["name"] for index in inspector.get_indexes("llmwiki_knowledge_bases")}
if "ix_llmwiki_knowledge_bases_wiki_index_enabled" not in mapping_indexes:
op.create_index("ix_llmwiki_knowledge_bases_wiki_index_enabled", "llmwiki_knowledge_bases", ["wiki_index_enabled"])
if "ix_llmwiki_knowledge_bases_external_search_enabled" not in mapping_indexes:
op.create_index("ix_llmwiki_knowledge_bases_external_search_enabled", "llmwiki_knowledge_bases", ["external_search_enabled"])
long_text = sa.Text().with_variant(mysql.LONGTEXT(), "mysql")
portable_json = sa.JSON().with_variant(sa.Text(), "mysql")
if not inspector.has_table("llmwiki_wiki_pages"):
op.create_table(
"llmwiki_wiki_pages",
sa.Column("id", sa.String(36), primary_key=True),
sa.Column("knowledge_base_mapping_id", sa.String(36), sa.ForeignKey("llmwiki_knowledge_bases.id", ondelete="CASCADE"), nullable=False),
sa.Column("remote_page_id", sa.String(128), nullable=True),
sa.Column("slug", sa.String(1024), nullable=False),
sa.Column("slug_hash", sa.String(64), nullable=False),
sa.Column("title", sa.String(512), nullable=False, server_default=""),
sa.Column("summary", long_text, nullable=False),
sa.Column("content_md", long_text, nullable=False),
sa.Column("page_type", sa.String(32), nullable=False, server_default="article"),
sa.Column("status", sa.String(32), nullable=False, server_default="published"),
sa.Column("aliases", portable_json, nullable=False),
sa.Column("category_path", portable_json, nullable=False),
sa.Column("parent_slug", sa.String(1024), nullable=True),
sa.Column("wiki_path", sa.String(1024), nullable=True),
sa.Column("source_refs", portable_json, nullable=False),
sa.Column("chunk_refs", portable_json, nullable=False),
sa.Column("page_version", sa.Integer(), nullable=False, server_default="0"),
sa.Column("content_hash", sa.String(64), nullable=False),
sa.Column("remote_created_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("remote_updated_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("index_status", sa.String(24), nullable=False, server_default="pending"),
sa.Column("indexed_fingerprint", sa.String(64), nullable=True),
sa.Column("indexed_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_error", sa.Text(), nullable=True),
sa.Column("is_remote_deleted", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("last_seen_sync_id", sa.String(36), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("knowledge_base_mapping_id", "slug_hash", name="uq_llmwiki_wiki_page_mapping_slug_hash"),
)
op.create_index("ix_llmwiki_wiki_pages_knowledge_base_mapping_id", "llmwiki_wiki_pages", ["knowledge_base_mapping_id"])
op.create_index("ix_llmwiki_wiki_page_mapping_visibility", "llmwiki_wiki_pages", ["knowledge_base_mapping_id", "status", "index_status", "is_remote_deleted"])
op.create_index("ix_llmwiki_wiki_pages_remote_page_id", "llmwiki_wiki_pages", ["remote_page_id"])
op.create_index("ix_llmwiki_wiki_pages_title", "llmwiki_wiki_pages", ["title"])
op.create_index("ix_llmwiki_wiki_pages_page_type", "llmwiki_wiki_pages", ["page_type"])
op.create_index("ix_llmwiki_wiki_pages_status", "llmwiki_wiki_pages", ["status"])
op.create_index("ix_llmwiki_wiki_pages_page_version", "llmwiki_wiki_pages", ["page_version"])
op.create_index("ix_llmwiki_wiki_pages_content_hash", "llmwiki_wiki_pages", ["content_hash"])
op.create_index("ix_llmwiki_wiki_pages_remote_updated_at", "llmwiki_wiki_pages", ["remote_updated_at"])
op.create_index("ix_llmwiki_wiki_pages_index_status", "llmwiki_wiki_pages", ["index_status"])
op.create_index("ix_llmwiki_wiki_pages_is_remote_deleted", "llmwiki_wiki_pages", ["is_remote_deleted"])
op.create_index("ix_llmwiki_wiki_pages_last_seen_sync_id", "llmwiki_wiki_pages", ["last_seen_sync_id"])
op.create_index("ix_llmwiki_wiki_pages_updated_at", "llmwiki_wiki_pages", ["updated_at"])
if not inspector.has_table("llmwiki_wiki_vectors"):
op.create_table(
"llmwiki_wiki_vectors",
sa.Column("id", sa.String(36), primary_key=True),
sa.Column("page_id", sa.String(36), sa.ForeignKey("llmwiki_wiki_pages.id", ondelete="CASCADE"), nullable=False),
sa.Column("knowledge_base_mapping_id", sa.String(36), nullable=False),
sa.Column("section_index", sa.Integer(), nullable=False),
sa.Column("heading", sa.String(1024), nullable=True),
sa.Column("section_content", long_text, nullable=False),
sa.Column("content_hash", sa.String(64), nullable=False),
sa.Column("embedding_fingerprint", sa.String(64), nullable=False),
sa.Column("embedding_dimensions", sa.Integer(), nullable=False),
sa.Column("vector_blob", sa.LargeBinary(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("page_id", "section_index", "embedding_fingerprint", name="uq_llmwiki_wiki_vector_page_section_fingerprint"),
)
op.create_index("ix_llmwiki_wiki_vector_snapshot", "llmwiki_wiki_vectors", ["knowledge_base_mapping_id", "embedding_fingerprint"])
op.create_index("ix_llmwiki_wiki_vectors_page_id", "llmwiki_wiki_vectors", ["page_id"])
op.create_index("ix_llmwiki_wiki_vectors_knowledge_base_mapping_id", "llmwiki_wiki_vectors", ["knowledge_base_mapping_id"])
op.create_index("ix_llmwiki_wiki_vectors_content_hash", "llmwiki_wiki_vectors", ["content_hash"])
op.create_index("ix_llmwiki_wiki_vectors_embedding_fingerprint", "llmwiki_wiki_vectors", ["embedding_fingerprint"])
if not inspector.has_table("llmwiki_wiki_sync_states"):
op.create_table(
"llmwiki_wiki_sync_states",
sa.Column("knowledge_base_mapping_id", sa.String(36), sa.ForeignKey("llmwiki_knowledge_bases.id", ondelete="CASCADE"), primary_key=True),
sa.Column("state", sa.String(24), nullable=False, server_default="idle"),
sa.Column("active_sync_id", sa.String(36), nullable=True),
sa.Column("lease_owner", sa.String(128), nullable=True),
sa.Column("lease_expires_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_started_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_completed_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_success_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_error", sa.Text(), nullable=True),
sa.Column("remote_page_count", sa.Integer(), nullable=False, server_default="0"),
sa.Column("local_page_count", sa.Integer(), nullable=False, server_default="0"),
sa.Column("ready_page_count", sa.Integer(), nullable=False, server_default="0"),
sa.Column("vector_count", sa.Integer(), nullable=False, server_default="0"),
sa.Column("failed_page_count", sa.Integer(), nullable=False, server_default="0"),
sa.Column("index_revision", sa.BigInteger(), nullable=False, server_default="0"),
sa.Column("embedding_fingerprint", sa.String(64), nullable=True),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
for table in ("llmwiki_wiki_vectors", "llmwiki_wiki_pages", "llmwiki_wiki_sync_states"):
if inspector.has_table(table):
op.drop_table(table)
columns = {column["name"] for column in inspector.get_columns("llmwiki_knowledge_bases")}
indexes = {index["name"] for index in inspector.get_indexes("llmwiki_knowledge_bases")}
for index in ("ix_llmwiki_knowledge_bases_external_search_enabled", "ix_llmwiki_knowledge_bases_wiki_index_enabled"):
if index in indexes:
op.drop_index(index, table_name="llmwiki_knowledge_bases")
for column in ("external_search_updated_at", "external_search_enabled", "wiki_index_enabled"):
if column in columns:
op.drop_column("llmwiki_knowledge_bases", column)
@@ -0,0 +1,34 @@
"""Merge report-structure and local-Wiki heads, repairing the old duplicate stamp.
Revision ID: 20260825_01
Revises: 20260822_02, 20260823_01
Create Date: 2026-08-25
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260825_01"
down_revision = ("20260822_02", "20260823_01")
branch_labels = None
depends_on = None
def upgrade() -> None:
# An older build accidentally used 20260821_01 for two migrations. A DB
# stamped by the fixed-question variant may therefore still lack this
# report column even though Alembic considers the surviving 01 applied.
inspector = sa.inspect(op.get_bind())
if inspector.has_table("report_structures"):
columns = {column["name"] for column in inspector.get_columns("report_structures")}
if "structure_mode" not in columns:
op.add_column(
"report_structures",
sa.Column("structure_mode", sa.String(length=16), nullable=False, server_default="adaptive"),
)
def downgrade() -> None:
pass
@@ -0,0 +1,70 @@
"""Create workflow_definitions / workflow_versions tables.
Revision ID: 20260828_01
Revises: 20260825_01
Create Date: 2026-08-28
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260828_01"
down_revision = "20260825_01"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
# Match PortableLongText used by the ORM. MySQL TEXT only holds 64 KiB,
# which is too small for serialized workflow graphs.
long_text = LONGTEXT() if bind.dialect.name == "mysql" else sa.Text()
if not inspector.has_table("workflow_definitions"):
op.create_table(
"workflow_definitions",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("name", sa.String(length=255), nullable=False),
# Older MySQL versions reject defaults on TEXT/LONGTEXT columns.
# The repository always writes both fields explicitly.
sa.Column("description", sa.Text(), nullable=False),
sa.Column("owner_id", sa.String(length=64), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False, server_default="draft"),
sa.Column("draft_revision", sa.Integer(), nullable=False, server_default="0"),
sa.Column("draft_graph_json", long_text, nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_workflow_definitions_owner_id", "workflow_definitions", ["owner_id"])
op.create_index("ix_workflow_definitions_status", "workflow_definitions", ["status"])
if not inspector.has_table("workflow_versions"):
op.create_table(
"workflow_versions",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("workflow_id", sa.String(length=64), nullable=False),
sa.Column("version_number", sa.Integer(), nullable=False),
sa.Column("graph_json", long_text, nullable=False),
sa.Column("graph_hash", sa.String(length=64), nullable=False),
sa.Column("input_schema", sa.Text(), nullable=True),
sa.Column("output_schema", sa.Text(), nullable=True),
sa.Column("published_by", sa.String(length=64), nullable=True),
sa.Column("published_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("change_note", sa.Text(), nullable=False),
sa.ForeignKeyConstraint(["workflow_id"], ["workflow_definitions.id"], ondelete="CASCADE"),
sa.UniqueConstraint("workflow_id", "version_number", name="uq_workflow_versions_wf_num"),
)
op.create_index("ix_workflow_versions_workflow_id", "workflow_versions", ["workflow_id"])
op.create_index("ix_workflow_versions_graph_hash", "workflow_versions", ["graph_hash"])
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if inspector.has_table("workflow_versions"):
op.drop_table("workflow_versions")
if inspector.has_table("workflow_definitions"):
op.drop_table("workflow_definitions")
@@ -0,0 +1,127 @@
"""Create workflow run / node-run / event / artifact tables.
Revision ID: 20260828_02
Revises: 20260828_01
Create Date: 2026-08-28
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260828_02"
down_revision = "20260828_01"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("workflow_runs"):
op.create_table(
"workflow_runs",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("workflow_id", sa.String(length=64), nullable=False),
sa.Column("workflow_version_id", sa.String(length=64), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False, server_default="queued"),
sa.Column("owner_id", sa.String(length=64), nullable=False),
sa.Column("idempotency_key", sa.String(length=128), nullable=True),
sa.Column("input_json", sa.Text(), nullable=True),
sa.Column("output_json", sa.Text(), nullable=True),
sa.Column("error_json", sa.Text(), nullable=True),
sa.Column("context_json", sa.Text(), nullable=True),
sa.Column("pending_input_json", sa.Text(), nullable=True),
sa.Column("resume_token", sa.String(length=64), nullable=True),
sa.Column("lease_owner", sa.String(length=64), nullable=True),
sa.Column("lease_until", sa.DateTime(timezone=True), nullable=True),
sa.Column("heartbeat_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("attempt", sa.Integer(), nullable=False, server_default="0"),
sa.Column("max_attempts", sa.Integer(), nullable=False, server_default="3"),
sa.Column("version", sa.Integer(), nullable=False, server_default="0"),
sa.Column("retry_of_run_id", sa.String(length=64), nullable=True),
sa.Column("started_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("idempotency_key", name="uq_workflow_runs_idempotency"),
)
op.create_index("ix_workflow_runs_workflow_id", "workflow_runs", ["workflow_id"])
op.create_index("ix_workflow_runs_workflow_version_id", "workflow_runs", ["workflow_version_id"])
op.create_index("ix_workflow_runs_owner_id", "workflow_runs", ["owner_id"])
op.create_index("ix_workflow_runs_status", "workflow_runs", ["status"])
op.create_index("ix_workflow_runs_resume_token", "workflow_runs", ["resume_token"])
if not inspector.has_table("workflow_node_runs"):
op.create_table(
"workflow_node_runs",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("run_id", sa.String(length=64), nullable=False),
sa.Column("node_id", sa.String(length=128), nullable=False),
sa.Column("node_type", sa.String(length=32), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False, server_default="queued"),
sa.Column("attempt", sa.Integer(), nullable=False, server_default="1"),
sa.Column("iteration", sa.Integer(), nullable=False, server_default="0"),
sa.Column("is_current", sa.Boolean(), nullable=False, server_default=sa.text("1")),
sa.Column("input_snapshot", sa.Text(), nullable=True),
sa.Column("output_snapshot", sa.Text(), nullable=True),
sa.Column("error_json", sa.Text(), nullable=True),
sa.Column("parent_node_run_id", sa.String(length=64), nullable=True),
sa.Column("duration_ms", sa.Integer(), nullable=True),
sa.Column("started_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint(
"run_id", "node_id", "attempt", "iteration", name="uq_workflow_node_runs_key"
),
)
op.create_index("ix_workflow_node_runs_run_id", "workflow_node_runs", ["run_id"])
op.create_index("ix_workflow_node_runs_status", "workflow_node_runs", ["status"])
if not inspector.has_table("workflow_run_events"):
op.create_table(
"workflow_run_events",
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
sa.Column("run_id", sa.String(length=64), nullable=False),
sa.Column("workflow_id", sa.String(length=64), nullable=False),
sa.Column("version_id", sa.String(length=64), nullable=False),
sa.Column("seq", sa.Integer(), nullable=False),
sa.Column("event_type", sa.String(length=64), nullable=False),
sa.Column("node_id", sa.String(length=128), nullable=True),
sa.Column("node_run_id", sa.String(length=64), nullable=True),
sa.Column("payload_json", sa.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("run_id", "seq", name="uq_workflow_run_events_run_seq"),
)
op.create_index("ix_workflow_run_events_run_id", "workflow_run_events", ["run_id"])
op.create_index("ix_workflow_run_events_run_seq", "workflow_run_events", ["run_id", "seq"])
if not inspector.has_table("workflow_run_artifacts"):
op.create_table(
"workflow_run_artifacts",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("run_id", sa.String(length=64), nullable=False),
sa.Column("node_id", sa.String(length=128), nullable=False),
sa.Column("name", sa.String(length=512), nullable=False),
sa.Column("mime_type", sa.String(length=191), nullable=False),
sa.Column("path", sa.Text(), nullable=False),
sa.Column("size_bytes", sa.Integer(), nullable=True),
sa.Column("preview", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_workflow_run_artifacts_run_id", "workflow_run_artifacts", ["run_id"])
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
for table in (
"workflow_run_artifacts",
"workflow_run_events",
"workflow_node_runs",
"workflow_runs",
):
if inspector.has_table(table):
op.drop_table(table)
@@ -0,0 +1,49 @@
"""Create workflow_data_sources table.
Revision ID: 20260828_03
Revises: 20260828_02
Create Date: 2026-08-28
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260828_03"
down_revision = "20260828_02"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if inspector.has_table("workflow_data_sources"):
return
op.create_table(
"workflow_data_sources",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("name", sa.String(length=191), nullable=False),
sa.Column("description", sa.String(length=512), nullable=False, server_default=""),
sa.Column("kind", sa.String(length=32), nullable=False, server_default="sql"),
sa.Column("driver", sa.String(length=64), nullable=False, server_default=""),
sa.Column("secret_ciphertext", sa.Text(), nullable=False),
sa.Column("secret_encrypted", sa.Boolean(), nullable=False, server_default=sa.text("1")),
sa.Column("masked_target", sa.String(length=512), nullable=False, server_default=""),
sa.Column("max_rows", sa.Integer(), nullable=False, server_default="1000"),
sa.Column("allowed_tables", sa.Text(), nullable=True),
sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.text("1")),
sa.Column("owner_id", sa.String(length=64), nullable=True),
sa.Column("created_by", sa.String(length=64), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("name", name="uq_workflow_data_sources_name"),
)
op.create_index("ix_workflow_data_sources_owner_id", "workflow_data_sources", ["owner_id"])
def downgrade() -> None:
bind = op.get_bind()
if sa.inspect(bind).has_table("workflow_data_sources"):
op.drop_table("workflow_data_sources")
@@ -0,0 +1,66 @@
"""Add workflow counter columns: version allocator + event seq counter.
Revision ID: 20260828_04
Revises: 20260828_03
Create Date: 2026-08-28
Functional-robustness remediation (audit items P1-02 / P1-03):
* ``workflow_definitions.next_version_number`` — publish allocates the version
number by CAS-bumping this counter instead of ``MAX(version_number) + 1``,
so two concurrent publishes get adjacent distinct numbers instead of a
unique-constraint 500.
* ``workflow_runs.next_event_seq`` — the event log draws each event's ``seq``
from this counter in the insert's own transaction instead of ``MAX(seq)+1``.
Both columns carry a ``server_default`` so existing databases get them via the
startup ``_ensure_orm_columns_sync`` sweep even without running Alembic; rows
keep the default (1 / 0) and the first write self-heals from the existing
maximum on unique-conflict.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260828_04"
down_revision = "20260828_03"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if inspector.has_table("workflow_definitions"):
existing = {c["name"] for c in inspector.get_columns("workflow_definitions")}
if "next_version_number" not in existing:
op.add_column(
"workflow_definitions",
sa.Column("next_version_number", sa.Integer(), nullable=False, server_default="1"),
)
if inspector.has_table("workflow_runs"):
existing = {c["name"] for c in inspector.get_columns("workflow_runs")}
if "next_event_seq" not in existing:
op.add_column(
"workflow_runs",
sa.Column("next_event_seq", sa.Integer(), nullable=False, server_default="0"),
)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if inspector.has_table("workflow_definitions"):
existing = {c["name"] for c in inspector.get_columns("workflow_definitions")}
if "next_version_number" in existing:
op.drop_column("workflow_definitions", "next_version_number")
if inspector.has_table("workflow_runs"):
existing = {c["name"] for c in inspector.get_columns("workflow_runs")}
if "next_event_seq" in existing:
op.drop_column("workflow_runs", "next_event_seq")
@@ -0,0 +1,50 @@
"""Add non-secret HTTP metadata to workflow data sources.
Revision ID: 20260829_01
Revises: 20260828_04
Create Date: 2026-08-29
HTTP request headers remain in the encrypted secret blob. The endpoint and
method allowlist are intentionally separate non-secret fields so the canvas
can show a reusable interface resource without exposing credentials.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "20260829_01"
down_revision = "20260828_04"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("workflow_data_sources"):
return
existing = {column["name"] for column in inspector.get_columns("workflow_data_sources")}
if "base_url" not in existing:
op.add_column(
"workflow_data_sources",
sa.Column("base_url", sa.String(length=2048), nullable=False, server_default=""),
)
if "allowed_methods" not in existing:
op.add_column(
"workflow_data_sources",
sa.Column("allowed_methods", sa.Text(), nullable=True),
)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("workflow_data_sources"):
return
existing = {column["name"] for column in inspector.get_columns("workflow_data_sources")}
if "allowed_methods" in existing:
op.drop_column("workflow_data_sources", "allowed_methods")
if "base_url" in existing:
op.drop_column("workflow_data_sources", "base_url")
@@ -0,0 +1,72 @@
"""Add Coze canvas draft column to workflow_definitions.
Revision ID: 20260829_02
Revises: 20260829_01
Create Date: 2026-08-29
The canvas document (positions, Coze form internals) is stored separately from
the executable WorkflowGraph so neither representation can impersonate the
other. ``published_canvas_schema_hash`` records which canvas the current
published version was compiled from, for audit only.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260829_02"
down_revision = "20260829_01"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("workflow_definitions"):
return
existing = {column["name"] for column in inspector.get_columns("workflow_definitions")}
if "draft_canvas_schema_json" not in existing:
# Follow roundtable/deep-research migrations: large JSON is LONGTEXT on
# MySQL, and we must not use a TEXT/LONGTEXT server default (unsupported
# by MySQL 5.7). Add it nullable, backfill legacy rows, then enforce the
# ORM's NOT NULL contract.
canvas_type = LONGTEXT() if bind.dialect.name == "mysql" else sa.Text()
op.add_column(
"workflow_definitions",
sa.Column("draft_canvas_schema_json", canvas_type, nullable=True),
)
op.execute(
sa.text(
"UPDATE workflow_definitions "
"SET draft_canvas_schema_json = '{}' "
"WHERE draft_canvas_schema_json IS NULL"
)
)
# ``batch_alter_table`` uses a native ALTER TABLE on MySQL while also
# handling SQLite's lack of ALTER COLUMN for legacy SQLite deployments.
with op.batch_alter_table("workflow_definitions") as batch_op:
batch_op.alter_column(
"draft_canvas_schema_json",
existing_type=canvas_type,
nullable=False,
)
if "published_canvas_schema_hash" not in existing:
op.add_column(
"workflow_definitions",
sa.Column("published_canvas_schema_hash", sa.String(length=64), nullable=True),
)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("workflow_definitions"):
return
existing = {column["name"] for column in inspector.get_columns("workflow_definitions")}
if "published_canvas_schema_hash" in existing:
op.drop_column("workflow_definitions", "published_canvas_schema_hash")
if "draft_canvas_schema_json" in existing:
op.drop_column("workflow_definitions", "draft_canvas_schema_json")
@@ -0,0 +1,79 @@
"""Create durable pre-run workflow planning sessions and proposals.
Revision ID: 20260831_01
Revises: 20260829_02
Create Date: 2026-08-31
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.mysql import LONGTEXT
revision = "20260831_01"
down_revision = "20260829_02"
branch_labels = None
depends_on = None
def _large_text_type() -> sa.types.TypeEngine:
bind = op.get_bind()
return LONGTEXT() if bind.dialect.name == "mysql" else sa.Text()
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
text_type = _large_text_type()
if not inspector.has_table("workflow_planning_sessions"):
op.create_table(
"workflow_planning_sessions",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("workflow_id", sa.String(length=64), nullable=False),
sa.Column("owner_id", sa.String(length=64), nullable=False),
sa.Column("query", sa.Text(), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False, server_default="proposed"),
sa.Column("source_draft_revision", sa.Integer(), nullable=True),
sa.Column("selected_proposal_id", sa.String(length=64), nullable=True),
sa.Column("confirmed_run_id", sa.String(length=64), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index("ix_workflow_planning_sessions_workflow_id", "workflow_planning_sessions", ["workflow_id"])
op.create_index("ix_workflow_planning_sessions_owner_id", "workflow_planning_sessions", ["owner_id"])
op.create_index("ix_workflow_planning_sessions_status", "workflow_planning_sessions", ["status"])
op.create_index("ix_workflow_planning_sessions_confirmed_run_id", "workflow_planning_sessions", ["confirmed_run_id"])
if not inspector.has_table("workflow_planning_proposals"):
op.create_table(
"workflow_planning_proposals",
sa.Column("id", sa.String(length=64), primary_key=True),
sa.Column("session_id", sa.String(length=64), sa.ForeignKey("workflow_planning_sessions.id", ondelete="CASCADE"), nullable=False),
sa.Column("position", sa.Integer(), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False, server_default="proposed"),
sa.Column("strategy", sa.String(length=64), nullable=False, server_default="collaborative"),
sa.Column("title", sa.String(length=255), nullable=False),
sa.Column("summary", sa.Text(), nullable=False, server_default=""),
sa.Column("rationale", sa.Text(), nullable=False, server_default=""),
sa.Column("estimated_duration_seconds", sa.Integer(), nullable=True),
sa.Column("graph_json", text_type, nullable=False),
sa.Column("canvas_schema_json", text_type, nullable=False),
sa.Column("validation_json", text_type, nullable=False),
sa.Column("graph_revision", sa.Integer(), nullable=False, server_default="0"),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("session_id", "position", name="uq_workflow_planning_proposals_position"),
)
op.create_index("ix_workflow_planning_proposals_session_id", "workflow_planning_proposals", ["session_id"])
op.create_index("ix_workflow_planning_proposals_status", "workflow_planning_proposals", ["status"])
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if inspector.has_table("workflow_planning_proposals"):
op.drop_table("workflow_planning_proposals")
if inspector.has_table("workflow_planning_sessions"):
op.drop_table("workflow_planning_sessions")
Loaded 100 of 3008 files, more files were not shown because too many files have changed in this diff. Show more