archive_manager.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. #!/usr/bin/env python3
  2. """
  3. state.json 数据归档管理脚本
  4. 目标:防止 state.json 无限增长,确保 200 万字长跑稳定运行
  5. 功能:
  6. 1. 智能归档长期未使用的数据(角色/伏笔/审查报告)
  7. 2. 自动触发条件检测(文件大小/章节数)
  8. 3. 安全备份与恢复机制
  9. 4. 归档数据可随时恢复
  10. 归档策略:
  11. - 角色:超过 50 章未出场的次要角色 → archive/characters.json
  12. - 伏笔:status="已回收" 且超过 20 章的伏笔 → archive/plot_threads.json
  13. - 审查报告:超过 50 章的旧报告 → archive/reviews.json
  14. 使用方式:
  15. # 自动归档检查(推荐在 update_state.py 之后调用)
  16. python archive_manager.py --auto-check
  17. # 强制归档(忽略触发条件)
  18. python archive_manager.py --force
  19. # 恢复特定角色
  20. python archive_manager.py --restore-character "李雪"
  21. # 查看归档统计
  22. python archive_manager.py --stats
  23. # Dry-run 模式(仅显示将被归档的数据)
  24. python archive_manager.py --auto-check --dry-run
  25. """
  26. import json
  27. import os
  28. import sys
  29. import argparse
  30. from datetime import datetime
  31. from pathlib import Path
  32. from runtime_compat import enable_windows_utf8_stdio
  33. # ============================================================================
  34. # 安全修复:导入安全工具函数(P1 MEDIUM)
  35. # ============================================================================
  36. from security_utils import create_secure_directory, atomic_write_json
  37. from project_locator import resolve_project_root
  38. # v5.1 引入: 使用 IndexManager 读取实体
  39. try:
  40. from data_modules.index_manager import IndexManager
  41. from data_modules.config import get_config
  42. except ImportError:
  43. from scripts.data_modules.index_manager import IndexManager
  44. from scripts.data_modules.config import get_config
  45. # Windows UTF-8 编码修复
  46. if sys.platform == "win32":
  47. enable_windows_utf8_stdio()
  48. class ArchiveManager:
  49. """state.json 数据归档管理器"""
  50. def __init__(self, project_root=None):
  51. if project_root is None:
  52. # 默认使用当前目录
  53. project_root = Path.cwd()
  54. else:
  55. project_root = Path(project_root)
  56. self.project_root = project_root
  57. self.state_file = project_root / ".webnovel" / "state.json"
  58. self.archive_dir = project_root / ".webnovel" / "archive"
  59. # v5.1 引入: IndexManager 用于读取实体
  60. self._config = get_config(project_root)
  61. self._index_manager = IndexManager(self._config)
  62. # ============================================================================
  63. # 安全修复:使用安全目录创建函数(P1 MEDIUM)
  64. # 原代码: self.archive_dir.mkdir(parents=True, exist_ok=True)
  65. # 漏洞: 未设置权限,使用OS默认(可能为755,允许同组用户读取)
  66. # ============================================================================
  67. create_secure_directory(str(self.archive_dir))
  68. # 归档文件路径
  69. self.characters_archive = self.archive_dir / "characters.json"
  70. self.plot_threads_archive = self.archive_dir / "plot_threads.json"
  71. self.reviews_archive = self.archive_dir / "reviews.json"
  72. # 归档规则配置
  73. self.config = {
  74. "character_inactive_threshold": 50, # 角色超过 50 章未出场视为不活跃
  75. "plot_resolved_threshold": 20, # 已回收伏笔超过 20 章后归档
  76. "review_old_threshold": 50, # 审查报告超过 50 章后归档
  77. "file_size_trigger_mb": 1.0, # state.json 超过 1.0MB 触发强制归档
  78. "chapter_trigger": 10 # 每 10 章检查一次
  79. }
  80. def load_state(self):
  81. """加载 state.json"""
  82. if not self.state_file.exists():
  83. print(f"❌ state.json 不存在: {self.state_file}")
  84. sys.exit(1)
  85. with open(self.state_file, 'r', encoding='utf-8') as f:
  86. return json.load(f)
  87. def save_state(self, state):
  88. """保存 state.json(原子化写入)"""
  89. # 使用集中式原子写入(自动备份)
  90. atomic_write_json(self.state_file, state, use_lock=True, backup=True)
  91. print(f"✅ state.json 已原子化更新")
  92. def load_archive(self, archive_file):
  93. """加载归档文件"""
  94. if not archive_file.exists():
  95. return []
  96. with open(archive_file, 'r', encoding='utf-8') as f:
  97. return json.load(f)
  98. def save_archive(self, archive_file, data):
  99. """保存归档文件"""
  100. with open(archive_file, 'w', encoding='utf-8') as f:
  101. json.dump(data, f, ensure_ascii=False, indent=2)
  102. def check_trigger_conditions(self, state):
  103. """检查是否需要触发归档"""
  104. current_chapter = state.get("progress", {}).get("current_chapter", 0)
  105. # 条件 1: 文件大小超过阈值
  106. file_size_mb = self.state_file.stat().st_size / (1024 * 1024)
  107. size_trigger = file_size_mb >= self.config["file_size_trigger_mb"]
  108. # 条件 2: 章节数是触发间隔的倍数
  109. chapter_trigger = (current_chapter % self.config["chapter_trigger"]) == 0 and current_chapter > 0
  110. return {
  111. "should_archive": size_trigger or chapter_trigger,
  112. "file_size_mb": file_size_mb,
  113. "current_chapter": current_chapter,
  114. "size_trigger": size_trigger,
  115. "chapter_trigger": chapter_trigger
  116. }
  117. def identify_inactive_characters(self, state):
  118. """识别不活跃的次要角色(v5.1 引入,v5.4 沿用)"""
  119. current_chapter = state.get("progress", {}).get("current_chapter", 0)
  120. threshold = self.config["character_inactive_threshold"]
  121. # v5.1 引入: 从 SQLite 获取所有角色实体
  122. characters = self._index_manager.get_entities_by_type("角色")
  123. inactive = []
  124. for char in characters:
  125. # 只归档次要角色(tier="装饰" 或 tier="支线")
  126. tier = str(char.get("tier", "")).strip()
  127. if tier == "核心":
  128. continue
  129. # 检查最后出场章节
  130. last_appearance = char.get("last_appearance", 0)
  131. try:
  132. last_appearance = int(last_appearance)
  133. except (TypeError, ValueError):
  134. last_appearance = 0
  135. if last_appearance <= 0:
  136. continue
  137. inactive_chapters = current_chapter - last_appearance
  138. if inactive_chapters >= threshold:
  139. char_id = char.get("id", "")
  140. char_data = {
  141. "id": char_id,
  142. "name": char.get("canonical_name", char_id),
  143. "tier": tier,
  144. "last_appearance_chapter": last_appearance
  145. }
  146. char_data.update(char)
  147. inactive.append({
  148. "character": char_data,
  149. "inactive_chapters": inactive_chapters,
  150. "last_appearance": last_appearance
  151. })
  152. return inactive
  153. def identify_resolved_plot_threads(self, state):
  154. """识别可归档的已回收伏笔"""
  155. current_chapter = state.get("progress", {}).get("current_chapter", 0)
  156. plot_threads = state.get("plot_threads", {}) or {}
  157. foreshadowing = plot_threads.get("foreshadowing", []) or []
  158. resolved_legacy = plot_threads.get("resolved", []) or []
  159. threshold = self.config["plot_resolved_threshold"]
  160. archivable = []
  161. # 新格式:plot_threads.foreshadowing(用 status 标识是否已回收)
  162. if isinstance(foreshadowing, list):
  163. for item in foreshadowing:
  164. if not isinstance(item, dict):
  165. continue
  166. status = str(item.get("status", "")).strip()
  167. if status not in ["已回收", "resolved"]:
  168. continue
  169. try:
  170. resolved_chapter = int(item.get("resolved_chapter", 0))
  171. except (TypeError, ValueError):
  172. continue
  173. chapters_since_resolved = current_chapter - resolved_chapter
  174. if chapters_since_resolved >= threshold:
  175. archivable.append({
  176. "thread": item,
  177. "chapters_since_resolved": chapters_since_resolved,
  178. "resolved_chapter": resolved_chapter
  179. })
  180. # 旧格式兼容:plot_threads.resolved(直接存已回收列表)
  181. if isinstance(resolved_legacy, list):
  182. for item in resolved_legacy:
  183. if not isinstance(item, dict):
  184. continue
  185. try:
  186. resolved_chapter = int(item.get("resolved_chapter", 0))
  187. except (TypeError, ValueError):
  188. continue
  189. chapters_since_resolved = current_chapter - resolved_chapter
  190. if chapters_since_resolved >= threshold:
  191. archivable.append({
  192. "thread": item,
  193. "chapters_since_resolved": chapters_since_resolved,
  194. "resolved_chapter": resolved_chapter
  195. })
  196. return archivable
  197. def identify_old_reviews(self, state):
  198. """识别可归档的旧审查报告"""
  199. current_chapter = state.get("progress", {}).get("current_chapter", 0)
  200. reviews = state.get("review_checkpoints", [])
  201. threshold = self.config["review_old_threshold"]
  202. def _parse_end_chapter(review: dict) -> int:
  203. # 新格式:{"chapters":"5-6","report":"...","reviewed_at":"..."}
  204. chapters = review.get("chapters")
  205. if isinstance(chapters, str):
  206. parts = [p.strip() for p in chapters.replace("—", "-").split("-") if p.strip()]
  207. if parts:
  208. try:
  209. return int(parts[-1])
  210. except ValueError:
  211. pass
  212. # 旧格式:{"chapter_range":[5,6], "date":"..."}
  213. cr = review.get("chapter_range")
  214. if isinstance(cr, (list, tuple)) and len(cr) >= 2:
  215. try:
  216. return int(cr[1])
  217. except (TypeError, ValueError):
  218. pass
  219. # 兜底:从 report 文件名里抓 "Ch5-6" 或 "第005-006"
  220. report = review.get("report")
  221. if isinstance(report, str):
  222. import re
  223. m = re.search(r"Ch(\d+)[-–—](\d+)", report)
  224. if m:
  225. try:
  226. return int(m.group(2))
  227. except ValueError:
  228. pass
  229. m = re.search(r"第(\d+)[-–—](\d+)章", report)
  230. if m:
  231. try:
  232. return int(m.group(2))
  233. except ValueError:
  234. pass
  235. return 0
  236. old_reviews = []
  237. for review in reviews:
  238. review_chapter = _parse_end_chapter(review)
  239. chapters_since_review = current_chapter - review_chapter
  240. if chapters_since_review >= threshold:
  241. old_reviews.append({
  242. "review": review,
  243. "chapters_since_review": chapters_since_review,
  244. "review_chapter": review_chapter
  245. })
  246. return old_reviews
  247. def archive_characters(self, inactive_list, dry_run=False):
  248. """归档不活跃角色(v5.1 引入:使用 IndexManager 更新状态)"""
  249. if not inactive_list:
  250. return 0
  251. # 加载现有归档
  252. archived = self.load_archive(self.characters_archive)
  253. # 添加时间戳
  254. timestamp = datetime.now().isoformat()
  255. for item in inactive_list:
  256. item["character"]["archived_at"] = timestamp
  257. archived.append(item["character"])
  258. # v5.1 引入: 通过 IndexManager 更新实体状态
  259. if not dry_run:
  260. try:
  261. entity_id = item["character"].get("id")
  262. if entity_id:
  263. # 更新实体的 current_json 添加 archived 标记
  264. self._index_manager.update_entity_field(
  265. entity_id, "status", "archived"
  266. )
  267. except Exception as e:
  268. print(f"⚠️ 实体状态更新失败(不影响归档): {e}")
  269. if not dry_run:
  270. self.save_archive(self.characters_archive, archived)
  271. return len(inactive_list)
  272. def archive_plot_threads(self, resolved_list, dry_run=False):
  273. """归档已回收伏笔"""
  274. if not resolved_list:
  275. return 0
  276. # 加载现有归档
  277. archived = self.load_archive(self.plot_threads_archive)
  278. # 添加时间戳
  279. timestamp = datetime.now().isoformat()
  280. for item in resolved_list:
  281. item["thread"]["archived_at"] = timestamp
  282. archived.append(item["thread"])
  283. if not dry_run:
  284. self.save_archive(self.plot_threads_archive, archived)
  285. return len(resolved_list)
  286. def archive_reviews(self, old_reviews_list, dry_run=False):
  287. """归档旧审查报告"""
  288. if not old_reviews_list:
  289. return 0
  290. # 加载现有归档
  291. archived = self.load_archive(self.reviews_archive)
  292. # 添加时间戳
  293. timestamp = datetime.now().isoformat()
  294. for item in old_reviews_list:
  295. item["review"]["archived_at"] = timestamp
  296. archived.append(item["review"])
  297. if not dry_run:
  298. self.save_archive(self.reviews_archive, archived)
  299. return len(old_reviews_list)
  300. def remove_from_state(self, state, inactive_chars, resolved_threads, old_reviews):
  301. """从 state.json/SQLite 中移除已归档的数据(v5.1 引入,v5.4 沿用)"""
  302. # v5.1 引入: 角色数据在 SQLite,archive_characters 已处理状态更新
  303. # 这里只需要处理 state.json 中的伏笔和审查报告
  304. # 移除已归档的伏笔
  305. if resolved_threads:
  306. thread_ids = {
  307. (item.get("thread", {}) or {}).get("content") or (item.get("thread", {}) or {}).get("description")
  308. for item in resolved_threads
  309. }
  310. thread_ids = {t for t in thread_ids if isinstance(t, str) and t.strip()}
  311. plot_threads = state.get("plot_threads", {}) or {}
  312. if isinstance(plot_threads.get("foreshadowing"), list):
  313. plot_threads["foreshadowing"] = [
  314. t for t in plot_threads["foreshadowing"]
  315. if not isinstance(t, dict) or (t.get("content") or t.get("description")) not in thread_ids
  316. ]
  317. if isinstance(plot_threads.get("resolved"), list):
  318. plot_threads["resolved"] = [
  319. t for t in plot_threads["resolved"]
  320. if not isinstance(t, dict) or (t.get("content") or t.get("description")) not in thread_ids
  321. ]
  322. state["plot_threads"] = plot_threads
  323. # 移除旧审查报告
  324. if old_reviews:
  325. review_keys = set()
  326. for item in old_reviews:
  327. review = item.get("review", {}) or {}
  328. key = review.get("report") or review.get("reviewed_at") or review.get("date")
  329. if isinstance(key, str) and key.strip():
  330. review_keys.add(key)
  331. state["review_checkpoints"] = [
  332. review for review in state.get("review_checkpoints", [])
  333. if (review.get("report") or review.get("reviewed_at") or review.get("date")) not in review_keys
  334. ]
  335. return state
  336. def run_auto_check(self, force=False, dry_run=False):
  337. """自动归档检查"""
  338. state = self.load_state()
  339. # 检查触发条件
  340. trigger = self.check_trigger_conditions(state)
  341. if not force and not trigger["should_archive"]:
  342. print("✅ 无需归档(触发条件未满足)")
  343. print(f" 文件大小: {trigger['file_size_mb']:.2f} MB (阈值: {self.config['file_size_trigger_mb']} MB)")
  344. print(f" 当前章节: {trigger['current_chapter']} (每 {self.config['chapter_trigger']} 章触发)")
  345. return
  346. print("🔍 开始归档检查...")
  347. print(f" 文件大小: {trigger['file_size_mb']:.2f} MB")
  348. print(f" 当前章节: {trigger['current_chapter']}")
  349. # 识别可归档数据
  350. inactive_chars = self.identify_inactive_characters(state)
  351. resolved_threads = self.identify_resolved_plot_threads(state)
  352. old_reviews = self.identify_old_reviews(state)
  353. # 输出统计
  354. print(f"\n📊 归档统计:")
  355. print(f" 不活跃角色: {len(inactive_chars)}")
  356. print(f" 已回收伏笔: {len(resolved_threads)}")
  357. print(f" 旧审查报告: {len(old_reviews)}")
  358. if not (inactive_chars or resolved_threads or old_reviews):
  359. print("\n✅ 无需归档(无符合条件的数据)")
  360. return
  361. # Dry-run 模式
  362. if dry_run:
  363. print("\n🔍 [Dry-run] 将被归档的数据:")
  364. if inactive_chars:
  365. print("\n 不活跃角色:")
  366. for item in inactive_chars[:5]: # 只显示前 5 个
  367. print(f" - {item['character']['name']} (超过 {item['inactive_chapters']} 章未出场)")
  368. if resolved_threads:
  369. print("\n 已回收伏笔:")
  370. for item in resolved_threads[:5]:
  371. desc = item["thread"].get("content") or item["thread"].get("description") or ""
  372. print(f" - {str(desc)[:30]}... (已回收 {item['chapters_since_resolved']} 章)")
  373. if old_reviews:
  374. print("\n 旧审查报告:")
  375. for item in old_reviews[:5]:
  376. print(f" - Ch{item['review_chapter']} ({item['chapters_since_review']} 章前)")
  377. return
  378. # 执行归档
  379. chars_archived = self.archive_characters(inactive_chars, dry_run=dry_run)
  380. threads_archived = self.archive_plot_threads(resolved_threads, dry_run=dry_run)
  381. reviews_archived = self.archive_reviews(old_reviews, dry_run=dry_run)
  382. # 从 state.json 中移除
  383. state = self.remove_from_state(state, inactive_chars, resolved_threads, old_reviews)
  384. self.save_state(state)
  385. # 最终统计
  386. print(f"\n✅ 归档完成:")
  387. print(f" 角色归档: {chars_archived} → {self.characters_archive.name}")
  388. print(f" 伏笔归档: {threads_archived} → {self.plot_threads_archive.name}")
  389. print(f" 报告归档: {reviews_archived} → {self.reviews_archive.name}")
  390. # 显示归档后的文件大小
  391. new_size_mb = self.state_file.stat().st_size / (1024 * 1024)
  392. saved_mb = trigger["file_size_mb"] - new_size_mb
  393. print(f"\n💾 文件大小: {trigger['file_size_mb']:.2f} MB → {new_size_mb:.2f} MB (节省 {saved_mb:.2f} MB)")
  394. def restore_character(self, name):
  395. """恢复归档的角色(v5.1 引入:使用 IndexManager 恢复状态)"""
  396. archived = self.load_archive(self.characters_archive)
  397. # 查找角色
  398. char_to_restore = None
  399. for char in archived:
  400. if char["name"] == name:
  401. char_to_restore = char
  402. break
  403. if not char_to_restore:
  404. print(f"❌ 归档中未找到角色: {name}")
  405. return
  406. # 移除 archived_at 字段
  407. char_to_restore.pop("archived_at", None)
  408. # 原子性修复:先从归档中移除
  409. archived = [char for char in archived if char["name"] != name]
  410. self.save_archive(self.characters_archive, archived)
  411. # v5.1 引入: 恢复到 SQLite (通过 IndexManager)
  412. char_id = char_to_restore.get("id", char_to_restore.get("name", "unknown"))
  413. try:
  414. # 更新实体状态为 active
  415. self._index_manager.update_entity_field(char_id, "status", "active")
  416. print(f"✅ 角色已恢复: {name}")
  417. except Exception as e:
  418. print(f"⚠️ 实体状态恢复失败: {e}")
  419. def show_stats(self):
  420. """显示归档统计"""
  421. chars = self.load_archive(self.characters_archive)
  422. threads = self.load_archive(self.plot_threads_archive)
  423. reviews = self.load_archive(self.reviews_archive)
  424. print("📊 归档统计:")
  425. print(f" 角色归档: {len(chars)}")
  426. print(f" 伏笔归档: {len(threads)}")
  427. print(f" 报告归档: {len(reviews)}")
  428. # 计算归档文件大小
  429. total_size = 0
  430. for archive_file in [self.characters_archive, self.plot_threads_archive, self.reviews_archive]:
  431. if archive_file.exists():
  432. total_size += archive_file.stat().st_size
  433. print(f" 归档大小: {total_size / 1024:.2f} KB")
  434. # 显示 state.json 大小
  435. state_size_mb = self.state_file.stat().st_size / (1024 * 1024)
  436. print(f"\n💾 state.json 当前大小: {state_size_mb:.2f} MB")
  437. def main():
  438. parser = argparse.ArgumentParser(description="state.json 数据归档管理")
  439. parser.add_argument("--auto-check", action="store_true", help="自动归档检查")
  440. parser.add_argument("--force", action="store_true", help="强制归档(忽略触发条件)")
  441. parser.add_argument("--dry-run", action="store_true", help="Dry-run 模式(仅显示将被归档的数据)")
  442. parser.add_argument("--restore-character", metavar="NAME", help="恢复归档的角色")
  443. parser.add_argument("--stats", action="store_true", help="显示归档统计")
  444. parser.add_argument("--project-root", metavar="PATH", help="项目根目录(默认为当前目录)")
  445. args = parser.parse_args()
  446. # 创建管理器(支持从仓库根目录运行)
  447. project_root = args.project_root
  448. if project_root is None and not (Path.cwd() / ".webnovel" / "state.json").exists():
  449. try:
  450. project_root = str(resolve_project_root())
  451. except FileNotFoundError:
  452. project_root = None
  453. manager = ArchiveManager(project_root=project_root)
  454. # 执行操作
  455. if args.auto_check or args.force:
  456. manager.run_auto_check(force=args.force, dry_run=args.dry_run)
  457. elif args.restore_character:
  458. manager.restore_character(args.restore_character)
  459. elif args.stats:
  460. manager.show_stats()
  461. else:
  462. parser.print_help()
  463. if __name__ == "__main__":
  464. main()