fix(qa): 实施 4 组设计型 QA 项——规则删除/codex 角色/大纲卷过滤/文风回炉锚点

#5 规则 DELETE + id:暴露 RuleView.id(PK);新增 DELETE /projects/{id}/rules/{rule_id}
  (项目/规则不存在→404,成功→204,按 (id,project_id) 限定);rule_repo 加
  list_for_project/delete;RulesPage 每条加删除(乐观删+回滚+toast)。assemble 侧
  RuleView(缓存前缀)不动,列表另立 RuleListItemView。
#7 codex 角色 relations:写侧本已持久化、读端点 _existing_characters 硬编码 []。
  加 _relations_from_jsonb 解析 {name,kind,note},CodexPage 渲染关系 chip。
#8 角色入库幂等:SqlCharacterWriteRepo.create 改 (project_id,name) app 层 upsert——
  重复入库改更新而非插入;不加 UNIQUE/迁移(线上已有重复行会让约束迁移失败)。
#1 大纲卷过滤:GET /outline 支持可选 ?volume(无参=全部,向后兼容);OutlineEditor
  加「查看:全部/卷N」筛选,与生成目标卷解耦。
H3/#9 文风回炉锚点:StyleDriftSegment 加 text(逐字命中段),style.md 指示审稿输出;
  前端按内容锚点定位回炉目标(idx 仅排序),命中失败 → 提示「无法定位该段」而非
  静默 no-op。style golden fixture 已重生成。

契约变更已 pnpm gen:api(RuleView.id / DELETE rules / outline ?volume)。无迁移
(alembic 无漂移)。门禁绿:ruff/mypy(210)/alembic/pytest 760 · 前端 tsc/lint/vitest 329。
This commit is contained in:
Yaojia Wang
2026-06-25 12:53:03 +02:00
parent e60eff7aa1
commit bf39f50b2f
33 changed files with 907 additions and 99 deletions

View File

