archive_manager.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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
  36. from project_locator import resolve_project_root
  37. # Windows UTF-8 编码修复
  38. if sys.platform == 'win32':
  39. import io
  40. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
  41. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
  42. class ArchiveManager:
  43. """state.json 数据归档管理器"""
  44. def __init__(self, project_root=None):
  45. if project_root is None:
  46. # 默认使用当前目录
  47. project_root = Path.cwd()
  48. else:
  49. project_root = Path(project_root)
  50. self.state_file = project_root / ".webnovel" / "state.json"
  51. self.archive_dir = project_root / ".webnovel" / "archive"
  52. # ============================================================================
  53. # 安全修复:使用安全目录创建函数(P1 MEDIUM)
  54. # 原代码: self.archive_dir.mkdir(parents=True, exist_ok=True)
  55. # 漏洞: 未设置权限,使用OS默认(可能为755,允许同组用户读取)
  56. # ============================================================================
  57. create_secure_directory(str(self.archive_dir))
  58. # 归档文件路径
  59. self.characters_archive = self.archive_dir / "characters.json"
  60. self.plot_threads_archive = self.archive_dir / "plot_threads.json"
  61. self.reviews_archive = self.archive_dir / "reviews.json"
  62. # 归档规则配置
  63. self.config = {
  64. "character_inactive_threshold": 50, # 角色超过 50 章未出场视为不活跃
  65. "plot_resolved_threshold": 20, # 已回收伏笔超过 20 章后归档
  66. "review_old_threshold": 20, # 审查报告超过 20 章后归档(从 50 降至 20)
  67. "file_size_trigger_mb": 0.5, # state.json 超过 0.5MB 触发归档(从 1.0 降至 0.5)
  68. "chapter_trigger": 10 # 每 10 章检查一次
  69. }
  70. def load_state(self):
  71. """加载 state.json"""
  72. if not self.state_file.exists():
  73. print(f"❌ state.json 不存在: {self.state_file}")
  74. sys.exit(1)
  75. with open(self.state_file, 'r', encoding='utf-8') as f:
  76. return json.load(f)
  77. def save_state(self, state):
  78. """保存 state.json(带备份)"""
  79. # 备份原文件
  80. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  81. backup_file = self.state_file.parent / f"state.backup_{timestamp}.json"
  82. if self.state_file.exists():
  83. import shutil
  84. shutil.copy2(self.state_file, backup_file)
  85. # 写入新文件
  86. with open(self.state_file, 'w', encoding='utf-8') as f:
  87. json.dump(state, f, ensure_ascii=False, indent=2)
  88. print(f"✅ state.json 已更新(备份: {backup_file.name})")
  89. def load_archive(self, archive_file):
  90. """加载归档文件"""
  91. if not archive_file.exists():
  92. return []
  93. with open(archive_file, 'r', encoding='utf-8') as f:
  94. return json.load(f)
  95. def save_archive(self, archive_file, data):
  96. """保存归档文件"""
  97. with open(archive_file, 'w', encoding='utf-8') as f:
  98. json.dump(data, f, ensure_ascii=False, indent=2)
  99. def check_trigger_conditions(self, state):
  100. """检查是否需要触发归档"""
  101. current_chapter = state.get("progress", {}).get("current_chapter", 0)
  102. # 条件 1: 文件大小超过阈值
  103. file_size_mb = self.state_file.stat().st_size / (1024 * 1024)
  104. size_trigger = file_size_mb >= self.config["file_size_trigger_mb"]
  105. # 条件 2: 章节数是触发间隔的倍数
  106. chapter_trigger = (current_chapter % self.config["chapter_trigger"]) == 0 and current_chapter > 0
  107. return {
  108. "should_archive": size_trigger or chapter_trigger,
  109. "file_size_mb": file_size_mb,
  110. "current_chapter": current_chapter,
  111. "size_trigger": size_trigger,
  112. "chapter_trigger": chapter_trigger
  113. }
  114. def identify_inactive_characters(self, state):
  115. """识别不活跃的次要角色"""
  116. current_chapter = state.get("progress", {}).get("current_chapter", 0)
  117. characters = state.get("entities", {}).get("characters", [])
  118. threshold = self.config["character_inactive_threshold"]
  119. inactive = []
  120. for char in characters:
  121. # 只归档次要角色(importance="minor")
  122. if char.get("importance") != "minor":
  123. continue
  124. # 检查最后出场章节
  125. last_appearance = char.get("last_appearance_chapter", 0)
  126. inactive_chapters = current_chapter - last_appearance
  127. if inactive_chapters >= threshold:
  128. inactive.append({
  129. "character": char,
  130. "inactive_chapters": inactive_chapters,
  131. "last_appearance": last_appearance
  132. })
  133. return inactive
  134. def identify_resolved_plot_threads(self, state):
  135. """识别可归档的已回收伏笔"""
  136. current_chapter = state.get("progress", {}).get("current_chapter", 0)
  137. plot_threads = state.get("plot_threads", {}).get("active", [])
  138. resolved = state.get("plot_threads", {}).get("resolved", [])
  139. threshold = self.config["plot_resolved_threshold"]
  140. archivable = []
  141. for thread in resolved:
  142. resolved_chapter = thread.get("resolved_chapter", 0)
  143. chapters_since_resolved = current_chapter - resolved_chapter
  144. if chapters_since_resolved >= threshold:
  145. archivable.append({
  146. "thread": thread,
  147. "chapters_since_resolved": chapters_since_resolved,
  148. "resolved_chapter": resolved_chapter
  149. })
  150. return archivable
  151. def identify_old_reviews(self, state):
  152. """识别可归档的旧审查报告"""
  153. current_chapter = state.get("progress", {}).get("current_chapter", 0)
  154. reviews = state.get("review_checkpoints", [])
  155. threshold = self.config["review_old_threshold"]
  156. old_reviews = []
  157. for review in reviews:
  158. review_chapter = review.get("chapter_range", [0, 0])[1] # 取结束章节
  159. chapters_since_review = current_chapter - review_chapter
  160. if chapters_since_review >= threshold:
  161. old_reviews.append({
  162. "review": review,
  163. "chapters_since_review": chapters_since_review,
  164. "review_chapter": review_chapter
  165. })
  166. return old_reviews
  167. def archive_characters(self, inactive_list, dry_run=False):
  168. """归档不活跃角色(Priority 2 修复:与索引集成)"""
  169. if not inactive_list:
  170. return 0
  171. # 加载现有归档
  172. archived = self.load_archive(self.characters_archive)
  173. # 添加时间戳
  174. timestamp = datetime.now().isoformat()
  175. for item in inactive_list:
  176. item["character"]["archived_at"] = timestamp
  177. archived.append(item["character"])
  178. # ✅ Priority 2 修复:同步更新索引状态(而非删除)
  179. if not dry_run:
  180. try:
  181. # 导入索引模块
  182. import sys
  183. from pathlib import Path
  184. script_dir = Path(__file__).parent
  185. sys.path.insert(0, str(script_dir))
  186. from structured_index import StructuredIndex
  187. # 更新索引状态为 'archived'
  188. project_root = self.state_file.parent.parent
  189. index = StructuredIndex(str(project_root))
  190. index.mark_character_archived(item["character"]["name"], timestamp)
  191. except Exception as e:
  192. # 索引更新失败不影响归档流程
  193. print(f"⚠️ 索引状态更新失败(不影响归档): {e}")
  194. if not dry_run:
  195. self.save_archive(self.characters_archive, archived)
  196. return len(inactive_list)
  197. def archive_plot_threads(self, resolved_list, dry_run=False):
  198. """归档已回收伏笔"""
  199. if not resolved_list:
  200. return 0
  201. # 加载现有归档
  202. archived = self.load_archive(self.plot_threads_archive)
  203. # 添加时间戳
  204. timestamp = datetime.now().isoformat()
  205. for item in resolved_list:
  206. item["thread"]["archived_at"] = timestamp
  207. archived.append(item["thread"])
  208. if not dry_run:
  209. self.save_archive(self.plot_threads_archive, archived)
  210. return len(resolved_list)
  211. def archive_reviews(self, old_reviews_list, dry_run=False):
  212. """归档旧审查报告"""
  213. if not old_reviews_list:
  214. return 0
  215. # 加载现有归档
  216. archived = self.load_archive(self.reviews_archive)
  217. # 添加时间戳
  218. timestamp = datetime.now().isoformat()
  219. for item in old_reviews_list:
  220. item["review"]["archived_at"] = timestamp
  221. archived.append(item["review"])
  222. if not dry_run:
  223. self.save_archive(self.reviews_archive, archived)
  224. return len(old_reviews_list)
  225. def remove_from_state(self, state, inactive_chars, resolved_threads, old_reviews):
  226. """从 state.json 中移除已归档的数据"""
  227. # 移除不活跃角色
  228. if inactive_chars:
  229. char_names = {item["character"]["name"] for item in inactive_chars}
  230. state["entities"]["characters"] = [
  231. char for char in state["entities"]["characters"]
  232. if char["name"] not in char_names
  233. ]
  234. # 移除已归档的伏笔
  235. if resolved_threads:
  236. thread_ids = {item["thread"]["description"] for item in resolved_threads}
  237. state["plot_threads"]["resolved"] = [
  238. thread for thread in state["plot_threads"]["resolved"]
  239. if thread["description"] not in thread_ids
  240. ]
  241. # 移除旧审查报告
  242. if old_reviews:
  243. review_dates = {item["review"]["date"] for item in old_reviews}
  244. state["review_checkpoints"] = [
  245. review for review in state["review_checkpoints"]
  246. if review["date"] not in review_dates
  247. ]
  248. return state
  249. def run_auto_check(self, force=False, dry_run=False):
  250. """自动归档检查"""
  251. state = self.load_state()
  252. # 检查触发条件
  253. trigger = self.check_trigger_conditions(state)
  254. if not force and not trigger["should_archive"]:
  255. print("✅ 无需归档(触发条件未满足)")
  256. print(f" 文件大小: {trigger['file_size_mb']:.2f} MB (阈值: {self.config['file_size_trigger_mb']} MB)")
  257. print(f" 当前章节: {trigger['current_chapter']} (每 {self.config['chapter_trigger']} 章触发)")
  258. return
  259. print("🔍 开始归档检查...")
  260. print(f" 文件大小: {trigger['file_size_mb']:.2f} MB")
  261. print(f" 当前章节: {trigger['current_chapter']}")
  262. # 识别可归档数据
  263. inactive_chars = self.identify_inactive_characters(state)
  264. resolved_threads = self.identify_resolved_plot_threads(state)
  265. old_reviews = self.identify_old_reviews(state)
  266. # 输出统计
  267. print(f"\n📊 归档统计:")
  268. print(f" 不活跃角色: {len(inactive_chars)}")
  269. print(f" 已回收伏笔: {len(resolved_threads)}")
  270. print(f" 旧审查报告: {len(old_reviews)}")
  271. if not (inactive_chars or resolved_threads or old_reviews):
  272. print("\n✅ 无需归档(无符合条件的数据)")
  273. return
  274. # Dry-run 模式
  275. if dry_run:
  276. print("\n🔍 [Dry-run] 将被归档的数据:")
  277. if inactive_chars:
  278. print("\n 不活跃角色:")
  279. for item in inactive_chars[:5]: # 只显示前 5 个
  280. print(f" - {item['character']['name']} (超过 {item['inactive_chapters']} 章未出场)")
  281. if resolved_threads:
  282. print("\n 已回收伏笔:")
  283. for item in resolved_threads[:5]:
  284. print(f" - {item['thread']['description'][:30]}... (已回收 {item['chapters_since_resolved']} 章)")
  285. if old_reviews:
  286. print("\n 旧审查报告:")
  287. for item in old_reviews[:5]:
  288. print(f" - Ch{item['review_chapter']} ({item['chapters_since_review']} 章前)")
  289. return
  290. # 执行归档
  291. chars_archived = self.archive_characters(inactive_chars, dry_run=dry_run)
  292. threads_archived = self.archive_plot_threads(resolved_threads, dry_run=dry_run)
  293. reviews_archived = self.archive_reviews(old_reviews, dry_run=dry_run)
  294. # 从 state.json 中移除
  295. state = self.remove_from_state(state, inactive_chars, resolved_threads, old_reviews)
  296. self.save_state(state)
  297. # 最终统计
  298. print(f"\n✅ 归档完成:")
  299. print(f" 角色归档: {chars_archived} → {self.characters_archive.name}")
  300. print(f" 伏笔归档: {threads_archived} → {self.plot_threads_archive.name}")
  301. print(f" 报告归档: {reviews_archived} → {self.reviews_archive.name}")
  302. # 显示归档后的文件大小
  303. new_size_mb = self.state_file.stat().st_size / (1024 * 1024)
  304. saved_mb = trigger["file_size_mb"] - new_size_mb
  305. print(f"\n💾 文件大小: {trigger['file_size_mb']:.2f} MB → {new_size_mb:.2f} MB (节省 {saved_mb:.2f} MB)")
  306. def restore_character(self, name):
  307. """恢复归档的角色(Priority 2 修复:同步恢复索引状态)"""
  308. archived = self.load_archive(self.characters_archive)
  309. state = self.load_state()
  310. # 查找角色
  311. char_to_restore = None
  312. for char in archived:
  313. if char["name"] == name:
  314. char_to_restore = char
  315. break
  316. if not char_to_restore:
  317. print(f"❌ 归档中未找到角色: {name}")
  318. return
  319. # 移除 archived_at 字段
  320. char_to_restore.pop("archived_at", None)
  321. # ✅ 原子性修复:先从归档中移除,再添加到 state.json
  322. # 理由:即使崩溃,数据仍在归档中,可重新恢复,不会丢失或重复
  323. archived = [char for char in archived if char["name"] != name]
  324. self.save_archive(self.characters_archive, archived)
  325. # 恢复到 state.json
  326. state["entities"]["characters"].append(char_to_restore)
  327. self.save_state(state)
  328. # ✅ Priority 2 修复:同步恢复索引状态为 'active'
  329. try:
  330. import sys
  331. from pathlib import Path
  332. script_dir = Path(__file__).parent
  333. sys.path.insert(0, str(script_dir))
  334. from structured_index import StructuredIndex
  335. project_root = self.state_file.parent.parent
  336. index = StructuredIndex(str(project_root))
  337. index.mark_character_active(name)
  338. except Exception as e:
  339. print(f"⚠️ 索引状态恢复失败(不影响数据恢复): {e}")
  340. print(f"✅ 角色已恢复: {name}")
  341. def show_stats(self):
  342. """显示归档统计"""
  343. chars = self.load_archive(self.characters_archive)
  344. threads = self.load_archive(self.plot_threads_archive)
  345. reviews = self.load_archive(self.reviews_archive)
  346. print("📊 归档统计:")
  347. print(f" 角色归档: {len(chars)}")
  348. print(f" 伏笔归档: {len(threads)}")
  349. print(f" 报告归档: {len(reviews)}")
  350. # 计算归档文件大小
  351. total_size = 0
  352. for archive_file in [self.characters_archive, self.plot_threads_archive, self.reviews_archive]:
  353. if archive_file.exists():
  354. total_size += archive_file.stat().st_size
  355. print(f" 归档大小: {total_size / 1024:.2f} KB")
  356. # 显示 state.json 大小
  357. state_size_mb = self.state_file.stat().st_size / (1024 * 1024)
  358. print(f"\n💾 state.json 当前大小: {state_size_mb:.2f} MB")
  359. def main():
  360. parser = argparse.ArgumentParser(description="state.json 数据归档管理")
  361. parser.add_argument("--auto-check", action="store_true", help="自动归档检查")
  362. parser.add_argument("--force", action="store_true", help="强制归档(忽略触发条件)")
  363. parser.add_argument("--dry-run", action="store_true", help="Dry-run 模式(仅显示将被归档的数据)")
  364. parser.add_argument("--restore-character", metavar="NAME", help="恢复归档的角色")
  365. parser.add_argument("--stats", action="store_true", help="显示归档统计")
  366. parser.add_argument("--project-root", metavar="PATH", help="项目根目录(默认为当前目录)")
  367. args = parser.parse_args()
  368. # 创建管理器(支持从仓库根目录运行)
  369. project_root = args.project_root
  370. if project_root is None and not (Path.cwd() / ".webnovel" / "state.json").exists():
  371. try:
  372. project_root = str(resolve_project_root())
  373. except FileNotFoundError:
  374. project_root = None
  375. manager = ArchiveManager(project_root=project_root)
  376. # 执行操作
  377. if args.auto_check or args.force:
  378. manager.run_auto_check(force=args.force, dry_run=args.dry_run)
  379. elif args.restore_character:
  380. manager.restore_character(args.restore_character)
  381. elif args.stats:
  382. manager.show_stats()
  383. else:
  384. parser.print_help()
  385. if __name__ == "__main__":
  386. main()