state_manager.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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. sqlite_data = self._pending_sqlite_data
  408. chapter = sqlite_data.get("chapter")
  409. if chapter is None:
  410. # 清空并返回
  411. self._clear_pending_sqlite_data()
  412. return
  413. try:
  414. self._sql_state_manager.process_chapter_entities(
  415. chapter=chapter,
  416. entities_appeared=sqlite_data.get("entities_appeared", []),
  417. entities_new=sqlite_data.get("entities_new", []),
  418. state_changes=sqlite_data.get("state_changes", []),
  419. relationships_new=sqlite_data.get("relationships_new", [])
  420. )
  421. except Exception:
  422. pass # SQLite 同步失败时静默降级,不影响主流程
  423. finally:
  424. self._clear_pending_sqlite_data()
  425. def _clear_pending_sqlite_data(self):
  426. """清空待同步的 SQLite 数据"""
  427. self._pending_sqlite_data = {
  428. "entities_appeared": [],
  429. "entities_new": [],
  430. "state_changes": [],
  431. "relationships_new": [],
  432. "chapter": None
  433. }
  434. # ==================== 进度管理 ====================
  435. def get_current_chapter(self) -> int:
  436. """获取当前章节号"""
  437. return self._state.get("progress", {}).get("current_chapter", 0)
  438. def update_progress(self, chapter: int, words: int = 0):
  439. """更新进度"""
  440. if "progress" not in self._state:
  441. self._state["progress"] = {}
  442. self._state["progress"]["current_chapter"] = chapter
  443. if words > 0:
  444. total = self._state["progress"].get("total_words", 0)
  445. self._state["progress"]["total_words"] = total + words
  446. # 记录增量:锁内合并时用 max(chapter) + words_delta 累加
  447. if self._pending_progress_chapter is None:
  448. self._pending_progress_chapter = chapter
  449. else:
  450. self._pending_progress_chapter = max(self._pending_progress_chapter, chapter)
  451. if words > 0:
  452. self._pending_progress_words_delta += int(words)
  453. # ==================== 实体管理 (v5.0 entities_v3) ====================
  454. def get_entity(self, entity_id: str, entity_type: str = None) -> Optional[Dict]:
  455. """获取实体 (v5.0 entities_v3 格式)"""
  456. entities_v3 = self._state.get("entities_v3", {})
  457. if entity_type:
  458. return entities_v3.get(entity_type, {}).get(entity_id)
  459. # 遍历所有类型查找
  460. for type_name, entities in entities_v3.items():
  461. if entity_id in entities:
  462. return entities[entity_id]
  463. return None
  464. def get_entity_type(self, entity_id: str) -> Optional[str]:
  465. """获取实体所属类型"""
  466. for type_name, entities in self._state.get("entities_v3", {}).items():
  467. if entity_id in entities:
  468. return type_name
  469. return None
  470. def get_all_entities(self) -> Dict[str, Dict]:
  471. """获取所有实体(扁平化视图,兼容旧代码)"""
  472. result = {}
  473. for type_name, entities in self._state.get("entities_v3", {}).items():
  474. for eid, e in entities.items():
  475. result[eid] = {**e, "type": type_name}
  476. return result
  477. def get_entities_by_type(self, entity_type: str) -> Dict[str, Dict]:
  478. """按类型获取实体"""
  479. return self._state.get("entities_v3", {}).get(entity_type, {})
  480. def get_entities_by_tier(self, tier: str) -> Dict[str, Dict]:
  481. """按层级获取实体"""
  482. result = {}
  483. for type_name, entities in self._state.get("entities_v3", {}).items():
  484. for eid, e in entities.items():
  485. if e.get("tier") == tier:
  486. result[eid] = {**e, "type": type_name}
  487. return result
  488. def add_entity(self, entity: EntityState) -> bool:
  489. """添加新实体 (v5.0 entities_v3 格式)"""
  490. entity_type = entity.type
  491. if entity_type not in self.ENTITY_TYPES:
  492. entity_type = "角色"
  493. if "entities_v3" not in self._state:
  494. self._state["entities_v3"] = {t: {} for t in self.ENTITY_TYPES}
  495. if entity_type not in self._state["entities_v3"]:
  496. self._state["entities_v3"][entity_type] = {}
  497. # 检查是否已存在
  498. if entity.id in self._state["entities_v3"][entity_type]:
  499. return False
  500. # 转换为 v3 格式
  501. v3_entity = {
  502. "canonical_name": entity.name,
  503. "tier": entity.tier,
  504. "desc": "",
  505. "current": entity.attributes,
  506. "first_appearance": entity.first_appearance,
  507. "last_appearance": entity.last_appearance,
  508. "history": []
  509. }
  510. self._state["entities_v3"][entity_type][entity.id] = v3_entity
  511. # 记录实体补丁(新建:仅填充缺失字段,避免覆盖并发写入)
  512. patch = self._pending_entity_patches.get((entity_type, entity.id))
  513. if patch is None:
  514. patch = _EntityPatch(entity_type=entity_type, entity_id=entity.id)
  515. self._pending_entity_patches[(entity_type, entity.id)] = patch
  516. patch.replace = True
  517. patch.base_entity = v3_entity
  518. # 注册别名到 alias_index
  519. self._register_alias_internal(entity.id, entity_type, entity.name)
  520. for alias in entity.aliases:
  521. self._register_alias_internal(entity.id, entity_type, alias)
  522. return True
  523. def _register_alias_internal(self, entity_id: str, entity_type: str, alias: str):
  524. """内部方法:注册别名到 state.json 的 alias_index"""
  525. if not alias:
  526. return
  527. if "alias_index" not in self._state:
  528. self._state["alias_index"] = {}
  529. if alias not in self._state["alias_index"]:
  530. self._state["alias_index"][alias] = []
  531. # 检查是否已存在
  532. exists = any(
  533. e.get("type") == entity_type and e.get("id") == entity_id
  534. for e in self._state["alias_index"][alias]
  535. )
  536. if not exists:
  537. self._state["alias_index"][alias].append({
  538. "type": entity_type,
  539. "id": entity_id
  540. })
  541. # 记录待合并增量:避免锁外读-改-写覆盖
  542. pending = self._pending_alias_entries.setdefault(alias, [])
  543. if not any(e.get("type") == entity_type and e.get("id") == entity_id for e in pending):
  544. pending.append({"type": entity_type, "id": entity_id})
  545. def update_entity(self, entity_id: str, updates: Dict[str, Any], entity_type: str = None) -> bool:
  546. """更新实体属性 (v5.0)"""
  547. # 查找实体
  548. if entity_type:
  549. if entity_id not in self._state.get("entities_v3", {}).get(entity_type, {}):
  550. return False
  551. entity = self._state["entities_v3"][entity_type][entity_id]
  552. else:
  553. entity_type = self.get_entity_type(entity_id)
  554. if not entity_type:
  555. return False
  556. entity = self._state["entities_v3"][entity_type][entity_id]
  557. for key, value in updates.items():
  558. if key == "attributes" and isinstance(value, dict):
  559. # v5.0: attributes 存在 current 字段
  560. if "current" not in entity:
  561. entity["current"] = {}
  562. entity["current"].update(value)
  563. # 记录补丁(current 增量)
  564. patch = self._pending_entity_patches.get((entity_type, entity_id))
  565. if patch is None:
  566. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  567. self._pending_entity_patches[(entity_type, entity_id)] = patch
  568. patch.current_updates.update(value)
  569. elif key == "current" and isinstance(value, dict):
  570. if "current" not in entity:
  571. entity["current"] = {}
  572. entity["current"].update(value)
  573. patch = self._pending_entity_patches.get((entity_type, entity_id))
  574. if patch is None:
  575. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  576. self._pending_entity_patches[(entity_type, entity_id)] = patch
  577. patch.current_updates.update(value)
  578. else:
  579. entity[key] = value
  580. patch = self._pending_entity_patches.get((entity_type, entity_id))
  581. if patch is None:
  582. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  583. self._pending_entity_patches[(entity_type, entity_id)] = patch
  584. patch.top_updates[key] = value
  585. return True
  586. def update_entity_appearance(self, entity_id: str, chapter: int, entity_type: str = None):
  587. """更新实体出场章节"""
  588. if not entity_type:
  589. entity_type = self.get_entity_type(entity_id)
  590. if not entity_type:
  591. return
  592. entity = self._state["entities_v3"][entity_type].get(entity_id)
  593. if entity:
  594. if entity.get("first_appearance", 0) == 0:
  595. entity["first_appearance"] = chapter
  596. entity["last_appearance"] = chapter
  597. # 记录补丁:锁内应用 first=min(non-zero), last=max
  598. patch = self._pending_entity_patches.get((entity_type, entity_id))
  599. if patch is None:
  600. patch = _EntityPatch(entity_type=entity_type, entity_id=entity_id)
  601. self._pending_entity_patches[(entity_type, entity_id)] = patch
  602. if patch.appearance_chapter is None:
  603. patch.appearance_chapter = chapter
  604. else:
  605. patch.appearance_chapter = max(int(patch.appearance_chapter), int(chapter))
  606. # ==================== 状态变化记录 ====================
  607. def record_state_change(
  608. self,
  609. entity_id: str,
  610. field: str,
  611. old_value: Any,
  612. new_value: Any,
  613. reason: str,
  614. chapter: int
  615. ):
  616. """记录状态变化"""
  617. if "state_changes" not in self._state:
  618. self._state["state_changes"] = []
  619. change = StateChange(
  620. entity_id=entity_id,
  621. field=field,
  622. old_value=old_value,
  623. new_value=new_value,
  624. reason=reason,
  625. chapter=chapter
  626. )
  627. change_dict = asdict(change)
  628. self._state["state_changes"].append(change_dict)
  629. self._pending_state_changes.append(change_dict)
  630. # 同时更新实体属性
  631. self.update_entity(entity_id, {"attributes": {field: new_value}})
  632. def get_state_changes(self, entity_id: Optional[str] = None) -> List[Dict]:
  633. """获取状态变化历史"""
  634. changes = self._state.get("state_changes", [])
  635. if entity_id:
  636. changes = [c for c in changes if c.get("entity_id") == entity_id]
  637. return changes
  638. # ==================== 关系管理 ====================
  639. def add_relationship(
  640. self,
  641. from_entity: str,
  642. to_entity: str,
  643. rel_type: str,
  644. description: str,
  645. chapter: int
  646. ):
  647. """添加关系"""
  648. rel = Relationship(
  649. from_entity=from_entity,
  650. to_entity=to_entity,
  651. type=rel_type,
  652. description=description,
  653. chapter=chapter
  654. )
  655. # v5.0: 实体关系存入 structured_relationships,避免与 relationships(人物关系字典) 冲突
  656. if "structured_relationships" not in self._state:
  657. self._state["structured_relationships"] = []
  658. rel_dict = asdict(rel)
  659. self._state["structured_relationships"].append(rel_dict)
  660. self._pending_structured_relationships.append(rel_dict)
  661. def get_relationships(self, entity_id: Optional[str] = None) -> List[Dict]:
  662. """获取关系列表"""
  663. rels = self._state.get("structured_relationships", [])
  664. if entity_id:
  665. rels = [
  666. r for r in rels
  667. if r.get("from_entity") == entity_id or r.get("to_entity") == entity_id
  668. ]
  669. return rels
  670. # ==================== 批量操作 ====================
  671. def _record_disambiguation(self, chapter: int, uncertain_items: Any) -> List[str]:
  672. """
  673. 记录消歧反馈到 state.json,便于 Writer/Context Agent 感知风险。
  674. 约定:
  675. - >= extraction_confidence_medium:写入 disambiguation_warnings(采用但警告)
  676. - < extraction_confidence_medium:写入 disambiguation_pending(需人工确认)
  677. """
  678. if not isinstance(uncertain_items, list) or not uncertain_items:
  679. return []
  680. warnings: List[str] = []
  681. now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  682. for item in uncertain_items:
  683. if not isinstance(item, dict):
  684. continue
  685. mention = str(item.get("mention", "") or "").strip()
  686. if not mention:
  687. continue
  688. raw_conf = item.get("confidence", 0.0)
  689. try:
  690. confidence = float(raw_conf)
  691. except (TypeError, ValueError):
  692. confidence = 0.0
  693. # 候选:支持 [{"type","id"}...] 或 ["id1","id2"] 两种形式
  694. candidates_raw = item.get("candidates", [])
  695. candidates: List[Dict[str, str]] = []
  696. if isinstance(candidates_raw, list):
  697. for c in candidates_raw:
  698. if isinstance(c, dict):
  699. cid = str(c.get("id", "") or "").strip()
  700. ctype = str(c.get("type", "") or "").strip()
  701. entry: Dict[str, str] = {}
  702. if ctype:
  703. entry["type"] = ctype
  704. if cid:
  705. entry["id"] = cid
  706. if entry:
  707. candidates.append(entry)
  708. else:
  709. cid = str(c).strip()
  710. if cid:
  711. candidates.append({"id": cid})
  712. entity_type = str(item.get("type", "") or "").strip()
  713. suggested_id = str(item.get("suggested", "") or "").strip()
  714. adopted_raw = item.get("adopted", None)
  715. chosen_id = ""
  716. if isinstance(adopted_raw, str):
  717. chosen_id = adopted_raw.strip()
  718. elif adopted_raw is True:
  719. chosen_id = suggested_id
  720. else:
  721. # 兼容字段名:entity_id / chosen_id
  722. chosen_id = str(item.get("entity_id") or item.get("chosen_id") or "").strip() or suggested_id
  723. context = str(item.get("context", "") or "").strip()
  724. note = str(item.get("warning", "") or "").strip()
  725. record: Dict[str, Any] = {
  726. "chapter": int(chapter),
  727. "mention": mention,
  728. "type": entity_type,
  729. "suggested_id": suggested_id,
  730. "chosen_id": chosen_id,
  731. "confidence": confidence,
  732. "candidates": candidates,
  733. "context": context,
  734. "note": note,
  735. "created_at": now,
  736. }
  737. if confidence >= float(self.config.extraction_confidence_medium):
  738. self._state.setdefault("disambiguation_warnings", []).append(record)
  739. self._pending_disambiguation_warnings.append(record)
  740. chosen_part = f" → {chosen_id}" if chosen_id else ""
  741. warnings.append(f"消歧警告: {mention}{chosen_part} (confidence: {confidence:.2f})")
  742. else:
  743. self._state.setdefault("disambiguation_pending", []).append(record)
  744. self._pending_disambiguation_pending.append(record)
  745. warnings.append(f"消歧需人工确认: {mention} (confidence: {confidence:.2f})")
  746. return warnings
  747. def process_chapter_result(self, chapter: int, result: Dict) -> List[str]:
  748. """
  749. 处理 Data Agent 的章节处理结果 (v5.1)
  750. 输入格式:
  751. - entities_appeared: 出场实体列表
  752. - entities_new: 新实体列表
  753. - state_changes: 状态变化列表
  754. - relationships_new: 新关系列表
  755. 返回警告列表
  756. """
  757. warnings = []
  758. # v5.1: 记录章节号用于 SQLite 同步
  759. self._pending_sqlite_data["chapter"] = chapter
  760. # 处理出场实体
  761. for entity in result.get("entities_appeared", []):
  762. entity_id = entity.get("id")
  763. entity_type = entity.get("type")
  764. if entity_id:
  765. self.update_entity_appearance(entity_id, chapter, entity_type)
  766. # v5.1: 缓存用于 SQLite 同步
  767. self._pending_sqlite_data["entities_appeared"].append(entity)
  768. # 处理新实体
  769. for entity in result.get("entities_new", []):
  770. entity_id = entity.get("suggested_id") or entity.get("id")
  771. if entity_id and entity_id != "NEW":
  772. new_entity = EntityState(
  773. id=entity_id,
  774. name=entity.get("name", ""),
  775. type=entity.get("type", "角色"),
  776. tier=entity.get("tier", "装饰"),
  777. aliases=entity.get("mentions", []),
  778. first_appearance=chapter,
  779. last_appearance=chapter
  780. )
  781. if not self.add_entity(new_entity):
  782. warnings.append(f"实体已存在: {entity_id}")
  783. # v5.1: 缓存用于 SQLite 同步
  784. self._pending_sqlite_data["entities_new"].append(entity)
  785. # 处理状态变化
  786. for change in result.get("state_changes", []):
  787. self.record_state_change(
  788. entity_id=change.get("entity_id", ""),
  789. field=change.get("field", ""),
  790. old_value=change.get("old"),
  791. new_value=change.get("new"),
  792. reason=change.get("reason", ""),
  793. chapter=chapter
  794. )
  795. # v5.1: 缓存用于 SQLite 同步
  796. self._pending_sqlite_data["state_changes"].append(change)
  797. # 处理关系
  798. for rel in result.get("relationships_new", []):
  799. self.add_relationship(
  800. from_entity=rel.get("from", ""),
  801. to_entity=rel.get("to", ""),
  802. rel_type=rel.get("type", ""),
  803. description=rel.get("description", ""),
  804. chapter=chapter
  805. )
  806. # v5.1: 缓存用于 SQLite 同步
  807. self._pending_sqlite_data["relationships_new"].append(rel)
  808. # 处理消歧不确定项(不影响实体写入,但必须对 Writer 可见)
  809. warnings.extend(self._record_disambiguation(chapter, result.get("uncertain", [])))
  810. # 更新进度
  811. self.update_progress(chapter)
  812. # 同步主角状态(entities_v3 → protagonist_state)
  813. self.sync_protagonist_from_entity()
  814. return warnings
  815. # ==================== 导出 ====================
  816. def export_for_context(self) -> Dict:
  817. """导出用于上下文的精简版状态 (v5.0)"""
  818. # 从 entities_v3 构建精简视图
  819. entities_flat = {}
  820. for type_name, entities in self._state.get("entities_v3", {}).items():
  821. for eid, e in entities.items():
  822. entities_flat[eid] = {
  823. "name": e.get("canonical_name", eid),
  824. "type": type_name,
  825. "tier": e.get("tier", "装饰"),
  826. "current": e.get("current", {})
  827. }
  828. return {
  829. "progress": self._state.get("progress", {}),
  830. "entities": entities_flat,
  831. "alias_index": self._state.get("alias_index", {}),
  832. "recent_changes": self._state.get("state_changes", [])[-self.config.export_recent_changes_slice:],
  833. "disambiguation": {
  834. "warnings": self._state.get("disambiguation_warnings", [])[-self.config.export_disambiguation_slice:],
  835. "pending": self._state.get("disambiguation_pending", [])[-self.config.export_disambiguation_slice:],
  836. },
  837. }
  838. # ==================== 主角同步 ====================
  839. def get_protagonist_entity_id(self) -> Optional[str]:
  840. """获取主角实体 ID(通过 is_protagonist 标记或 protagonist_state.name 查找)"""
  841. # 方式1: 查找 is_protagonist 标记
  842. for eid, e in self._state.get("entities_v3", {}).get("角色", {}).items():
  843. if e.get("is_protagonist"):
  844. return eid
  845. # 方式2: 通过 protagonist_state.name 查找
  846. protag_name = self._state.get("protagonist_state", {}).get("name")
  847. if protag_name:
  848. alias_entries = self._state.get("alias_index", {}).get(protag_name, [])
  849. for entry in alias_entries:
  850. if entry.get("type") == "角色":
  851. return entry.get("id")
  852. return None
  853. def sync_protagonist_from_entity(self, entity_id: str = None):
  854. """
  855. 将 entities_v3 中主角实体的状态同步到 protagonist_state
  856. 用于确保 consistency-checker 等依赖 protagonist_state 的组件获取最新数据
  857. """
  858. if entity_id is None:
  859. entity_id = self.get_protagonist_entity_id()
  860. if entity_id is None:
  861. return
  862. entity = self.get_entity(entity_id, "角色")
  863. if not entity:
  864. return
  865. current = entity.get("current", {})
  866. protag = self._state.setdefault("protagonist_state", {})
  867. # 同步境界
  868. if "realm" in current:
  869. power = protag.setdefault("power", {})
  870. power["realm"] = current["realm"]
  871. if "layer" in current:
  872. power["layer"] = current["layer"]
  873. # 同步位置
  874. if "location" in current:
  875. loc = protag.setdefault("location", {})
  876. loc["current"] = current["location"]
  877. if "last_chapter" in current:
  878. loc["last_chapter"] = current["last_chapter"]
  879. def sync_protagonist_to_entity(self, entity_id: str = None):
  880. """
  881. 将 protagonist_state 同步到 entities_v3 中的主角实体
  882. 用于初始化或手动编辑 protagonist_state 后保持一致性
  883. """
  884. if entity_id is None:
  885. entity_id = self.get_protagonist_entity_id()
  886. if entity_id is None:
  887. return
  888. protag = self._state.get("protagonist_state", {})
  889. if not protag:
  890. return
  891. updates = {}
  892. # 同步境界
  893. power = protag.get("power", {})
  894. if power.get("realm"):
  895. updates["realm"] = power["realm"]
  896. if power.get("layer"):
  897. updates["layer"] = power["layer"]
  898. # 同步位置
  899. loc = protag.get("location", {})
  900. if loc.get("current"):
  901. updates["location"] = loc["current"]
  902. if updates:
  903. self.update_entity(entity_id, updates, "角色")
  904. # ==================== CLI 接口 ====================
  905. def main():
  906. import argparse
  907. parser = argparse.ArgumentParser(description="State Manager CLI")
  908. parser.add_argument("--project-root", type=str, help="项目根目录")
  909. subparsers = parser.add_subparsers(dest="command")
  910. # 获取进度
  911. subparsers.add_parser("get-progress")
  912. # 获取实体
  913. get_entity_parser = subparsers.add_parser("get-entity")
  914. get_entity_parser.add_argument("--id", required=True, help="实体ID")
  915. # 列出实体
  916. list_parser = subparsers.add_parser("list-entities")
  917. list_parser.add_argument("--type", help="按类型过滤")
  918. list_parser.add_argument("--tier", help="按层级过滤")
  919. # 处理章节结果
  920. process_parser = subparsers.add_parser("process-chapter")
  921. process_parser.add_argument("--chapter", type=int, required=True, help="章节号")
  922. process_parser.add_argument("--data", required=True, help="JSON 格式的处理结果")
  923. args = parser.parse_args()
  924. # 初始化
  925. config = None
  926. if args.project_root:
  927. from .config import DataModulesConfig
  928. config = DataModulesConfig.from_project_root(args.project_root)
  929. manager = StateManager(config)
  930. if args.command == "get-progress":
  931. print(json.dumps(manager._state.get("progress", {}), ensure_ascii=False, indent=2))
  932. elif args.command == "get-entity":
  933. entity = manager.get_entity(args.id)
  934. if entity:
  935. print(json.dumps(entity, ensure_ascii=False, indent=2))
  936. else:
  937. print(f"未找到实体: {args.id}")
  938. elif args.command == "list-entities":
  939. if args.type:
  940. entities = manager.get_entities_by_type(args.type)
  941. elif args.tier:
  942. entities = manager.get_entities_by_tier(args.tier)
  943. else:
  944. entities = manager.get_all_entities()
  945. for eid, e in entities.items():
  946. print(f"{eid}: {e.get('name')} ({e.get('type')}/{e.get('tier')})")
  947. elif args.command == "process-chapter":
  948. data = json.loads(args.data)
  949. warnings = manager.process_chapter_result(args.chapter, data)
  950. manager.save_state()
  951. print(f"✓ 已处理第 {args.chapter} 章")
  952. if warnings:
  953. print("警告:")
  954. for w in warnings:
  955. print(f" - {w}")
  956. if __name__ == "__main__":
  957. main()