@@ -30,7 +30,7 @@ from ww_agents import (
)
from ww_core.domain.character_repo import CharacterWriteView
from ww_core.domain.project_repo import ProjectCreate
from ww_core.domain.repositories import RuleView
from ww_core.domain.rule_repo import RuleListItemView
from ww_llm_gateway.types import LlmRequest, LlmResponse, ServedBy, Usage
from ww_shared import AppError, ErrorCode
from ww_skills import SkillRegistry
@@ -81,8 +81,27 @@ class _FakeCharacterWriteRepo:
tags: list[Any],
relations: list[dict[str, Any]],
) -> CharacterWriteView:
# 幂等:按 (project_id, name) upsert——同名更新既有行而非插重复镜像 Sql 实现)。
existing = next(
(r for r in self.rows if r["project_id"] == project_id and r["name"] == name),
None,
)
if existing is not None:
existing.update(
{
"role": role,
"traits": list(traits),
"arc": arc,
"speech_tics": list(speech_tics),
"tags": list(tags),
"relations": [dict(r) for r in relations],
}
)
return CharacterWriteView(id=existing["id"], name=name, role=role)
row_id = uuid.uuid4()
self.rows.append(
{
"id": row_id,
"project_id": project_id,
"name": name,
"role": role,
@@ -93,14 +112,16 @@ class _FakeCharacterWriteRepo:
"relations": [dict(r) for r in relations],
}
)
return CharacterWriteView(id=uuid.uuid4(), name=name, role=role)
return CharacterWriteView(id=row_id, name=name, role=role)
class _FakeRulesReadRepo:
def __init__(self, rules: list[RuleView] | None = None) -> None:
"""实现规则 repo 的读侧 `list_for_project`(带 id供 list_rules 端点)。"""
def __init__(self, rules: list[RuleListItemView] | None = None) -> None:
self._rules = rules or []
async def all_for_project(self, project_id: uuid.UUID) -> list[RuleView]:
async def list_for_project(self, project_id: uuid.UUID) -> list[RuleListItemView]:
return list(self._rules)
@@ -170,7 +191,7 @@ def _make_app(
get_memory_repos,
get_precheck_gateway,
get_project_repo,
get_rules_read_repo,
get_rule_write_repo,
get_skill_registry,
get_worldbuilder_gateway,
)
@@ -190,7 +211,7 @@ def _make_app(
(lambda: memory) if memory is not None else _empty_memory_repos
)
app.dependency_overrides[get_character_write_repo] = lambda: char_repo
app.dependency_overrides[get_rules_read_repo] = lambda: rules_repo
app.dependency_overrides[get_rule_write_repo] = lambda: rules_repo
app.dependency_overrides[get_skill_registry] = lambda: registry
app.dependency_overrides[get_session] = lambda: session
gw = _raise_no_creds if no_creds else (lambda: gateway)
@@ -370,6 +391,118 @@ async def test_ingest_characters_acknowledged_conflict_writes() -> None:
assert len(char_repo.rows) == 1
@pytest.mark.asyncio
async def test_ingest_same_name_twice_updates_not_duplicates() -> None:
# Arrange同一项目、同名角色入库两次第二次字段不同。
repo = FakeProjectRepo()
pid = await _seed_project(repo)
gateway = _SchemaRoutingGateway({ContinuityReview: _no_conflicts()})
char_repo = _FakeCharacterWriteRepo()
app, _ = _make_app(project_repo=repo, gateway=gateway, char_repo=char_repo)
def _payload(role: str, trait: str) -> dict[str, Any]:
return {
"cards": [
{
"name": "叶寒",
"role": role,
"traits": [trait],
"backstory": "孤儿",
"arc": "成长",
"speech_tics": [],
"tags": [],
"relations": [],
}
]
}
async with _client(app) as client:
# Act先入主角/腹黑,再以同名入对手/隐忍。
first = await client.post(f"/projects/{pid}/characters", json=_payload("主角", "腹黑"))
second = await client.post(f"/projects/{pid}/characters", json=_payload("对手", "隐忍"))
# Assert仍是一行按 name upsert字段被更新而非新增重复。
assert first.status_code == 201
assert second.status_code == 201
assert len(char_repo.rows) == 1
assert char_repo.rows[0]["role"] == "对手"
assert char_repo.rows[0]["traits"] == ["隐忍"]
@pytest.mark.asyncio
async def test_ingest_relations_persist_on_write() -> None:
# Arrange入库带关系网的角色卡。
repo = FakeProjectRepo()
pid = await _seed_project(repo)
gateway = _SchemaRoutingGateway({ContinuityReview: _no_conflicts()})
char_repo = _FakeCharacterWriteRepo()
app, _ = _make_app(project_repo=repo, gateway=gateway, char_repo=char_repo)
relations = [{"name": "苏离", "kind": "宿敌", "note": "灭门之仇"}]
async with _client(app) as client:
resp = await client.post(
f"/projects/{pid}/characters",
json={
"cards": [
{
"name": "叶寒",
"role": "主角",
"traits": ["腹黑"],
"backstory": "孤儿",
"arc": "成长",
"speech_tics": [],
"tags": [],
"relations": relations,
}
]
},
)
# Assertrelations 持久化(写侧未丢)。
assert resp.status_code == 201
assert char_repo.rows[0]["relations"] == relations
def test_relations_from_jsonb_parses_and_skips_dirty() -> None:
# Arrange混入脏条目非 dict / 缺 name / 缺 kind
from ww_api.routers.generation import _relations_from_jsonb
raw = [
{"name": "苏离", "kind": "宿敌", "note": "灭门之仇"},
{"name": "无类型"}, # 缺 kind → 跳过
{"kind": "无名"}, # 缺 name → 跳过
"not-a-dict", # 非 dict → 跳过
{"name": "墨白", "kind": "师徒"}, # note 可缺
]
# Act
out = _relations_from_jsonb(raw)
# Assert只保留有效两条note 缺为 None。
assert [(r.name, r.kind, r.note) for r in out] == [
("苏离", "宿敌", "灭门之仇"),
("墨白", "师徒", None),
]
@pytest.mark.asyncio
async def test_list_characters_includes_relations() -> None:
# Arrange读侧 memory view 带 relationsJSONB list
repo = FakeProjectRepo()
pid = await _seed_project(repo)
app, _ = _make_app(
project_repo=repo,
gateway=_SchemaRoutingGateway({}),
memory=_codex_memory_with_relations(),
)
async with _client(app) as client:
resp = await client.get(f"/projects/{pid}/characters")
# Assert读端点不再丢 relations修 #7
assert resp.status_code == 200
card = resp.json()["characters"][0]
assert card["relations"] == [{"name": "苏离", "kind": "宿敌", "note": "灭门之仇"}]
# ---- 读端点 ----
@@ -377,10 +510,11 @@ async def test_ingest_characters_acknowledged_conflict_writes() -> None:
async def test_list_rules_returns_rules() -> None:
repo = FakeProjectRepo()
pid = await _seed_project(repo)
rid1, rid2 = uuid.uuid4(), uuid.uuid4()
rules_repo = _FakeRulesReadRepo(
[
RuleView(level="project", content="主角不复活"),
RuleView(level="global", content="无脏话"),
RuleListItemView(id=rid1, level="project", content="主角不复活"),
RuleListItemView(id=rid2, level="global", content="无脏话"),
]
)
gateway = _SchemaRoutingGateway({})
@@ -392,6 +526,8 @@ async def test_list_rules_returns_rules() -> None:
assert resp.status_code == 200
rules = resp.json()["rules"]
assert [r["content"] for r in rules] == ["主角不复活", "无脏话"]
# 列表带稳定 id前端删除 handle
assert [r["id"] for r in rules] == [str(rid1), str(rid2)]
@pytest.mark.asyncio
@@ -466,6 +602,53 @@ def _codex_memory() -> Any:
)
def _codex_memory_with_relations() -> Any:
"""MemoryRepos角色行携 relationsJSONB list验读端点还原关系网修 #7"""
from test_projects import (
_EmptyDigestRepo,
_EmptyForeshadowRepo,
_EmptyOutlineRepo,
_EmptyRulesRepo,
_EmptyStyleRepo,
_StubProjectSpecRepo,
)
from ww_core.domain.repositories import (
CharacterView,
MemoryRepos,
WorldEntityView,
)
class _CharRepo:
async def list_for_project(self, project_id: uuid.UUID) -> list[CharacterView]:
return [
CharacterView(
name="叶寒",
role="主角",
traits={"items": ["腹黑"]},
backstory="孤儿出身",
arc={"text": "成长"},
speech_tics={"items": []},
tags=[],
relations=[{"name": "苏离", "kind": "宿敌", "note": "灭门之仇"}],
)
]
class _WorldRepo:
async def list_for_project(self, project_id: uuid.UUID) -> list[WorldEntityView]:
return []
return MemoryRepos(
outline=_EmptyOutlineRepo(),
character=_CharRepo(),
world_entity=_WorldRepo(),
digest=_EmptyDigestRepo(),
foreshadow=_EmptyForeshadowRepo(),
style=_EmptyStyleRepo(),
rules=_EmptyRulesRepo(),
project=_StubProjectSpecRepo(),
)
@pytest.mark.asyncio
async def test_list_characters_unpacks_jsonb_to_api_shape() -> None:
repo = FakeProjectRepo()

