M6:缘契、人格与世界——契约版本链、铸魂分灵、河图境界与三界分流
- 缘契域 domains/yuanqi:covenants(当前版)+ covenant_events(不可变历史);提议—问心—铭契—撤回全链;边界变更立即生效;多维关系并存,服务层拒绝 affinity/好感度单一键;浪漫维度成人资格标记位 - 道体铸魂与分灵 domains/jingsheng/soul.py:soul_forgings 确认流(锚点变更 pending→confirmed 应用并签发新魂籍版本,确认前人物锚点不变);分灵创建新人物(继承资料与谱系 lineage 链、不继承原身份,魂籍从 v1 起) - 河图域 domains/hetu:persistent_worlds 境界 + world_entities/world_relations 境界作用域重建 + 世谱挂接;境界正史视图(scope=persistent_world 归真集合);canonize 后置推进正史计数 - 三界分流:reality→息壤提取(不变);persistent_world→境界实录+正史推进;simulation→只记试演实录;factual_records 增 scope 列——境界/幻境实录与真界本相隔离 - 正影打通:引文 target_type=memory 时被引记忆 superseded → 返回 successor_memory_id 提示,不静默替换 - 前端:人物详情页缘契面板(提议维度选择/铭契/撤回/事件史)+ 世界页重建(境界目录/实体/正史概览)+ covenants/worlds api 库 - 退役:旧 personality/drive/evolution/world 模块、服务、端点、仓储、schema、前端五页与组件样式;迁移 007 退役九张旧表与 characters.current_personality_version_id - 验收(test_m6_domains 六用例):多维无单一好感度/铭契版本链/事件不可抹除/撤回立即生效/边界即时/铸魂确认流+魂籍版本/分灵谱系/境界正史不进真界(实录 scope 隔离+真界候选=0)/引文正影后继 - 四套件:后端 379、前端 199、BFF 4、神识 5 包全绿(2 个预存环境失败不变);迁移 007 净库+±1 干净
This commit is contained in:
1 parent
684261f4b4
commit
7e23d6fa84
108 files changed
+2600
-9732
No files matched your search
@@ -0,0 +1,5 @@
|
||||
"""河图世界域:境界(persistent_worlds)、世界实体与关系、境界正史(M6)。"""
|
||||
|
||||
from app.domains.hetu import models, service # noqa: F401
|
||||
|
||||
__all__ = ["models", "service"]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""河图世界 API(/worlds):境界 CRUD、实体关系、正史视图。"""
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.v1.deps import get_current_user
|
||||
from app.domains.hetu import service
|
||||
from app.schemas.auth import CurrentUser
|
||||
|
||||
world_router = APIRouter(prefix="/worlds", tags=["hetu"])
|
||||
|
||||
|
||||
class CreateWorldRequest(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
description: str = ""
|
||||
rules: dict = Field(default_factory=dict)
|
||||
lorebook_id: str | None = None
|
||||
|
||||
|
||||
class UpdateWorldRequest(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
rules: dict | None = None
|
||||
lorebook_id: str | None = None
|
||||
|
||||
|
||||
class EntityRequest(BaseModel):
|
||||
kind: str = "concept"
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
description: str = ""
|
||||
attrs: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
class RelationRequest(BaseModel):
|
||||
source_entity_id: str
|
||||
target_entity_id: str
|
||||
relation: str = Field(min_length=1, max_length=80)
|
||||
note: str = ""
|
||||
|
||||
|
||||
@world_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_world(
|
||||
payload: CreateWorldRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.create_world(
|
||||
owner_scope=user.owner_scope, name=payload.name, description=payload.description,
|
||||
rules=payload.rules, lorebook_id=payload.lorebook_id,
|
||||
)
|
||||
|
||||
|
||||
@world_router.get("")
|
||||
async def list_worlds(user: CurrentUser = Depends(get_current_user)) -> list[dict]:
|
||||
return await service.list_worlds(user.owner_scope)
|
||||
|
||||
|
||||
@world_router.get("/{world_id}")
|
||||
async def get_world(world_id: str, user: CurrentUser = Depends(get_current_user)) -> dict:
|
||||
return await service.get_world(world_id, user.owner_scope)
|
||||
|
||||
|
||||
@world_router.patch("/{world_id}")
|
||||
async def update_world(
|
||||
world_id: str, payload: UpdateWorldRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.update_world(
|
||||
world_id, user.owner_scope, name=payload.name, description=payload.description,
|
||||
rules=payload.rules, lorebook_id=payload.lorebook_id,
|
||||
)
|
||||
|
||||
|
||||
@world_router.delete("/{world_id}")
|
||||
async def archive_world(world_id: str, user: CurrentUser = Depends(get_current_user)) -> dict:
|
||||
return await service.archive_world(world_id, user.owner_scope)
|
||||
|
||||
|
||||
@world_router.post("/{world_id}/entities", status_code=status.HTTP_201_CREATED)
|
||||
async def add_entity(
|
||||
world_id: str, payload: EntityRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.add_entity(
|
||||
world_id, user.owner_scope, kind=payload.kind, name=payload.name,
|
||||
description=payload.description, attrs=payload.attrs,
|
||||
)
|
||||
|
||||
|
||||
@world_router.get("/{world_id}/entities")
|
||||
async def list_entities(world_id: str, user: CurrentUser = Depends(get_current_user)) -> list[dict]:
|
||||
return await service.list_entities(world_id, user.owner_scope)
|
||||
|
||||
|
||||
@world_router.post("/{world_id}/relations", status_code=status.HTTP_201_CREATED)
|
||||
async def add_relation(
|
||||
world_id: str, payload: RelationRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.add_relation(
|
||||
world_id, user.owner_scope, source_entity_id=payload.source_entity_id,
|
||||
target_entity_id=payload.target_entity_id, relation=payload.relation, note=payload.note,
|
||||
)
|
||||
|
||||
|
||||
@world_router.get("/{world_id}/relations")
|
||||
async def list_relations(world_id: str, user: CurrentUser = Depends(get_current_user)) -> list[dict]:
|
||||
return await service.list_relations(world_id, user.owner_scope)
|
||||
|
||||
|
||||
@world_router.get("/{world_id}/chronicle")
|
||||
async def world_chronicle(world_id: str, user: CurrentUser = Depends(get_current_user)) -> dict:
|
||||
return await service.world_chronicle(world_id, user.owner_scope)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""河图世界域表模型:境界(persistent_worlds)与世界认知实体/关系。
|
||||
|
||||
设计依据 core-domains.md §4 三界与 data-model.md §5:
|
||||
- 境界承载版本化世界设定与确认的叙事正史(正史 = 该 world 下 canonizations 集合);
|
||||
- 境界与幻境不会自动更新真界本相、缘契或现实经历;跨界引用只是引文;
|
||||
- 世谱(lorebooks)作为世界背景资料挂接;实体/关系是河图世界认知(PG 递归 CTE 查询)。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.ids import new_id
|
||||
from app.core.time import utc_now
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class PersistentWorld(Base):
|
||||
"""境界:世界背景、规则与世谱挂接;正史版本随 canonizations 演进。"""
|
||||
|
||||
__tablename__ = "persistent_worlds"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(80), primary_key=True, default=lambda: new_id("world"))
|
||||
owner_scope: Mapped[str] = mapped_column(String(80), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(120), nullable=False)
|
||||
description: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# 世界规则与设定(自由结构;组装境界运行时上下文)
|
||||
rules_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
|
||||
# 世谱挂接(lorebook id;世界背景资料经世谱激活管线进入投影)
|
||||
lorebook_id: Mapped[str | None] = mapped_column(String(80), index=True)
|
||||
# 正史版本号:该世界下 canonization 计数(视图派生,此列为缓存计数)
|
||||
canon_count: Mapped[int] = mapped_column(nullable=False, default=0)
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="active")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now)
|
||||
|
||||
|
||||
class WorldEntity(Base):
|
||||
"""河图世界实体:境界内的人物/地点/组织/物品认知(世界作用域)。"""
|
||||
|
||||
__tablename__ = "world_entities"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(80), primary_key=True, default=lambda: new_id("wentity"))
|
||||
world_id: Mapped[str] = mapped_column(
|
||||
String(80), ForeignKey("persistent_worlds.id"), nullable=False, index=True
|
||||
)
|
||||
# character / location / organization / item / concept(河图实体类型)
|
||||
kind: Mapped[str] = mapped_column(String(30), nullable=False, default="concept")
|
||||
name: Mapped[str] = mapped_column(String(120), nullable=False)
|
||||
description: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# 属性与不确定性(河图:状态与不确定性认知)
|
||||
attrs_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
|
||||
|
||||
|
||||
class WorldRelation(Base):
|
||||
"""河图世界关系:实体间有向关系(图查询走 PG 递归 CTE)。"""
|
||||
|
||||
__tablename__ = "world_relations"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(80), primary_key=True, default=lambda: new_id("wrel"))
|
||||
world_id: Mapped[str] = mapped_column(
|
||||
String(80), ForeignKey("persistent_worlds.id"), nullable=False, index=True
|
||||
)
|
||||
source_entity_id: Mapped[str] = mapped_column(
|
||||
String(80), ForeignKey("world_entities.id"), nullable=False, index=True
|
||||
)
|
||||
target_entity_id: Mapped[str] = mapped_column(
|
||||
String(80), ForeignKey("world_entities.id"), nullable=False, index=True
|
||||
)
|
||||
relation: Mapped[str] = mapped_column(String(80), nullable=False)
|
||||
note: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
|
||||
@@ -0,0 +1,238 @@
|
||||
"""河图世界域应用服务:境界 CRUD、实体与关系、境界正史视图。
|
||||
|
||||
铁律(core-domains.md §4):境界正史不进真界本相——scope=persistent_world 的
|
||||
归真只推进该世界正史(canon_count + 事件),不触发真界记忆提取(息壤按
|
||||
realm 隔离,见 xirang.on_canonized 的 scope 分流)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.core.time import utc_now
|
||||
from app.db.session import AsyncSessionLocal
|
||||
from app.domains.hetu.models import PersistentWorld, WorldEntity, WorldRelation
|
||||
from app.domains import one_qi
|
||||
from app.models.mirror_tree import Canonization
|
||||
|
||||
|
||||
async def create_world(
|
||||
*, owner_scope: str, name: str, description: str, rules: dict, lorebook_id: str | None
|
||||
) -> dict:
|
||||
async with AsyncSessionLocal() as session:
|
||||
world = PersistentWorld(
|
||||
owner_scope=owner_scope,
|
||||
name=name,
|
||||
description=description,
|
||||
rules_json=json.dumps(rules or {}, ensure_ascii=False),
|
||||
lorebook_id=lorebook_id,
|
||||
)
|
||||
session.add(world)
|
||||
await session.commit()
|
||||
session.expunge(world)
|
||||
return _world_dict(world)
|
||||
|
||||
|
||||
async def list_worlds(owner_scope: str) -> list[dict]:
|
||||
async with AsyncSessionLocal() as session:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(PersistentWorld)
|
||||
.where(PersistentWorld.owner_scope == owner_scope, PersistentWorld.status != "archived")
|
||||
.order_by(PersistentWorld.updated_at.desc())
|
||||
)
|
||||
).scalars().all()
|
||||
return [_world_dict(r) for r in rows]
|
||||
|
||||
|
||||
async def get_world(world_id: str, owner_scope: str) -> dict:
|
||||
return _world_dict(await _owned(world_id, owner_scope))
|
||||
|
||||
|
||||
async def update_world(
|
||||
world_id: str, owner_scope: str, *, name: str | None, description: str | None,
|
||||
rules: dict | None, lorebook_id: str | None,
|
||||
) -> dict:
|
||||
await _owned(world_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
world = await session.get(PersistentWorld, world_id)
|
||||
if name is not None:
|
||||
world.name = name
|
||||
if description is not None:
|
||||
world.description = description
|
||||
if rules is not None:
|
||||
world.rules_json = json.dumps(rules, ensure_ascii=False)
|
||||
if lorebook_id is not None:
|
||||
world.lorebook_id = lorebook_id
|
||||
world.updated_at = utc_now()
|
||||
await session.commit()
|
||||
session.expunge(world)
|
||||
return _world_dict(world)
|
||||
|
||||
|
||||
async def archive_world(world_id: str, owner_scope: str) -> dict:
|
||||
await _owned(world_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
world = await session.get(PersistentWorld, world_id)
|
||||
world.status = "archived"
|
||||
await session.commit()
|
||||
return {"world_id": world_id, "status": "archived"}
|
||||
|
||||
|
||||
# ── 实体与关系(河图世界认知) ──
|
||||
|
||||
|
||||
async def add_entity(
|
||||
world_id: str, owner_scope: str, *, kind: str, name: str, description: str, attrs: dict
|
||||
) -> dict:
|
||||
await _owned(world_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
entity = WorldEntity(
|
||||
world_id=world_id, kind=kind, name=name, description=description,
|
||||
attrs_json=json.dumps(attrs or {}, ensure_ascii=False),
|
||||
)
|
||||
session.add(entity)
|
||||
await session.commit()
|
||||
session.expunge(entity)
|
||||
return _entity_dict(entity)
|
||||
|
||||
|
||||
async def list_entities(world_id: str, owner_scope: str) -> list[dict]:
|
||||
await _owned(world_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(WorldEntity).where(WorldEntity.world_id == world_id)
|
||||
.order_by(WorldEntity.created_at.asc())
|
||||
)
|
||||
).scalars().all()
|
||||
return [_entity_dict(r) for r in rows]
|
||||
|
||||
|
||||
async def add_relation(
|
||||
world_id: str, owner_scope: str, *, source_entity_id: str, target_entity_id: str,
|
||||
relation: str, note: str,
|
||||
) -> dict:
|
||||
await _owned(world_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
for eid in (source_entity_id, target_entity_id):
|
||||
entity = await session.get(WorldEntity, eid)
|
||||
if entity is None or entity.world_id != world_id:
|
||||
raise AppError("invalid_request", f"实体 {eid} 不属于该境界。")
|
||||
row = WorldRelation(
|
||||
world_id=world_id, source_entity_id=source_entity_id,
|
||||
target_entity_id=target_entity_id, relation=relation, note=note,
|
||||
)
|
||||
session.add(row)
|
||||
await session.commit()
|
||||
session.expunge(row)
|
||||
return {
|
||||
"id": row.id, "source": source_entity_id, "target": target_entity_id,
|
||||
"relation": relation, "note": note,
|
||||
}
|
||||
|
||||
|
||||
async def list_relations(world_id: str, owner_scope: str) -> list[dict]:
|
||||
await _owned(world_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(WorldRelation).where(WorldRelation.world_id == world_id)
|
||||
.order_by(WorldRelation.created_at.asc())
|
||||
)
|
||||
).scalars().all()
|
||||
return [
|
||||
{
|
||||
"id": r.id, "source": r.source_entity_id, "target": r.target_entity_id,
|
||||
"relation": r.relation, "note": r.note,
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
# ── 境界正史 ──
|
||||
|
||||
|
||||
async def world_chronicle(world_id: str, owner_scope: str) -> dict:
|
||||
"""境界正史:该 world 下 scope=persistent_world 的归真集合(只读视图)。"""
|
||||
await _owned(world_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(Canonization)
|
||||
.where(Canonization.world_id == world_id, Canonization.scope == "persistent_world")
|
||||
.order_by(Canonization.created_at.asc())
|
||||
)
|
||||
).scalars().all()
|
||||
return {
|
||||
"world_id": world_id,
|
||||
"entries": [
|
||||
{
|
||||
"canonization_id": c.id,
|
||||
"tree_id": c.tree_id,
|
||||
"endpoint_node_id": c.endpoint_node_id,
|
||||
"path_nodes": json.loads(c.path_nodes_json or "[]"),
|
||||
"created_at": c.created_at.isoformat() if c.created_at else None,
|
||||
}
|
||||
for c in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def on_world_canonized(world_id: str) -> None:
|
||||
"""境界归真后置:推进正史计数(由镜树 canonize 的 world 分支调用)。"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
world = await session.get(PersistentWorld, world_id)
|
||||
if world is None:
|
||||
return
|
||||
count = (
|
||||
await session.execute(
|
||||
select(func.count()).select_from(Canonization).where(
|
||||
Canonization.world_id == world_id,
|
||||
Canonization.scope == "persistent_world",
|
||||
)
|
||||
)
|
||||
).scalar_one()
|
||||
world.canon_count = int(count)
|
||||
world.updated_at = utc_now()
|
||||
await session.commit()
|
||||
await one_qi.emit(
|
||||
"world.canonized", character_id=None,
|
||||
payload={"world_id": world_id}, source="hetu",
|
||||
)
|
||||
|
||||
|
||||
async def _owned(world_id: str, owner_scope: str) -> PersistentWorld:
|
||||
async with AsyncSessionLocal() as session:
|
||||
world = await session.get(PersistentWorld, world_id)
|
||||
if world is None or world.owner_scope != owner_scope:
|
||||
raise AppError("not_found", "境界不存在。", status_code=404)
|
||||
session.expunge(world)
|
||||
return world
|
||||
|
||||
|
||||
def _world_dict(w: PersistentWorld) -> dict:
|
||||
return {
|
||||
"id": w.id,
|
||||
"name": w.name,
|
||||
"description": w.description,
|
||||
"rules": json.loads(w.rules_json or "{}"),
|
||||
"lorebook_id": w.lorebook_id,
|
||||
"canon_count": w.canon_count,
|
||||
"status": w.status,
|
||||
"created_at": w.created_at.isoformat() if w.created_at else None,
|
||||
"updated_at": w.updated_at.isoformat() if w.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _entity_dict(e: WorldEntity) -> dict:
|
||||
return {
|
||||
"id": e.id,
|
||||
"kind": e.kind,
|
||||
"name": e.name,
|
||||
"description": e.description,
|
||||
"attrs": json.loads(e.attrs_json or "{}"),
|
||||
}
|
||||
Reference in new issue
Block a user