state_manager.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. State Manager - 状态管理模块 (v5.1)
  5. 管理 state.json 的读写操作:
  6. - 实体状态管理
  7. - 进度追踪
  8. - 关系记录
  9. v5.1 变更:
  10. - 集成 SQLStateManager,同步写入 SQLite (index.db)
  11. - state.json 保留精简数据,大数据自动迁移到 SQLite
  12. """
  13. import json
  14. from pathlib import Path
  15. from typing import Dict, List, Optional, Any
  16. from dataclasses import dataclass, field, asdict
  17. from datetime import datetime
  18. import filelock
  19. from .config import get_config
  20. try:
  21. # 当 scripts 目录在 sys.path 中(常见:从 scripts/ 运行)
  22. from security_utils import atomic_write_json, read_json_safe
  23. except ImportError: # pragma: no cover
  24. # 当以 `python -m scripts.data_modules...` 从仓库根目录运行
  25. from scripts.security_utils import atomic_write_json, read_json_safe
  26. @dataclass
  27. class EntityState:
  28. """实体状态"""
  29. id: str
  30. name: str
  31. type: str # 角色/地点/物品/势力
  32. tier: str = "装饰" # 核心/支线/装饰
  33. aliases: List[str] = field(default_factory=list)
  34. attributes: Dict[str, Any] = field(default_factory=dict)
  35. first_appearance: int = 0
  36. last_appearance: int = 0
  37. @dataclass
  38. class Relationship:
  39. """实体关系"""
  40. from_entity: str
  41. to_entity: str
  42. type: str
  43. description: str
  44. chapter: int
  45. @dataclass
  46. class StateChange:
  47. """状态变化记录"""
  48. entity_id: str
  49. field: str
  50. old_value: Any
  51. new_value: Any
  52. reason: str
  53. chapter: int
  54. timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
  55. @dataclass
  56. class _EntityPatch:
  57. """待写入的实体增量补丁(用于锁内合并)"""
  58. entity_type: str
  59. entity_id: str
  60. replace: bool = False
  61. base_entity: Optional[Dict[str, Any]] = None # 新建实体时的完整快照(用于填充缺失字段)
  62. top_updates: Dict[str, Any] = field(default_factory=dict)
  63. current_updates: Dict[str, Any] = field(default_factory=dict)
  64. appearance_chapter: Optional[int] = None
  65. class StateManager:
  66. """状态管理器 (v5.1 entities_v3 格式 + SQLite 同步)"""
  67. # v5.0 支持的实体类型
  68. ENTITY_TYPES = ["角色", "地点", "物品", "势力", "招式"]
  69. def __init__(self, config=None, enable_sqlite_sync: bool = True):
  70. """
  71. 初始化状态管理器
  72. 参数:
  73. - config: 配置对象
  74. - enable_sqlite_sync: 是否启用 SQLite 同步 (默认 True)
  75. """
  76. self.config = config or get_config()
  77. self._state: Dict[str, Any] = {}
  78. # 与 security_utils.atomic_write_json 保持一致:state.json.lock
  79. self._lock_path = self.config.state_file.with_suffix(self.config.state_file.suffix + ".lock")
  80. # v5.1: SQLite 同步
  81. self._enable_sqlite_sync = enable_sqlite_sync
  82. self._sql_state_manager = None
  83. if enable_sqlite_sync:
  84. try:
  85. from .sql_state_manager import SQLStateManager
  86. self._sql_state_manager = SQLStateManager(self.config)
  87. except ImportError:
  88. pass # SQLStateManager 不可用时静默降级
  89. # 待写入的增量(锁内重读 + 合并 + 写入)
  90. self._pending_entity_patches: Dict[tuple[str, str], _EntityPatch] = {}
  91. self._pending_alias_entries: Dict[str, List[Dict[str, str]]] = {}
  92. self._pending_state_changes: List[Dict[str, Any]] = []
  93. self._pending_structured_relationships: List[Dict[str, Any]] = []
  94. self._pending_disambiguation_warnings: List[Dict[str, Any]] = []
  95. self._pending_disambiguation_pending: List[Dict[str, Any]] = []
  96. self._pending_progress_chapter: Optional[int] = None
  97. self._pending_progress_words_delta: int = 0
  98. # v5.1: 缓存待同步到 SQLite 的数据
  99. self._pending_sqlite_data: Dict[str, Any] = {
  100. "entities_appeared": [],
  101. "entities_new": [],
  102. "state_changes": [],
  103. "relationships_new": [],
  104. "chapter": None
  105. }
  106. self._load_state()
  107. def _now_progress_timestamp(self) -> str:
  108. return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  109. def _ensure_state_schema(self, state: Dict[str, Any]) -> Dict[str, Any]:
  110. """确保 state.json 具备运行所需的关键字段(尽量不破坏既有数据)。"""
  111. if not isinstance(state, dict):
  112. state = {}
  113. state.setdefault("project_info", {})
  114. state.setdefault("progress", {})
  115. state.setdefault("protagonist_state", {})
  116. # relationships: 旧版本可能是 list(实体关系),v5.0 运行态用 dict(人物关系/重要关系)
  117. relationships = state.get("relationships")
  118. if isinstance(relationships, list):
  119. state.setdefault("structured_relationships", [])
  120. if isinstance(state.get("structured_relationships"), list):
  121. state["structured_relationships"].extend(relationships)
  122. state["relationships"] = {}
  123. elif not isinstance(relationships, dict):
  124. state["relationships"] = {}
  125. state.setdefault("world_settings", {"power_system": [], "factions": [], "locations": []})
  126. state.setdefault("plot_threads", {"active_threads": [], "foreshadowing": []})
  127. state.setdefault("review_checkpoints", [])
  128. state.setdefault(
  129. "strand_tracker",
  130. {
  131. "last_quest_chapter": 0,
  132. "last_fire_chapter": 0,
  133. "last_constellation_chapter": 0,
  134. "current_dominant": "quest",
  135. "chapters_since_switch": 0,
  136. "history": [],
  137. },
  138. )
  139. entities_v3 = state.get("entities_v3")
  140. if not isinstance(entities_v3, dict):
  141. entities_v3 = {}
  142. state["entities_v3"] = entities_v3
  143. for t in self.ENTITY_TYPES:
  144. if not isinstance(entities_v3.get(t), dict):
  145. entities_v3[t] = {}
  146. if not isinstance(state.get("alias_index"), dict):
  147. state["alias_index"] = {}
  148. if not isinstance(state.get("state_changes"), list):
  149. state["state_changes"] = []
  150. if not isinstance(state.get("structured_relationships"), list):
  151. state["structured_relationships"] = []
  152. if not isinstance(state.get("disambiguation_warnings"), list):
  153. state["disambiguation_warnings"] = []
  154. if not isinstance(state.get("disambiguation_pending"), list):
  155. state["disambiguation_pending"] = []
  156. # progress 基础字段
  157. progress = state["progress"]
  158. if not isinstance(progress, dict):
  159. progress = {}
  160. state["progress"] = progress
  161. progress.setdefault("current_chapter", 0)
  162. progress.setdefault("total_words", 0)
  163. progress.setdefault("last_updated", self._now_progress_timestamp())
  164. return state
  165. def _load_state(self):
  166. """加载状态文件"""
  167. if self.config.state_file.exists():
  168. self._state = read_json_safe(self.config.state_file, default={})
  169. self._state = self._ensure_state_schema(self._state)
  170. else:
  171. self._state = self._ensure_state_schema({})
  172. def save_state(self):
  173. """
  174. 保存状态文件(锁内重读 + 合并 + 原子写入)。
  175. 解决多 Agent 并行下的“读-改-写覆盖”风险:
  176. - 获取锁
  177. - 重新读取磁盘最新 state.json
  178. - 仅合并本实例产生的增量(pending_*)
  179. - 原子化写入
  180. """
  181. # 无增量时不写入,避免无意义覆盖
  182. has_pending = any(
  183. [
  184. self._pending_entity_patches,
  185. self._pending_alias_entries,
  186. self._pending_state_changes,
  187. self._pending_structured_relationships,
  188. self._pending_disambiguation_warnings,
  189. self._pending_disambiguation_pending,
  190. self._pending_progress_chapter is not None,
  191. self._pending_progress_words_delta != 0,
  192. ]
  193. )
  194. if not has_pending:
  195. return
  196. self.config.ensure_dirs()
  197. lock = filelock.FileLock(str(self._lock_path), timeout=10)
  198. try:
  199. with lock:
  200. disk_state = read_json_safe(self.config.state_file, default={})
  201. disk_state = self._ensure_state_schema(disk_state)
  202. # progress(合并为 max(chapter) + words_delta 累加)
  203. if self._pending_progress_chapter is not None or self._pending_progress_words_delta != 0:
  204. progress = disk_state.get("progress", {})
  205. if not isinstance(progress, dict):
  206. progress = {}
  207. disk_state["progress"] = progress
  208. try:
  209. current_chapter = int(progress.get("current_chapter", 0) or 0)
  210. except (TypeError, ValueError):
  211. current_chapter = 0
  212. if self._pending_progress_chapter is not None:
  213. progress["current_chapter"] = max(current_chapter, int(self._pending_progress_chapter))
  214. if self._pending_progress_words_delta:
  215. try:
  216. total_words = int(progress.get("total_words", 0) or 0)
  217. except (TypeError, ValueError):
  218. total_words = 0
  219. progress["total_words"] = total_words + int(self._pending_progress_words_delta)
  220. progress["last_updated"] = self._now_progress_timestamp()
  221. # entities_v3(按补丁应用)
  222. entities_v3 = disk_state.get("entities_v3", {})
  223. if not isinstance(entities_v3, dict):
  224. entities_v3 = {}
  225. disk_state["entities_v3"] = entities_v3
  226. for t in self.ENTITY_TYPES:
  227. if not isinstance(entities_v3.get(t), dict):
  228. entities_v3[t] = {}
  229. for (entity_type, entity_id), patch in self._pending_entity_patches.items():
  230. bucket = entities_v3.setdefault(entity_type, {})
  231. if not isinstance(bucket, dict):
  232. bucket = {}
  233. entities_v3[entity_type] = bucket
  234. entity = bucket.get(entity_id)
  235. if not isinstance(entity, dict):
  236. entity = {}
  237. bucket[entity_id] = entity
  238. # 新建实体时:只填充缺失字段,避免覆盖并发写入的更完整信息
  239. if patch.base_entity:
  240. for k, v in patch.base_entity.items():
  241. if k not in entity:
  242. entity[k] = v
  243. elif isinstance(entity.get(k), dict) and isinstance(v, dict):
  244. # 递归填充缺失
  245. for kk, vv in v.items():
  246. if kk not in entity[k]:
  247. entity[k][kk] = vv
  248. # top-level updates(明确写入)
  249. for k, v in patch.top_updates.items():
  250. entity[k] = v
  251. # current updates(明确写入)
  252. if patch.current_updates:
  253. current = entity.get("current")
  254. if not isinstance(current, dict):
  255. current = {}
  256. entity["current"] = current
  257. current.update(patch.current_updates)
  258. # appearance updates(first=min(non-zero), last=max)
  259. if patch.appearance_chapter is not None:
  260. chapter = int(patch.appearance_chapter)
  261. try:
  262. first = int(entity.get("first_appearance", 0) or 0)
  263. except (TypeError, ValueError):
  264. first = 0
  265. try:
  266. last = int(entity.get("last_appearance", 0) or 0)
  267. except (TypeError, ValueError):
  268. last = 0
  269. if first <= 0:
  270. entity["first_appearance"] = chapter
  271. else:
  272. entity["first_appearance"] = min(first, chapter)
  273. entity["last_appearance"] = max(last, chapter)
  274. # alias_index(一对多:合并去重)
  275. alias_index = disk_state.get("alias_index", {})
  276. if not isinstance(alias_index, dict):
  277. alias_index = {}
  278. disk_state["alias_index"] = alias_index
  279. for alias, entries in self._pending_alias_entries.items():
  280. if not alias:
  281. continue
  282. existing = alias_index.get(alias)
  283. if not isinstance(existing, list):
  284. existing = []
  285. alias_index[alias] = existing
  286. for entry in entries:
  287. et = entry.get("type")
  288. eid = entry.get("id")
  289. if not et or not eid:
  290. continue
  291. if any(e.get("type") == et and e.get("id") == eid for e in existing if isinstance(e, dict)):
  292. continue
  293. existing.append({"type": et, "id": eid})
  294. # state_changes(追加)
  295. if self._pending_state_changes:
  296. changes = disk_state.get("state_changes")
  297. if not isinstance(changes, list):
  298. changes = []
  299. disk_state["state_changes"] = changes
  300. changes.extend(self._pending_state_changes)
  301. # structured_relationships(追加去重)
  302. if self._pending_structured_relationships:
  303. rels = disk_state.get("structured_relationships")
  304. if not isinstance(rels, list):
  305. rels = []
  306. disk_state["structured_relationships"] = rels
  307. def _rel_key(r: Dict[str, Any]) -> tuple:
  308. return (
  309. r.get("from_entity"),
  310. r.get("to_entity"),
  311. r.get("type"),
  312. r.get("description"),
  313. r.get("chapter"),
  314. )
  315. existing_keys = {_rel_key(r) for r in rels if isinstance(r, dict)}
  316. for r in self._pending_structured_relationships:
  317. if not isinstance(r, dict):
  318. continue
  319. k = _rel_key(r)
  320. if k in existing_keys:
  321. continue
  322. rels.append(r)
  323. existing_keys.add(k)
  324. # disambiguation_warnings(追加去重 + 截断)
  325. if self._pending_disambiguation_warnings:
  326. warnings_list = disk_state.get("disambiguation_warnings")
  327. if not isinstance(warnings_list, list):
  328. warnings_list = []
  329. disk_state["disambiguation_warnings"] = warnings_list
  330. def _warn_key(w: Dict[str, Any]) -> tuple:
  331. return (
  332. w.get("chapter"),
  333. w.get("mention"),
  334. w.get("chosen_id"),
  335. w.get("confidence"),
  336. )
  337. existing_keys = {_warn_key(w) for w in warnings_list if isinstance(w, dict)}
  338. for w in self._pending_disambiguation_warnings:
  339. if not isinstance(w, dict):
  340. continue
  341. k = _warn_key(w)
  342. if k in existing_keys:
  343. continue
  344. warnings_list.append(w)
  345. existing_keys.add(k)
  346. # 只保留最近 N 条,避免文件无限增长
  347. max_keep = self.config.max_disambiguation_warnings
  348. if len(warnings_list) > max_keep:
  349. disk_state["disambiguation_warnings"] = warnings_list[-max_keep:]
  350. # disambiguation_pending(追加去重 + 截断)
  351. if self._pending_disambiguation_pending:
  352. pending_list = disk_state.get("disambiguation_pending")
  353. if not isinstance(pending_list, list):
  354. pending_list = []
  355. disk_state["disambiguation_pending"] = pending_list
  356. def _pending_key(w: Dict[str, Any]) -> tuple:
  357. return (
  358. w.get("chapter"),
  359. w.get("mention"),
  360. w.get("suggested_id"),
  361. w.get("confidence"),
  362. )
  363. existing_keys = {_pending_key(w) for w in pending_list if isinstance(w, dict)}
  364. for w in self._pending_disambiguation_pending:
  365. if not isinstance(w, dict):
  366. continue
  367. k = _pending_key(w)
  368. if k in existing_keys:
  369. continue
  370. pending_list.append(w)
  371. existing_keys.add(k)
  372. max_keep = self.config.max_disambiguation_pending
  373. if len(pending_list) > max_keep:
  374. disk_state["disambiguation_pending"] = pending_list[-max_keep:]
  375. # 原子写入(锁已持有,不再二次加锁)
  376. atomic_write_json(self.config.state_file, disk_state, use_lock=False, backup=True)
  377. # 同步内存为磁盘最新快照,并清空增量队列
  378. self._state = disk_state
  379. self._pending_entity_patches.clear()
  380. self._pending_alias_entries.clear()
  381. self._pending_state_changes.clear()
  382. self._pending_structured_relationships.clear()
  383. self._pending_disambiguation_warnings.clear()
  384. self._pending_disambiguation_pending.clear()
  385. self._pending_progress_chapter = None
  386. self._pending_progress_words_delta = 0
  387. # v5.1: 同步到 SQLite
  388. self._sync_to_sqlite()
  389. except filelock.Timeout:
  390. raise RuntimeError("无法获取 state.json 文件锁,请稍后重试")
  391. def _sync_to_sqlite(self):
  392. """v5.1: 同步待处理数据到 SQLite"""
  393. if not self._sql_state_manager:
  394. return
  395. sqlite_data = self._pending_sqlite_data
  396. chapter = sqlite_data.get("chapter")
  397. if chapter is None:
  398. # 清空并返回
  399. self._clear_pending_sqlite_data()
  400. return
  401. try:
  402. self._sql_state_manager.process_chapter_entities(
  403. chapter=chapter,
  404. entities_appeared=sqlite_data.get("entities_appeared", []),
  405. entities_new=sqlite_data.get("entities_new", []),
  406. state_changes=sqlite_data.get("state_changes", []),
  407. relationships_new=sqlite_data.get("relationships_new", [])
  408. )
  409. except Exception:
  410. pass # SQLite 同步失败时静默降级,不影响主流程
  411. finally:
  412. self._clear_pending_sqlite_data()
  413. def _clear_pending_sqlite_data(self):
  414. """清空待同步的 SQLite 数据"""
  415. self._pending_sqlite_data = {
  416. "entities_appeared": [],
  417. "entities_new": [],
  418. "state_changes": [],
  419. "relationships_new": [],
  420. "chapter": None
  421. }
  422. # ==================== 进度管理 ====================
  423. def get_current_chapter(self) -> int:
  424. """获取当前章节号"""
  425. return self._state.get("progress", {}).get("current_chapter", 0)
  426. def update_progress(self, chapter: int, words: int = 0):
  427. """更新进度"""
  428. if "progress" not in self._state:
  429. self._state["progress"] = {}
  430. self._state["progress"]["current_chapter"] = chapter
  431. if words > 0:
  432. total = self._state["progress"].get("total_words", 0)
  433. self._state["progress"]["total_words"] = total + words
  434. # 记录增量:锁内合并时用 max(chapter) + words_delta 累加
  435. if self._pending_progress_chapter is None:
  436. self._pending_progress_chapter = chapter
  437. else:
  438. self._pending_progress_chapter = max(self._pending_progress_chapter, chapter)
  439. if words > 0:
  440. self._pending_progress_words_delta += int(words)
  441. # ==================== 实体管理 (v5.0 entities_v3) ====================
  442. def get_entity(self, entity_id: str, entity_type: str = None) -> Optional[Dict]:
  443. """获取实体 (v5.0 entities_v3 格式)"""
  444. entities_v3 = self._state.get("entities_v3", {})
  445. if entity_type:
  446. return entities_v3.get(entity_type, {}).get(entity_id)
  447. # 遍历所有类型查找
  448. for type_name, entities in entities_v3.items():
  449. if entity_id in entities:
  450. return entities[entity_id]
  451. return None
  452. def get_entity_type(self, entity_id: str) -> Optional[str]:
  453. """获取实体所属类型"""
  454. for type_name, entities in self._state.get("entities_v3", {}).items():
  455. if entity_id in entities:
  456. return type_name
  457. return None
  458. def get_all_entities(self) -> Dict[str, Dict]:
  459. """获取所有实体(扁平化视图,兼容旧代码)"""
  460. result = {}
  461. for type_name, entities in self._state.get("entities_v3", {}).items():
  462. for eid, e in entities.items():
  463. result[eid] = {**e, "type": type_name}
  464. return result
  465. def get_entities_by_type(self, entity_type: str) -> Dict[str, Dict]:
  466. """按类型获取实体"""
  467. return self._state.get("entities_v3", {}).get(entity_type, {})
  468. def get_entities_by_tier(self, tier: str) -> Dict[str, Dict]:
  469. """按层级获取实体"""
  470. result = {}
  471. for type_name, entities in self._state.get("entities_v3", {}).items():
  472. for eid, e in entities.items():
  473. if e.get("tier") == tier:
  474. result[eid] = {**e, "type": type_name}
  475. return result
  476. def add_entity(self, entity: EntityState) -> bool:
  477. """添加新实体 (v5.0 entities_v3 格式)"""
  478. entity_type = entity.type
  479. if entity_type not in self.ENTITY_TYPES:
  480. entity_type = "角色"
  481. if "entities_v3" not in self._state:
  482. self._state["entities_v3"] = {t: {} for t in self.ENTITY_TYPES}
  483. if entity_type not in self._state["entities_v3"]:
  484. self._state["entities_v3"][entity_type] = {}
  485. # 检查是否已存在
  486. if entity.id in self._state["entities_v3"][entity_type]:
  487. return False
  488. # 转换为 v3 格式
  489. v3_entity = {
  490. "canonical_name": entity.name,
  491. "tier": entity.tier,
  492. "desc": "",
  493. "current": entity.attributes,
  494. "first_appearance": entity.first_appearance,
  495. "last_appearance": entity.last_appearance,
  496. "history": []
  497. }
  498. self._state["entities_v3"][entity_type][entity.id] = v3_entity
  499. # 记录实体补丁(新建:仅填充缺失字段,避免覆盖并发写入)
  500. patch = self._pending_entity_patches.get((entity_type, entity.id))
  501. if patch is None:
  502. patch = _EntityPatch(entity_type=entity_type, entity_id=entity.id)
  503. self._pending_entity_patches[(entity_type, entity.id)] = patch
  504. patch.replace = True
  505. patch.base_entity = v3_entity
  506. # 注册别名到 alias_index
  507. self._register_alias_internal(entity.id, entity_type, entity.name)
  508. for alias in entity.aliases:
  509. self._register_alias_internal(entity.id, entity_type, alias)
  510. return True
  511. def _register_alias_internal(self, entity_id: str, entity_type: str, alias: str):
  512. """内部方法:注册别名到 state.json 的 alias_index"""
  513. if not alias:
  514. return
  515. if "alias_index" not in self._state:
  516. self._state["alias_index"] = {}
  517. if alias not in self._state["alias_index"]:
  518. self._state["alias_index"][alias] = []
  519. # 检查是否已存在
  520. exists = any(
  521. e.get("type") == entity_type and e.get("id") == entity_id
  522. for e in self._state["alias_index"][alias]
  523. )
  524. if not exists:
  525. self._state["alias_index"][alias].append({
  526. "type": entity_type,
  527. "id": entity_id
  528. })
  529. # 记录待合并增量:避免锁外读-改-写覆盖
  530. pending = self._pending_alias_entries.setdefault(alias, [])
  531. if not any(e.get("type") == entity_type and e.get("id") == entity_id for e in pending):
  532. pending.append({"type": entity_type, "id": entity_id})
  533. def update_entity(self, entity_id: str, updates: Dict[str, Any], entity_type: str = None) -> bool:
  534. """更新实体属性 (v5.0)"""
  535. # 查找实体
  536. if entity_type:
  537. if entity_id not in self._state.get("entities_v3", {}).get(entity_type, {}):
  538. return False
  539. entity = self._state["entities_v3"][entity_type][entity_id]
  540. else:
  541. entity_type = self.get_entity_type(entity_id)
  542. if not entity_type:
  543. return False
  544. entity = self._state["entities_v3"][entity_type][entity_id]
  545. for key, value in updates.items():
  546. if key == "attributes" and isinstance(value, dict):
  547. # v5.0: attributes 存在 current 字段
  548. if "current" not in entity:
  549. entity["current"] = {}
  550. entity["current"].update(value)
  551. # 记录补丁(current 增量)
  552. patch = self._pending_entity_patches.get((entity_type, entity_id))
  553. if patch is None:
  554. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  555. self._pending_entity_patches[(entity_type, entity_id)] = patch
  556. patch.current_updates.update(value)
  557. elif key == "current" and isinstance(value, dict):
  558. if "current" not in entity:
  559. entity["current"] = {}
  560. entity["current"].update(value)
  561. patch = self._pending_entity_patches.get((entity_type, entity_id))
  562. if patch is None:
  563. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  564. self._pending_entity_patches[(entity_type, entity_id)] = patch
  565. patch.current_updates.update(value)
  566. else:
  567. entity[key] = value
  568. patch = self._pending_entity_patches.get((entity_type, entity_id))
  569. if patch is None:
  570. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  571. self._pending_entity_patches[(entity_type, entity_id)] = patch
  572. patch.top_updates[key] = value
  573. return True
  574. def update_entity_appearance(self, entity_id: str, chapter: int, entity_type: str = None):
  575. """更新实体出场章节"""
  576. if not entity_type:
  577. entity_type = self.get_entity_type(entity_id)
  578. if not entity_type:
  579. return
  580. entity = self._state["entities_v3"][entity_type].get(entity_id)
  581. if entity:
  582. if entity.get("first_appearance", 0) == 0:
  583. entity["first_appearance"] = chapter
  584. entity["last_appearance"] = chapter
  585. # 记录补丁:锁内应用 first=min(non-zero), last=max
  586. patch = self._pending_entity_patches.get((entity_type, entity_id))
  587. if patch is None:
  588. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  589. self._pending_entity_patches[(entity_type, entity_id)] = patch
  590. if patch.appearance_chapter is None:
  591. patch.appearance_chapter = chapter
  592. else:
  593. patch.appearance_chapter = max(int(patch.appearance_chapter), int(chapter))
  594. # ==================== 状态变化记录 ====================
  595. def record_state_change(
  596. self,
  597. entity_id: str,
  598. field: str,
  599. old_value: Any,
  600. new_value: Any,
  601. reason: str,
  602. chapter: int
  603. ):
  604. """记录状态变化"""
  605. if "state_changes" not in self._state:
  606. self._state["state_changes"] = []
  607. change = StateChange(
  608. entity_id=entity_id,
  609. field=field,
  610. old_value=old_value,
  611. new_value=new_value,
  612. reason=reason,
  613. chapter=chapter
  614. )
  615. change_dict = asdict(change)
  616. self._state["state_changes"].append(change_dict)
  617. self._pending_state_changes.append(change_dict)
  618. # 同时更新实体属性
  619. self.update_entity(entity_id, {"attributes": {field: new_value}})
  620. def get_state_changes(self, entity_id: Optional[str] = None) -> List[Dict]:
  621. """获取状态变化历史"""
  622. changes = self._state.get("state_changes", [])
  623. if entity_id:
  624. changes = [c for c in changes if c.get("entity_id") == entity_id]
  625. return changes
  626. # ==================== 关系管理 ====================
  627. def add_relationship(
  628. self,
  629. from_entity: str,
  630. to_entity: str,
  631. rel_type: str,
  632. description: str,
  633. chapter: int
  634. ):
  635. """添加关系"""
  636. rel = Relationship(
  637. from_entity=from_entity,
  638. to_entity=to_entity,
  639. type=rel_type,
  640. description=description,
  641. chapter=chapter
  642. )
  643. # v5.0: 实体关系存入 structured_relationships,避免与 relationships(人物关系字典) 冲突
  644. if "structured_relationships" not in self._state:
  645. self._state["structured_relationships"] = []
  646. rel_dict = asdict(rel)
  647. self._state["structured_relationships"].append(rel_dict)
  648. self._pending_structured_relationships.append(rel_dict)
  649. def get_relationships(self, entity_id: Optional[str] = None) -> List[Dict]:
  650. """获取关系列表"""
  651. rels = self._state.get("structured_relationships", [])
  652. if entity_id:
  653. rels = [
  654. r for r in rels
  655. if r.get("from_entity") == entity_id or r.get("to_entity") == entity_id
  656. ]
  657. return rels
  658. # ==================== 批量操作 ====================
  659. def _record_disambiguation(self, chapter: int, uncertain_items: Any) -> List[str]:
  660. """
  661. 记录消歧反馈到 state.json,便于 Writer/Context Agent 感知风险。
  662. 约定:
  663. - >= extraction_confidence_medium:写入 disambiguation_warnings(采用但警告)
  664. - < extraction_confidence_medium:写入 disambiguation_pending(需人工确认)
  665. """
  666. if not isinstance(uncertain_items, list) or not uncertain_items:
  667. return []
  668. warnings: List[str] = []
  669. now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  670. for item in uncertain_items:
  671. if not isinstance(item, dict):
  672. continue
  673. mention = str(item.get("mention", "") or "").strip()
  674. if not mention:
  675. continue
  676. raw_conf = item.get("confidence", 0.0)
  677. try:
  678. confidence = float(raw_conf)
  679. except (TypeError, ValueError):
  680. confidence = 0.0
  681. # 候选:支持 [{"type","id"}...] 或 ["id1","id2"] 两种形式
  682. candidates_raw = item.get("candidates", [])
  683. candidates: List[Dict[str, str]] = []
  684. if isinstance(candidates_raw, list):
  685. for c in candidates_raw:
  686. if isinstance(c, dict):
  687. cid = str(c.get("id", "") or "").strip()
  688. ctype = str(c.get("type", "") or "").strip()
  689. entry: Dict[str, str] = {}
  690. if ctype:
  691. entry["type"] = ctype
  692. if cid:
  693. entry["id"] = cid
  694. if entry:
  695. candidates.append(entry)
  696. else:
  697. cid = str(c).strip()
  698. if cid:
  699. candidates.append({"id": cid})
  700. entity_type = str(item.get("type", "") or "").strip()
  701. suggested_id = str(item.get("suggested", "") or "").strip()
  702. adopted_raw = item.get("adopted", None)
  703. chosen_id = ""
  704. if isinstance(adopted_raw, str):
  705. chosen_id = adopted_raw.strip()
  706. elif adopted_raw is True:
  707. chosen_id = suggested_id
  708. else:
  709. # 兼容字段名:entity_id / chosen_id
  710. chosen_id = str(item.get("entity_id") or item.get("chosen_id") or "").strip() or suggested_id
  711. context = str(item.get("context", "") or "").strip()
  712. note = str(item.get("warning", "") or "").strip()
  713. record: Dict[str, Any] = {
  714. "chapter": int(chapter),
  715. "mention": mention,
  716. "type": entity_type,
  717. "suggested_id": suggested_id,
  718. "chosen_id": chosen_id,
  719. "confidence": confidence,
  720. "candidates": candidates,
  721. "context": context,
  722. "note": note,
  723. "created_at": now,
  724. }
  725. if confidence >= float(self.config.extraction_confidence_medium):
  726. self._state.setdefault("disambiguation_warnings", []).append(record)
  727. self._pending_disambiguation_warnings.append(record)
  728. chosen_part = f" → {chosen_id}" if chosen_id else ""
  729. warnings.append(f"消歧警告: {mention}{chosen_part} (confidence: {confidence:.2f})")
  730. else:
  731. self._state.setdefault("disambiguation_pending", []).append(record)
  732. self._pending_disambiguation_pending.append(record)
  733. warnings.append(f"消歧需人工确认: {mention} (confidence: {confidence:.2f})")
  734. return warnings
  735. def process_chapter_result(self, chapter: int, result: Dict) -> List[str]:
  736. """
  737. 处理 Data Agent 的章节处理结果 (v5.1)
  738. 输入格式:
  739. - entities_appeared: 出场实体列表
  740. - entities_new: 新实体列表
  741. - state_changes: 状态变化列表
  742. - relationships_new: 新关系列表
  743. 返回警告列表
  744. """
  745. warnings = []
  746. # v5.1: 记录章节号用于 SQLite 同步
  747. self._pending_sqlite_data["chapter"] = chapter
  748. # 处理出场实体
  749. for entity in result.get("entities_appeared", []):
  750. entity_id = entity.get("id")
  751. entity_type = entity.get("type")
  752. if entity_id:
  753. self.update_entity_appearance(entity_id, chapter, entity_type)
  754. # v5.1: 缓存用于 SQLite 同步
  755. self._pending_sqlite_data["entities_appeared"].append(entity)
  756. # 处理新实体
  757. for entity in result.get("entities_new", []):
  758. entity_id = entity.get("suggested_id") or entity.get("id")
  759. if entity_id and entity_id != "NEW":
  760. new_entity = EntityState(
  761. id=entity_id,
  762. name=entity.get("name", ""),
  763. type=entity.get("type", "角色"),
  764. tier=entity.get("tier", "装饰"),
  765. aliases=entity.get("mentions", []),
  766. first_appearance=chapter,
  767. last_appearance=chapter
  768. )
  769. if not self.add_entity(new_entity):
  770. warnings.append(f"实体已存在: {entity_id}")
  771. # v5.1: 缓存用于 SQLite 同步
  772. self._pending_sqlite_data["entities_new"].append(entity)
  773. # 处理状态变化
  774. for change in result.get("state_changes", []):
  775. self.record_state_change(
  776. entity_id=change.get("entity_id", ""),
  777. field=change.get("field", ""),
  778. old_value=change.get("old"),
  779. new_value=change.get("new"),
  780. reason=change.get("reason", ""),
  781. chapter=chapter
  782. )
  783. # v5.1: 缓存用于 SQLite 同步
  784. self._pending_sqlite_data["state_changes"].append(change)
  785. # 处理关系
  786. for rel in result.get("relationships_new", []):
  787. self.add_relationship(
  788. from_entity=rel.get("from", ""),
  789. to_entity=rel.get("to", ""),
  790. rel_type=rel.get("type", ""),
  791. description=rel.get("description", ""),
  792. chapter=chapter
  793. )
  794. # v5.1: 缓存用于 SQLite 同步
  795. self._pending_sqlite_data["relationships_new"].append(rel)
  796. # 处理消歧不确定项(不影响实体写入,但必须对 Writer 可见)
  797. warnings.extend(self._record_disambiguation(chapter, result.get("uncertain", [])))
  798. # 更新进度
  799. self.update_progress(chapter)
  800. # 同步主角状态(entities_v3 → protagonist_state)
  801. self.sync_protagonist_from_entity()
  802. return warnings
  803. # ==================== 导出 ====================
  804. def export_for_context(self) -> Dict:
  805. """导出用于上下文的精简版状态 (v5.0)"""
  806. # 从 entities_v3 构建精简视图
  807. entities_flat = {}
  808. for type_name, entities in self._state.get("entities_v3", {}).items():
  809. for eid, e in entities.items():
  810. entities_flat[eid] = {
  811. "name": e.get("canonical_name", eid),
  812. "type": type_name,
  813. "tier": e.get("tier", "装饰"),
  814. "current": e.get("current", {})
  815. }
  816. return {
  817. "progress": self._state.get("progress", {}),
  818. "entities": entities_flat,
  819. "alias_index": self._state.get("alias_index", {}),
  820. "recent_changes": self._state.get("state_changes", [])[-self.config.export_recent_changes_slice:],
  821. "disambiguation": {
  822. "warnings": self._state.get("disambiguation_warnings", [])[-self.config.export_disambiguation_slice:],
  823. "pending": self._state.get("disambiguation_pending", [])[-self.config.export_disambiguation_slice:],
  824. },
  825. }
  826. # ==================== 主角同步 ====================
  827. def get_protagonist_entity_id(self) -> Optional[str]:
  828. """获取主角实体 ID(通过 is_protagonist 标记或 protagonist_state.name 查找)"""
  829. # 方式1: 查找 is_protagonist 标记
  830. for eid, e in self._state.get("entities_v3", {}).get("角色", {}).items():
  831. if e.get("is_protagonist"):
  832. return eid
  833. # 方式2: 通过 protagonist_state.name 查找
  834. protag_name = self._state.get("protagonist_state", {}).get("name")
  835. if protag_name:
  836. alias_entries = self._state.get("alias_index", {}).get(protag_name, [])
  837. for entry in alias_entries:
  838. if entry.get("type") == "角色":
  839. return entry.get("id")
  840. return None
  841. def sync_protagonist_from_entity(self, entity_id: str = None):
  842. """
  843. 将 entities_v3 中主角实体的状态同步到 protagonist_state
  844. 用于确保 consistency-checker 等依赖 protagonist_state 的组件获取最新数据
  845. """
  846. if entity_id is None:
  847. entity_id = self.get_protagonist_entity_id()
  848. if entity_id is None:
  849. return
  850. entity = self.get_entity(entity_id, "角色")
  851. if not entity:
  852. return
  853. current = entity.get("current", {})
  854. protag = self._state.setdefault("protagonist_state", {})
  855. # 同步境界
  856. if "realm" in current:
  857. power = protag.setdefault("power", {})
  858. power["realm"] = current["realm"]
  859. if "layer" in current:
  860. power["layer"] = current["layer"]
  861. # 同步位置
  862. if "location" in current:
  863. loc = protag.setdefault("location", {})
  864. loc["current"] = current["location"]
  865. if "last_chapter" in current:
  866. loc["last_chapter"] = current["last_chapter"]
  867. def sync_protagonist_to_entity(self, entity_id: str = None):
  868. """
  869. 将 protagonist_state 同步到 entities_v3 中的主角实体
  870. 用于初始化或手动编辑 protagonist_state 后保持一致性
  871. """
  872. if entity_id is None:
  873. entity_id = self.get_protagonist_entity_id()
  874. if entity_id is None:
  875. return
  876. protag = self._state.get("protagonist_state", {})
  877. if not protag:
  878. return
  879. updates = {}
  880. # 同步境界
  881. power = protag.get("power", {})
  882. if power.get("realm"):
  883. updates["realm"] = power["realm"]
  884. if power.get("layer"):
  885. updates["layer"] = power["layer"]
  886. # 同步位置
  887. loc = protag.get("location", {})
  888. if loc.get("current"):
  889. updates["location"] = loc["current"]
  890. if updates:
  891. self.update_entity(entity_id, updates, "角色")
  892. # ==================== CLI 接口 ====================
  893. def main():
  894. import argparse
  895. parser = argparse.ArgumentParser(description="State Manager CLI")
  896. parser.add_argument("--project-root", type=str, help="项目根目录")
  897. subparsers = parser.add_subparsers(dest="command")
  898. # 获取进度
  899. subparsers.add_parser("get-progress")
  900. # 获取实体
  901. get_entity_parser = subparsers.add_parser("get-entity")
  902. get_entity_parser.add_argument("--id", required=True, help="实体ID")
  903. # 列出实体
  904. list_parser = subparsers.add_parser("list-entities")
  905. list_parser.add_argument("--type", help="按类型过滤")
  906. list_parser.add_argument("--tier", help="按层级过滤")
  907. # 处理章节结果
  908. process_parser = subparsers.add_parser("process-chapter")
  909. process_parser.add_argument("--chapter", type=int, required=True, help="章节号")
  910. process_parser.add_argument("--data", required=True, help="JSON 格式的处理结果")
  911. args = parser.parse_args()
  912. # 初始化
  913. config = None
  914. if args.project_root:
  915. from .config import DataModulesConfig
  916. config = DataModulesConfig.from_project_root(args.project_root)
  917. manager = StateManager(config)
  918. if args.command == "get-progress":
  919. print(json.dumps(manager._state.get("progress", {}), ensure_ascii=False, indent=2))
  920. elif args.command == "get-entity":
  921. entity = manager.get_entity(args.id)
  922. if entity:
  923. print(json.dumps(entity, ensure_ascii=False, indent=2))
  924. else:
  925. print(f"未找到实体: {args.id}")
  926. elif args.command == "list-entities":
  927. if args.type:
  928. entities = manager.get_entities_by_type(args.type)
  929. elif args.tier:
  930. entities = manager.get_entities_by_tier(args.tier)
  931. else:
  932. entities = manager.get_all_entities()
  933. for eid, e in entities.items():
  934. print(f"{eid}: {e.get('name')} ({e.get('type')}/{e.get('tier')})")
  935. elif args.command == "process-chapter":
  936. data = json.loads(args.data)
  937. warnings = manager.process_chapter_result(args.chapter, data)
  938. manager.save_state()
  939. print(f"✓ 已处理第 {args.chapter} 章")
  940. if warnings:
  941. print("警告:")
  942. for w in warnings:
  943. print(f" - {w}")
  944. if __name__ == "__main__":
  945. main()