View File

@@ -239,6 +239,31 @@ async def test_get_outline_returns_persisted_chapters_in_order_with_unpacked_bea
assert body["chapters"][1]["beats"] == ["冲突升级"]
@pytest.mark.asyncio
async def test_get_outline_with_volume_filters_to_that_volume() -> None:
# ?volume=N 只返回该卷章节;无该参数返回全部(向后兼容)。
project_repo = FakeProjectRepo()
pid = await _seed_project(project_repo)
read_repo = FakeOutlineReadRepo()
read_repo.add_chapter(pid, volume=1, chapter_no=1, beats=["卷一·开篇"])
read_repo.add_chapter(pid, volume=1, chapter_no=2, beats=["卷一·冲突"])
read_repo.add_chapter(pid, volume=2, chapter_no=3, beats=["卷二·新篇"])
client = _make_read_client(project_repo=project_repo, outline_read_repo=read_repo)
async with client:
all_resp = await client.get(f"/projects/{pid}/outline")
vol2_resp = await client.get(f"/projects/{pid}/outline?volume=2")
# 不带 volume → 全部三章。
assert all_resp.status_code == 200
assert [c["no"] for c in all_resp.json()["chapters"]] == [1, 2, 3]
# ?volume=2 → 仅卷二的第 3 章。
assert vol2_resp.status_code == 200
vol2_chapters = vol2_resp.json()["chapters"]
assert [c["no"] for c in vol2_chapters] == [3]
assert all(c["volume"] == 2 for c in vol2_chapters)
@pytest.mark.asyncio
async def test_get_outline_returns_empty_list_when_no_outline() -> None:
project_repo = FakeProjectRepo()

