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