state_manager.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. # v5.1: 检查是否已迁移到 SQLite
  222. # 如果启用了 SQLite 同步,则不再写入大数据字段到 state.json
  223. _migrated = self._enable_sqlite_sync and self._sql_state_manager is not None
  224. if not _migrated:
  225. # ==================== 旧模式:写入 state.json ====================
  226. # entities_v3(按补丁应用)
  227. entities_v3 = disk_state.get("entities_v3", {})
  228. if not isinstance(entities_v3, dict):
  229. entities_v3 = {}
  230. disk_state["entities_v3"] = entities_v3
  231. for t in self.ENTITY_TYPES:
  232. if not isinstance(entities_v3.get(t), dict):
  233. entities_v3[t] = {}
  234. for (entity_type, entity_id), patch in self._pending_entity_patches.items():
  235. bucket = entities_v3.setdefault(entity_type, {})
  236. if not isinstance(bucket, dict):
  237. bucket = {}
  238. entities_v3[entity_type] = bucket
  239. entity = bucket.get(entity_id)
  240. if not isinstance(entity, dict):
  241. entity = {}
  242. bucket[entity_id] = entity
  243. # 新建实体时:只填充缺失字段,避免覆盖并发写入的更完整信息
  244. if patch.base_entity:
  245. for k, v in patch.base_entity.items():
  246. if k not in entity:
  247. entity[k] = v
  248. elif isinstance(entity.get(k), dict) and isinstance(v, dict):
  249. # 递归填充缺失
  250. for kk, vv in v.items():
  251. if kk not in entity[k]:
  252. entity[k][kk] = vv
  253. # top-level updates(明确写入)
  254. for k, v in patch.top_updates.items():
  255. entity[k] = v
  256. # current updates(明确写入)
  257. if patch.current_updates:
  258. current = entity.get("current")
  259. if not isinstance(current, dict):
  260. current = {}
  261. entity["current"] = current
  262. current.update(patch.current_updates)
  263. # appearance updates(first=min(non-zero), last=max)
  264. if patch.appearance_chapter is not None:
  265. chapter = int(patch.appearance_chapter)
  266. try:
  267. first = int(entity.get("first_appearance", 0) or 0)
  268. except (TypeError, ValueError):
  269. first = 0
  270. try:
  271. last = int(entity.get("last_appearance", 0) or 0)
  272. except (TypeError, ValueError):
  273. last = 0
  274. if first <= 0:
  275. entity["first_appearance"] = chapter
  276. else:
  277. entity["first_appearance"] = min(first, chapter)
  278. entity["last_appearance"] = max(last, chapter)
  279. # alias_index(一对多:合并去重)
  280. alias_index = disk_state.get("alias_index", {})
  281. if not isinstance(alias_index, dict):
  282. alias_index = {}
  283. disk_state["alias_index"] = alias_index
  284. for alias, entries in self._pending_alias_entries.items():
  285. if not alias:
  286. continue
  287. existing = alias_index.get(alias)
  288. if not isinstance(existing, list):
  289. existing = []
  290. alias_index[alias] = existing
  291. for entry in entries:
  292. et = entry.get("type")
  293. eid = entry.get("id")
  294. if not et or not eid:
  295. continue
  296. if any(e.get("type") == et and e.get("id") == eid for e in existing if isinstance(e, dict)):
  297. continue
  298. existing.append({"type": et, "id": eid})
  299. # state_changes(追加)
  300. if self._pending_state_changes:
  301. changes = disk_state.get("state_changes")
  302. if not isinstance(changes, list):
  303. changes = []
  304. disk_state["state_changes"] = changes
  305. changes.extend(self._pending_state_changes)
  306. # structured_relationships(追加去重)
  307. if self._pending_structured_relationships:
  308. rels = disk_state.get("structured_relationships")
  309. if not isinstance(rels, list):
  310. rels = []
  311. disk_state["structured_relationships"] = rels
  312. def _rel_key(r: Dict[str, Any]) -> tuple:
  313. return (
  314. r.get("from_entity"),
  315. r.get("to_entity"),
  316. r.get("type"),
  317. r.get("description"),
  318. r.get("chapter"),
  319. )
  320. existing_keys = {_rel_key(r) for r in rels if isinstance(r, dict)}
  321. for r in self._pending_structured_relationships:
  322. if not isinstance(r, dict):
  323. continue
  324. k = _rel_key(r)
  325. if k in existing_keys:
  326. continue
  327. rels.append(r)
  328. existing_keys.add(k)
  329. else:
  330. # ==================== v5.1 模式:移除大数据字段 ====================
  331. # 确保 state.json 中不存在这些膨胀字段
  332. for field in ["entities_v3", "alias_index", "state_changes", "structured_relationships"]:
  333. disk_state.pop(field, None)
  334. # 标记已迁移
  335. disk_state["_migrated_to_sqlite"] = True
  336. # disambiguation_warnings(追加去重 + 截断)
  337. if self._pending_disambiguation_warnings:
  338. warnings_list = disk_state.get("disambiguation_warnings")
  339. if not isinstance(warnings_list, list):
  340. warnings_list = []
  341. disk_state["disambiguation_warnings"] = warnings_list
  342. def _warn_key(w: Dict[str, Any]) -> tuple:
  343. return (
  344. w.get("chapter"),
  345. w.get("mention"),
  346. w.get("chosen_id"),
  347. w.get("confidence"),
  348. )
  349. existing_keys = {_warn_key(w) for w in warnings_list if isinstance(w, dict)}
  350. for w in self._pending_disambiguation_warnings:
  351. if not isinstance(w, dict):
  352. continue
  353. k = _warn_key(w)
  354. if k in existing_keys:
  355. continue
  356. warnings_list.append(w)
  357. existing_keys.add(k)
  358. # 只保留最近 N 条,避免文件无限增长
  359. max_keep = self.config.max_disambiguation_warnings
  360. if len(warnings_list) > max_keep:
  361. disk_state["disambiguation_warnings"] = warnings_list[-max_keep:]
  362. # disambiguation_pending(追加去重 + 截断)
  363. if self._pending_disambiguation_pending:
  364. pending_list = disk_state.get("disambiguation_pending")
  365. if not isinstance(pending_list, list):
  366. pending_list = []
  367. disk_state["disambiguation_pending"] = pending_list
  368. def _pending_key(w: Dict[str, Any]) -> tuple:
  369. return (
  370. w.get("chapter"),
  371. w.get("mention"),
  372. w.get("suggested_id"),
  373. w.get("confidence"),
  374. )
  375. existing_keys = {_pending_key(w) for w in pending_list if isinstance(w, dict)}
  376. for w in self._pending_disambiguation_pending:
  377. if not isinstance(w, dict):
  378. continue
  379. k = _pending_key(w)
  380. if k in existing_keys:
  381. continue
  382. pending_list.append(w)
  383. existing_keys.add(k)
  384. max_keep = self.config.max_disambiguation_pending
  385. if len(pending_list) > max_keep:
  386. disk_state["disambiguation_pending"] = pending_list[-max_keep:]
  387. # 原子写入(锁已持有,不再二次加锁)
  388. atomic_write_json(self.config.state_file, disk_state, use_lock=False, backup=True)
  389. # 同步内存为磁盘最新快照,并清空增量队列
  390. self._state = disk_state
  391. self._pending_entity_patches.clear()
  392. self._pending_alias_entries.clear()
  393. self._pending_state_changes.clear()
  394. self._pending_structured_relationships.clear()
  395. self._pending_disambiguation_warnings.clear()
  396. self._pending_disambiguation_pending.clear()
  397. self._pending_progress_chapter = None
  398. self._pending_progress_words_delta = 0
  399. # v5.1: 同步到 SQLite
  400. self._sync_to_sqlite()
  401. except filelock.Timeout:
  402. raise RuntimeError("无法获取 state.json 文件锁,请稍后重试")
  403. def _sync_to_sqlite(self):
  404. """v5.1: 同步待处理数据到 SQLite"""
  405. if not self._sql_state_manager:
  406. return
  407. # 方式1: 通过 process_chapter_result 收集的数据
  408. sqlite_data = self._pending_sqlite_data
  409. chapter = sqlite_data.get("chapter")
  410. if chapter is not None:
  411. try:
  412. self._sql_state_manager.process_chapter_entities(
  413. chapter=chapter,
  414. entities_appeared=sqlite_data.get("entities_appeared", []),
  415. entities_new=sqlite_data.get("entities_new", []),
  416. state_changes=sqlite_data.get("state_changes", []),
  417. relationships_new=sqlite_data.get("relationships_new", [])
  418. )
  419. except Exception:
  420. pass # SQLite 同步失败时静默降级,不影响主流程
  421. # 方式2: 通过 add_entity/update_entity 等直接调用收集的数据
  422. # 这些数据存储在 _pending_entity_patches 等变量中
  423. self._sync_pending_patches_to_sqlite()
  424. # 清空
  425. self._clear_pending_sqlite_data()
  426. def _sync_pending_patches_to_sqlite(self):
  427. """v5.1: 同步 _pending_entity_patches 等到 SQLite"""
  428. if not self._sql_state_manager:
  429. return
  430. try:
  431. from .sql_state_manager import EntityData
  432. # 同步实体补丁
  433. for (entity_type, entity_id), patch in self._pending_entity_patches.items():
  434. if patch.base_entity:
  435. # 新实体
  436. entity_data = EntityData(
  437. id=entity_id,
  438. type=entity_type,
  439. name=patch.base_entity.get("canonical_name", entity_id),
  440. tier=patch.base_entity.get("tier", "装饰"),
  441. desc=patch.base_entity.get("desc", ""),
  442. current=patch.base_entity.get("current", {}),
  443. aliases=[],
  444. first_appearance=patch.base_entity.get("first_appearance", 0),
  445. last_appearance=patch.base_entity.get("last_appearance", 0),
  446. is_protagonist=patch.base_entity.get("is_protagonist", False)
  447. )
  448. self._sql_state_manager.upsert_entity(entity_data)
  449. elif patch.current_updates or patch.top_updates:
  450. # 更新现有实体
  451. updates = {**patch.top_updates}
  452. if patch.current_updates:
  453. updates.update(patch.current_updates)
  454. if updates:
  455. self._sql_state_manager.update_entity_current(entity_id, updates)
  456. # 更新 last_appearance
  457. if patch.appearance_chapter is not None:
  458. self._sql_state_manager._update_last_appearance(entity_id, patch.appearance_chapter)
  459. # 同步别名
  460. for alias, entries in self._pending_alias_entries.items():
  461. for entry in entries:
  462. entity_type = entry.get("type")
  463. entity_id = entry.get("id")
  464. if entity_type and entity_id:
  465. self._sql_state_manager.register_alias(alias, entity_id, entity_type)
  466. # 同步状态变化
  467. for change in self._pending_state_changes:
  468. self._sql_state_manager.record_state_change(
  469. entity_id=change.get("entity_id", ""),
  470. field=change.get("field", ""),
  471. old_value=change.get("old", change.get("old_value", "")),
  472. new_value=change.get("new", change.get("new_value", "")),
  473. reason=change.get("reason", ""),
  474. chapter=change.get("chapter", 0)
  475. )
  476. # 同步关系
  477. for rel in self._pending_structured_relationships:
  478. self._sql_state_manager.upsert_relationship(
  479. from_entity=rel.get("from_entity", ""),
  480. to_entity=rel.get("to_entity", ""),
  481. type=rel.get("type", "相识"),
  482. description=rel.get("description", ""),
  483. chapter=rel.get("chapter", 0)
  484. )
  485. except Exception:
  486. pass # SQLite 同步失败时静默降级
  487. def _clear_pending_sqlite_data(self):
  488. """清空待同步的 SQLite 数据"""
  489. self._pending_sqlite_data = {
  490. "entities_appeared": [],
  491. "entities_new": [],
  492. "state_changes": [],
  493. "relationships_new": [],
  494. "chapter": None
  495. }
  496. # ==================== 进度管理 ====================
  497. def get_current_chapter(self) -> int:
  498. """获取当前章节号"""
  499. return self._state.get("progress", {}).get("current_chapter", 0)
  500. def update_progress(self, chapter: int, words: int = 0):
  501. """更新进度"""
  502. if "progress" not in self._state:
  503. self._state["progress"] = {}
  504. self._state["progress"]["current_chapter"] = chapter
  505. if words > 0:
  506. total = self._state["progress"].get("total_words", 0)
  507. self._state["progress"]["total_words"] = total + words
  508. # 记录增量:锁内合并时用 max(chapter) + words_delta 累加
  509. if self._pending_progress_chapter is None:
  510. self._pending_progress_chapter = chapter
  511. else:
  512. self._pending_progress_chapter = max(self._pending_progress_chapter, chapter)
  513. if words > 0:
  514. self._pending_progress_words_delta += int(words)
  515. # ==================== 实体管理 (v5.0 entities_v3) ====================
  516. def get_entity(self, entity_id: str, entity_type: str = None) -> Optional[Dict]:
  517. """获取实体 (v5.0 entities_v3 格式)"""
  518. entities_v3 = self._state.get("entities_v3", {})
  519. if entity_type:
  520. return entities_v3.get(entity_type, {}).get(entity_id)
  521. # 遍历所有类型查找
  522. for type_name, entities in entities_v3.items():
  523. if entity_id in entities:
  524. return entities[entity_id]
  525. return None
  526. def get_entity_type(self, entity_id: str) -> Optional[str]:
  527. """获取实体所属类型"""
  528. for type_name, entities in self._state.get("entities_v3", {}).items():
  529. if entity_id in entities:
  530. return type_name
  531. return None
  532. def get_all_entities(self) -> Dict[str, Dict]:
  533. """获取所有实体(扁平化视图,兼容旧代码)"""
  534. result = {}
  535. for type_name, entities in self._state.get("entities_v3", {}).items():
  536. for eid, e in entities.items():
  537. result[eid] = {**e, "type": type_name}
  538. return result
  539. def get_entities_by_type(self, entity_type: str) -> Dict[str, Dict]:
  540. """按类型获取实体"""
  541. return self._state.get("entities_v3", {}).get(entity_type, {})
  542. def get_entities_by_tier(self, tier: str) -> Dict[str, Dict]:
  543. """按层级获取实体"""
  544. result = {}
  545. for type_name, entities in self._state.get("entities_v3", {}).items():
  546. for eid, e in entities.items():
  547. if e.get("tier") == tier:
  548. result[eid] = {**e, "type": type_name}
  549. return result
  550. def add_entity(self, entity: EntityState) -> bool:
  551. """添加新实体 (v5.0 entities_v3 格式)"""
  552. entity_type = entity.type
  553. if entity_type not in self.ENTITY_TYPES:
  554. entity_type = "角色"
  555. if "entities_v3" not in self._state:
  556. self._state["entities_v3"] = {t: {} for t in self.ENTITY_TYPES}
  557. if entity_type not in self._state["entities_v3"]:
  558. self._state["entities_v3"][entity_type] = {}
  559. # 检查是否已存在
  560. if entity.id in self._state["entities_v3"][entity_type]:
  561. return False
  562. # 转换为 v3 格式
  563. v3_entity = {
  564. "canonical_name": entity.name,
  565. "tier": entity.tier,
  566. "desc": "",
  567. "current": entity.attributes,
  568. "first_appearance": entity.first_appearance,
  569. "last_appearance": entity.last_appearance,
  570. "history": []
  571. }
  572. self._state["entities_v3"][entity_type][entity.id] = v3_entity
  573. # 记录实体补丁(新建:仅填充缺失字段,避免覆盖并发写入)
  574. patch = self._pending_entity_patches.get((entity_type, entity.id))
  575. if patch is None:
  576. patch = _EntityPatch(entity_type=entity_type, entity_id=entity.id)
  577. self._pending_entity_patches[(entity_type, entity.id)] = patch
  578. patch.replace = True
  579. patch.base_entity = v3_entity
  580. # 注册别名到 alias_index
  581. self._register_alias_internal(entity.id, entity_type, entity.name)
  582. for alias in entity.aliases:
  583. self._register_alias_internal(entity.id, entity_type, alias)
  584. return True
  585. def _register_alias_internal(self, entity_id: str, entity_type: str, alias: str):
  586. """内部方法:注册别名到 state.json 的 alias_index"""
  587. if not alias:
  588. return
  589. if "alias_index" not in self._state:
  590. self._state["alias_index"] = {}
  591. if alias not in self._state["alias_index"]:
  592. self._state["alias_index"][alias] = []
  593. # 检查是否已存在
  594. exists = any(
  595. e.get("type") == entity_type and e.get("id") == entity_id
  596. for e in self._state["alias_index"][alias]
  597. )
  598. if not exists:
  599. self._state["alias_index"][alias].append({
  600. "type": entity_type,
  601. "id": entity_id
  602. })
  603. # 记录待合并增量:避免锁外读-改-写覆盖
  604. pending = self._pending_alias_entries.setdefault(alias, [])
  605. if not any(e.get("type") == entity_type and e.get("id") == entity_id for e in pending):
  606. pending.append({"type": entity_type, "id": entity_id})
  607. def update_entity(self, entity_id: str, updates: Dict[str, Any], entity_type: str = None) -> bool:
  608. """更新实体属性 (v5.0)"""
  609. # 查找实体
  610. if entity_type:
  611. if entity_id not in self._state.get("entities_v3", {}).get(entity_type, {}):
  612. return False
  613. entity = self._state["entities_v3"][entity_type][entity_id]
  614. else:
  615. entity_type = self.get_entity_type(entity_id)
  616. if not entity_type:
  617. return False
  618. entity = self._state["entities_v3"][entity_type][entity_id]
  619. for key, value in updates.items():
  620. if key == "attributes" and isinstance(value, dict):
  621. # v5.0: attributes 存在 current 字段
  622. if "current" not in entity:
  623. entity["current"] = {}
  624. entity["current"].update(value)
  625. # 记录补丁(current 增量)
  626. patch = self._pending_entity_patches.get((entity_type, entity_id))
  627. if patch is None:
  628. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  629. self._pending_entity_patches[(entity_type, entity_id)] = patch
  630. patch.current_updates.update(value)
  631. elif key == "current" and isinstance(value, dict):
  632. if "current" not in entity:
  633. entity["current"] = {}
  634. entity["current"].update(value)
  635. patch = self._pending_entity_patches.get((entity_type, entity_id))
  636. if patch is None:
  637. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  638. self._pending_entity_patches[(entity_type, entity_id)] = patch
  639. patch.current_updates.update(value)
  640. else:
  641. entity[key] = value
  642. patch = self._pending_entity_patches.get((entity_type, entity_id))
  643. if patch is None:
  644. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  645. self._pending_entity_patches[(entity_type, entity_id)] = patch
  646. patch.top_updates[key] = value
  647. return True
  648. def update_entity_appearance(self, entity_id: str, chapter: int, entity_type: str = None):
  649. """更新实体出场章节"""
  650. if not entity_type:
  651. entity_type = self.get_entity_type(entity_id)
  652. if not entity_type:
  653. return
  654. entity = self._state["entities_v3"][entity_type].get(entity_id)
  655. if entity:
  656. if entity.get("first_appearance", 0) == 0:
  657. entity["first_appearance"] = chapter
  658. entity["last_appearance"] = chapter
  659. # 记录补丁:锁内应用 first=min(non-zero), last=max
  660. patch = self._pending_entity_patches.get((entity_type, entity_id))
  661. if patch is None:
  662. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  663. self._pending_entity_patches[(entity_type, entity_id)] = patch
  664. if patch.appearance_chapter is None:
  665. patch.appearance_chapter = chapter
  666. else:
  667. patch.appearance_chapter = max(int(patch.appearance_chapter), int(chapter))
  668. # ==================== 状态变化记录 ====================
  669. def record_state_change(
  670. self,
  671. entity_id: str,
  672. field: str,
  673. old_value: Any,
  674. new_value: Any,
  675. reason: str,
  676. chapter: int
  677. ):
  678. """记录状态变化"""
  679. if "state_changes" not in self._state:
  680. self._state["state_changes"] = []
  681. change = StateChange(
  682. entity_id=entity_id,
  683. field=field,
  684. old_value=old_value,
  685. new_value=new_value,
  686. reason=reason,
  687. chapter=chapter
  688. )
  689. change_dict = asdict(change)
  690. self._state["state_changes"].append(change_dict)
  691. self._pending_state_changes.append(change_dict)
  692. # 同时更新实体属性
  693. self.update_entity(entity_id, {"attributes": {field: new_value}})
  694. def get_state_changes(self, entity_id: Optional[str] = None) -> List[Dict]:
  695. """获取状态变化历史"""
  696. changes = self._state.get("state_changes", [])
  697. if entity_id:
  698. changes = [c for c in changes if c.get("entity_id") == entity_id]
  699. return changes
  700. # ==================== 关系管理 ====================
  701. def add_relationship(
  702. self,
  703. from_entity: str,
  704. to_entity: str,
  705. rel_type: str,
  706. description: str,
  707. chapter: int
  708. ):
  709. """添加关系"""
  710. rel = Relationship(
  711. from_entity=from_entity,
  712. to_entity=to_entity,
  713. type=rel_type,
  714. description=description,
  715. chapter=chapter
  716. )
  717. # v5.0: 实体关系存入 structured_relationships,避免与 relationships(人物关系字典) 冲突
  718. if "structured_relationships" not in self._state:
  719. self._state["structured_relationships"] = []
  720. rel_dict = asdict(rel)
  721. self._state["structured_relationships"].append(rel_dict)
  722. self._pending_structured_relationships.append(rel_dict)
  723. def get_relationships(self, entity_id: Optional[str] = None) -> List[Dict]:
  724. """获取关系列表"""
  725. rels = self._state.get("structured_relationships", [])
  726. if entity_id:
  727. rels = [
  728. r for r in rels
  729. if r.get("from_entity") == entity_id or r.get("to_entity") == entity_id
  730. ]
  731. return rels
  732. # ==================== 批量操作 ====================
  733. def _record_disambiguation(self, chapter: int, uncertain_items: Any) -> List[str]:
  734. """
  735. 记录消歧反馈到 state.json,便于 Writer/Context Agent 感知风险。
  736. 约定:
  737. - >= extraction_confidence_medium:写入 disambiguation_warnings(采用但警告)
  738. - < extraction_confidence_medium:写入 disambiguation_pending(需人工确认)
  739. """
  740. if not isinstance(uncertain_items, list) or not uncertain_items:
  741. return []
  742. warnings: List[str] = []
  743. now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  744. for item in uncertain_items:
  745. if not isinstance(item, dict):
  746. continue
  747. mention = str(item.get("mention", "") or "").strip()
  748. if not mention:
  749. continue
  750. raw_conf = item.get("confidence", 0.0)
  751. try:
  752. confidence = float(raw_conf)
  753. except (TypeError, ValueError):
  754. confidence = 0.0
  755. # 候选:支持 [{"type","id"}...] 或 ["id1","id2"] 两种形式
  756. candidates_raw = item.get("candidates", [])
  757. candidates: List[Dict[str, str]] = []
  758. if isinstance(candidates_raw, list):
  759. for c in candidates_raw:
  760. if isinstance(c, dict):
  761. cid = str(c.get("id", "") or "").strip()
  762. ctype = str(c.get("type", "") or "").strip()
  763. entry: Dict[str, str] = {}
  764. if ctype:
  765. entry["type"] = ctype
  766. if cid:
  767. entry["id"] = cid
  768. if entry:
  769. candidates.append(entry)
  770. else:
  771. cid = str(c).strip()
  772. if cid:
  773. candidates.append({"id": cid})
  774. entity_type = str(item.get("type", "") or "").strip()
  775. suggested_id = str(item.get("suggested", "") or "").strip()
  776. adopted_raw = item.get("adopted", None)
  777. chosen_id = ""
  778. if isinstance(adopted_raw, str):
  779. chosen_id = adopted_raw.strip()
  780. elif adopted_raw is True:
  781. chosen_id = suggested_id
  782. else:
  783. # 兼容字段名:entity_id / chosen_id
  784. chosen_id = str(item.get("entity_id") or item.get("chosen_id") or "").strip() or suggested_id
  785. context = str(item.get("context", "") or "").strip()
  786. note = str(item.get("warning", "") or "").strip()
  787. record: Dict[str, Any] = {
  788. "chapter": int(chapter),
  789. "mention": mention,
  790. "type": entity_type,
  791. "suggested_id": suggested_id,
  792. "chosen_id": chosen_id,
  793. "confidence": confidence,
  794. "candidates": candidates,
  795. "context": context,
  796. "note": note,
  797. "created_at": now,
  798. }
  799. if confidence >= float(self.config.extraction_confidence_medium):
  800. self._state.setdefault("disambiguation_warnings", []).append(record)
  801. self._pending_disambiguation_warnings.append(record)
  802. chosen_part = f" → {chosen_id}" if chosen_id else ""
  803. warnings.append(f"消歧警告: {mention}{chosen_part} (confidence: {confidence:.2f})")
  804. else:
  805. self._state.setdefault("disambiguation_pending", []).append(record)
  806. self._pending_disambiguation_pending.append(record)
  807. warnings.append(f"消歧需人工确认: {mention} (confidence: {confidence:.2f})")
  808. return warnings
  809. def process_chapter_result(self, chapter: int, result: Dict) -> List[str]:
  810. """
  811. 处理 Data Agent 的章节处理结果 (v5.1)
  812. 输入格式:
  813. - entities_appeared: 出场实体列表
  814. - entities_new: 新实体列表
  815. - state_changes: 状态变化列表
  816. - relationships_new: 新关系列表
  817. 返回警告列表
  818. """
  819. warnings = []
  820. # v5.1: 记录章节号用于 SQLite 同步
  821. self._pending_sqlite_data["chapter"] = chapter
  822. # 处理出场实体
  823. for entity in result.get("entities_appeared", []):
  824. entity_id = entity.get("id")
  825. entity_type = entity.get("type")
  826. if entity_id:
  827. self.update_entity_appearance(entity_id, chapter, entity_type)
  828. # v5.1: 缓存用于 SQLite 同步
  829. self._pending_sqlite_data["entities_appeared"].append(entity)
  830. # 处理新实体
  831. for entity in result.get("entities_new", []):
  832. entity_id = entity.get("suggested_id") or entity.get("id")
  833. if entity_id and entity_id != "NEW":
  834. new_entity = EntityState(
  835. id=entity_id,
  836. name=entity.get("name", ""),
  837. type=entity.get("type", "角色"),
  838. tier=entity.get("tier", "装饰"),
  839. aliases=entity.get("mentions", []),
  840. first_appearance=chapter,
  841. last_appearance=chapter
  842. )
  843. if not self.add_entity(new_entity):
  844. warnings.append(f"实体已存在: {entity_id}")
  845. # v5.1: 缓存用于 SQLite 同步
  846. self._pending_sqlite_data["entities_new"].append(entity)
  847. # 处理状态变化
  848. for change in result.get("state_changes", []):
  849. self.record_state_change(
  850. entity_id=change.get("entity_id", ""),
  851. field=change.get("field", ""),
  852. old_value=change.get("old"),
  853. new_value=change.get("new"),
  854. reason=change.get("reason", ""),
  855. chapter=chapter
  856. )
  857. # v5.1: 缓存用于 SQLite 同步
  858. self._pending_sqlite_data["state_changes"].append(change)
  859. # 处理关系
  860. for rel in result.get("relationships_new", []):
  861. self.add_relationship(
  862. from_entity=rel.get("from", ""),
  863. to_entity=rel.get("to", ""),
  864. rel_type=rel.get("type", ""),
  865. description=rel.get("description", ""),
  866. chapter=chapter
  867. )
  868. # v5.1: 缓存用于 SQLite 同步
  869. self._pending_sqlite_data["relationships_new"].append(rel)
  870. # 处理消歧不确定项(不影响实体写入,但必须对 Writer 可见)
  871. warnings.extend(self._record_disambiguation(chapter, result.get("uncertain", [])))
  872. # 更新进度
  873. self.update_progress(chapter)
  874. # 同步主角状态(entities_v3 → protagonist_state)
  875. self.sync_protagonist_from_entity()
  876. return warnings
  877. # ==================== 导出 ====================
  878. def export_for_context(self) -> Dict:
  879. """导出用于上下文的精简版状态 (v5.0)"""
  880. # 从 entities_v3 构建精简视图
  881. entities_flat = {}
  882. for type_name, entities in self._state.get("entities_v3", {}).items():
  883. for eid, e in entities.items():
  884. entities_flat[eid] = {
  885. "name": e.get("canonical_name", eid),
  886. "type": type_name,
  887. "tier": e.get("tier", "装饰"),
  888. "current": e.get("current", {})
  889. }
  890. return {
  891. "progress": self._state.get("progress", {}),
  892. "entities": entities_flat,
  893. "alias_index": self._state.get("alias_index", {}),
  894. "recent_changes": self._state.get("state_changes", [])[-self.config.export_recent_changes_slice:],
  895. "disambiguation": {
  896. "warnings": self._state.get("disambiguation_warnings", [])[-self.config.export_disambiguation_slice:],
  897. "pending": self._state.get("disambiguation_pending", [])[-self.config.export_disambiguation_slice:],
  898. },
  899. }
  900. # ==================== 主角同步 ====================
  901. def get_protagonist_entity_id(self) -> Optional[str]:
  902. """获取主角实体 ID(通过 is_protagonist 标记或 protagonist_state.name 查找)"""
  903. # 方式1: 查找 is_protagonist 标记
  904. for eid, e in self._state.get("entities_v3", {}).get("角色", {}).items():
  905. if e.get("is_protagonist"):
  906. return eid
  907. # 方式2: 通过 protagonist_state.name 查找
  908. protag_name = self._state.get("protagonist_state", {}).get("name")
  909. if protag_name:
  910. alias_entries = self._state.get("alias_index", {}).get(protag_name, [])
  911. for entry in alias_entries:
  912. if entry.get("type") == "角色":
  913. return entry.get("id")
  914. return None
  915. def sync_protagonist_from_entity(self, entity_id: str = None):
  916. """
  917. 将 entities_v3 中主角实体的状态同步到 protagonist_state
  918. 用于确保 consistency-checker 等依赖 protagonist_state 的组件获取最新数据
  919. """
  920. if entity_id is None:
  921. entity_id = self.get_protagonist_entity_id()
  922. if entity_id is None:
  923. return
  924. entity = self.get_entity(entity_id, "角色")
  925. if not entity:
  926. return
  927. current = entity.get("current", {})
  928. protag = self._state.setdefault("protagonist_state", {})
  929. # 同步境界
  930. if "realm" in current:
  931. power = protag.setdefault("power", {})
  932. power["realm"] = current["realm"]
  933. if "layer" in current:
  934. power["layer"] = current["layer"]
  935. # 同步位置
  936. if "location" in current:
  937. loc = protag.setdefault("location", {})
  938. loc["current"] = current["location"]
  939. if "last_chapter" in current:
  940. loc["last_chapter"] = current["last_chapter"]
  941. def sync_protagonist_to_entity(self, entity_id: str = None):
  942. """
  943. 将 protagonist_state 同步到 entities_v3 中的主角实体
  944. 用于初始化或手动编辑 protagonist_state 后保持一致性
  945. """
  946. if entity_id is None:
  947. entity_id = self.get_protagonist_entity_id()
  948. if entity_id is None:
  949. return
  950. protag = self._state.get("protagonist_state", {})
  951. if not protag:
  952. return
  953. updates = {}
  954. # 同步境界
  955. power = protag.get("power", {})
  956. if power.get("realm"):
  957. updates["realm"] = power["realm"]
  958. if power.get("layer"):
  959. updates["layer"] = power["layer"]
  960. # 同步位置
  961. loc = protag.get("location", {})
  962. if loc.get("current"):
  963. updates["location"] = loc["current"]
  964. if updates:
  965. self.update_entity(entity_id, updates, "角色")
  966. # ==================== CLI 接口 ====================
  967. def main():
  968. import argparse
  969. parser = argparse.ArgumentParser(description="State Manager CLI")
  970. parser.add_argument("--project-root", type=str, help="项目根目录")
  971. subparsers = parser.add_subparsers(dest="command")
  972. # 获取进度
  973. subparsers.add_parser("get-progress")
  974. # 获取实体
  975. get_entity_parser = subparsers.add_parser("get-entity")
  976. get_entity_parser.add_argument("--id", required=True, help="实体ID")
  977. # 列出实体
  978. list_parser = subparsers.add_parser("list-entities")
  979. list_parser.add_argument("--type", help="按类型过滤")
  980. list_parser.add_argument("--tier", help="按层级过滤")
  981. # 处理章节结果
  982. process_parser = subparsers.add_parser("process-chapter")
  983. process_parser.add_argument("--chapter", type=int, required=True, help="章节号")
  984. process_parser.add_argument("--data", required=True, help="JSON 格式的处理结果")
  985. args = parser.parse_args()
  986. # 初始化
  987. config = None
  988. if args.project_root:
  989. from .config import DataModulesConfig
  990. config = DataModulesConfig.from_project_root(args.project_root)
  991. manager = StateManager(config)
  992. if args.command == "get-progress":
  993. print(json.dumps(manager._state.get("progress", {}), ensure_ascii=False, indent=2))
  994. elif args.command == "get-entity":
  995. entity = manager.get_entity(args.id)
  996. if entity:
  997. print(json.dumps(entity, ensure_ascii=False, indent=2))
  998. else:
  999. print(f"未找到实体: {args.id}")
  1000. elif args.command == "list-entities":
  1001. if args.type:
  1002. entities = manager.get_entities_by_type(args.type)
  1003. elif args.tier:
  1004. entities = manager.get_entities_by_tier(args.tier)
  1005. else:
  1006. entities = manager.get_all_entities()
  1007. for eid, e in entities.items():
  1008. print(f"{eid}: {e.get('name')} ({e.get('type')}/{e.get('tier')})")
  1009. elif args.command == "process-chapter":
  1010. data = json.loads(args.data)
  1011. warnings = manager.process_chapter_result(args.chapter, data)
  1012. manager.save_state()
  1013. print(f"✓ 已处理第 {args.chapter} 章")
  1014. if warnings:
  1015. print("警告:")
  1016. for w in warnings:
  1017. print(f" - {w}")
  1018. if __name__ == "__main__":
  1019. main()