feat(db): ai_messages 表 + 迁移——作者↔AI 往复聊天记录 append-only 侧表(AC-1)

计划 §2 canonical DDL:AiMessage(UuidPk, CreatedAt, Base),project_id(FK CASCADE)/
chapter_no(nullable=项目级)/thread_id/seq(repo 批内定序)/kind/tool_key/role(CHECK)/
content/meta(JSONB '{}'),append-only 无 updated_at。复合索引 (project_id,chapter_no,
created_at DESC) 手写 sa.text DESC + FK 单列索引。迁移 ceabd3c2c00d(down=f6a7b8c9d0e1),
autogenerate 仅捕获 ai_messages 无杂散漂移。T0.2 后第一张新业务表;旁路侧记录非手稿真源,
assemble()/agent 永不读(守 #1/#3/#6)。契约 C2 扩已「稳定」。
This commit is contained in:
Yaojia Wang
2026-07-09 16:39:24 +02:00
parent 9da938d39b
commit 1a188e6e5b
4 changed files with 118 additions and 1 deletions

View File

@@ -19,6 +19,7 @@ from sqlalchemy import (
LargeBinary,
Text,
UniqueConstraint,
Uuid,
text,
)
from sqlalchemy.dialects.postgresql import JSONB
@@ -231,6 +232,38 @@ class ChapterReview(UuidPk, CreatedAt, Base):
decisions: Mapped[dict[str, Any] | None] = mapped_column(JSONB)
class AiMessage(UuidPk, CreatedAt, Base):
"""作者↔AI 往复留痕append-only 辅助侧记录,非手稿真源)。
不喂 prompt、不改正文、永不被 assemble()/agent 读回生成链(守 #1/#3/#6
一行一条 bubble一次多轮交换用 thread_id 归组;同一 append 批次内 created_at
相同,靠 seq(批内 0 基位置) 稳定定序。仅 CreatedAt无 updated_at不可改写
"""
__tablename__ = "ai_messages"
__table_args__ = (
CheckConstraint("role IN ('author', 'ai')", name="ck_ai_messages_role"),
Index(
"ix_ai_messages_project_chapter",
"project_id",
"chapter_no",
text("created_at DESC"),
),
)
project_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("projects.id", ondelete="CASCADE"), nullable=False, index=True
)
chapter_no: Mapped[int | None] = mapped_column(Integer) # NULL = 项目级(工具箱)
thread_id: Mapped[uuid.UUID] = mapped_column(Uuid, nullable=False) # 客户端生成,归组一次交换
seq: Mapped[int] = mapped_column(Integer, nullable=False) # repo 赋值:批内 0 基位置
kind: Mapped[str] = mapped_column(Text, nullable=False) # 自由 Text边界 Literal 校验
tool_key: Mapped[str | None] = mapped_column(Text) # generator/continue其余 NULL
role: Mapped[str] = mapped_column(Text, nullable=False) # author | ai (有 CHECK)
content: Mapped[str] = mapped_column(Text, nullable=False) # 人读 bubble 文本(完整)
meta: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, server_default=text("'{}'"))
# id, created_at 来自 UuidPk / CreatedAt (TIMESTAMPTZ func.now())
# ---- 运营/系统表(续)----