state_manager.py 51 KB

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