state_manager.py 54 KB

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