View File

@@ -17,7 +17,7 @@ from cryptography.fernet import Fernet
from fakes_projects import FakeProjectRepo, FakeSession
from ww_api.services.credentials import STUB_OWNER_ID
from ww_core.domain.project_repo import ProjectView
from ww_core.domain.rule_repo import RuleWriteView
from ww_core.domain.rule_repo import RuleListItemView, RuleWriteView
class _FakeRuleWriteRepo:
@@ -25,10 +25,22 @@ class _FakeRuleWriteRepo:
self.rows: list[RuleWriteView] = []
async def create(self, project_id: uuid.UUID, *, level: str, content: str) -> RuleWriteView:
view = RuleWriteView(project_id=project_id, level=level, content=content)
view = RuleWriteView(id=uuid.uuid4(), project_id=project_id, level=level, content=content)
self.rows.append(view)
return view
async def list_for_project(self, project_id: uuid.UUID) -> list[RuleListItemView]:
return [
RuleListItemView(id=r.id, level=r.level, content=r.content)
for r in self.rows
if r.project_id in (project_id, None)
]
async def delete(self, project_id: uuid.UUID, rule_id: uuid.UUID) -> bool:
before = len(self.rows)
self.rows = [r for r in self.rows if not (r.id == rule_id and r.project_id == project_id)]
return len(self.rows) < before
def _make_client() -> tuple[
httpx.AsyncClient, _FakeRuleWriteRepo, FakeSession, FakeProjectRepo, uuid.UUID
@@ -72,6 +84,8 @@ async def test_create_rule_returns_201_and_commits() -> None:
body = resp.json()
assert body["level"] == "project"
assert body["content"] == "主角不许中途复活"
# 创建回显带 id前端删除 handle
assert body["id"] == str(repo.rows[0].id)
assert session.commits == 1
assert len(repo.rows) == 1
assert repo.rows[0].project_id == pid
@@ -124,3 +138,37 @@ async def test_create_rule_unknown_project_returns_404() -> None:
assert resp.status_code == 404
assert resp.json()["error"]["code"] == "NOT_FOUND"
assert len(repo.rows) == 0 # 未触达写库
@pytest.mark.asyncio
async def test_delete_rule_returns_204_and_commits() -> None:
# 作者显式删一条本作品规则(不变量 #3204 + 端点提交 + 行被移除。
client, repo, session, _project_repo, pid = _make_client()
seeded = await repo.create(pid, level="project", content="待删规则")
async with client:
resp = await client.delete(f"/projects/{pid}/rules/{seeded.id}")
assert resp.status_code == 204
assert session.commits == 1
assert len(repo.rows) == 0
@pytest.mark.asyncio
async def test_delete_rule_unknown_rule_returns_404() -> None:
# 未知 rule_id → 404不提交删不到行
client, repo, session, _project_repo, pid = _make_client()
async with client:
resp = await client.delete(f"/projects/{pid}/rules/{uuid.uuid4()}")
assert resp.status_code == 404
assert resp.json()["error"]["code"] == "NOT_FOUND"
assert session.commits == 0
@pytest.mark.asyncio
async def test_delete_rule_unknown_project_returns_404() -> None:
# 项目不存在 → 404先于 rule 查校验),不触达删除。
client, repo, session, _project_repo, _pid = _make_client()
async with client:
resp = await client.delete(f"/projects/{uuid.uuid4()}/rules/{uuid.uuid4()}")
assert resp.status_code == 404
assert resp.json()["error"]["code"] == "NOT_FOUND"
assert session.commits == 0

View File

@@ -103,7 +103,7 @@ class _FakeRuleWriteRepo:
async def create(self, project_id: uuid.UUID, *, level: str, content: str) -> RuleWriteView:
self.rows.append({"project_id": project_id, "level": level, "content": content})
return RuleWriteView(project_id=project_id, level=level, content=content)
return RuleWriteView(id=uuid.uuid4(), project_id=project_id, level=level, content=content)
class _FakeOutlineReadRepo: