1
0

index_manager.py 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Index Manager - 索引管理模块 (v5.4)
  5. 管理 index.db (SQLite) 的读写操作:
  6. - 章节元数据索引
  7. - 实体出场记录
  8. - 场景索引
  9. - 实体存储 (从 state.json 迁移)
  10. - 别名索引 (一对多)
  11. - 状态变化记录
  12. - 关系存储
  13. - 快速查询接口
  14. - 追读力债务管理 (v5.3 引入,v5.4 沿用)
  15. v5.4 变更:
  16. - 新增 invalid_facts 表:追踪无效事实 (pending/confirmed)
  17. - 新增 tool_call_stats 表:记录工具调用成功率与错误信息
  18. - 新增 review_metrics 表:记录审查指标与趋势数据
  19. v5.3 变更:
  20. - 新增 override_contracts 表:记录违背软建议时的Override Contract
  21. - 新增 chase_debt 表:追读力债务追踪
  22. - 新增 debt_events 表:债务事件日志(产生/偿还/利息)
  23. - 新增 chapter_reading_power 表:章节追读力元数据
  24. v5.1 变更:
  25. - 新增 entities 表替代 state.json 中的 entities_v3
  26. - 新增 aliases 表替代 state.json 中的 alias_index (支持一对多)
  27. - 新增 state_changes 表替代 state.json 中的 state_changes
  28. - 新增 relationships 表替代 state.json 中的 structured_relationships
  29. """
  30. import sqlite3
  31. import json
  32. from pathlib import Path
  33. from typing import Dict, List, Optional, Any, Tuple
  34. from dataclasses import dataclass, field
  35. from contextlib import contextmanager
  36. from datetime import datetime
  37. from .config import get_config
  38. @dataclass
  39. class ChapterMeta:
  40. """章节元数据"""
  41. chapter: int
  42. title: str
  43. location: str
  44. word_count: int
  45. characters: List[str]
  46. summary: str = ""
  47. @dataclass
  48. class SceneMeta:
  49. """场景元数据"""
  50. chapter: int
  51. scene_index: int
  52. start_line: int
  53. end_line: int
  54. location: str
  55. summary: str
  56. characters: List[str]
  57. @dataclass
  58. class EntityMeta:
  59. """实体元数据 (v5.1 引入)"""
  60. id: str
  61. type: str # 角色/地点/物品/势力/招式
  62. canonical_name: str
  63. tier: str = "装饰" # 核心/重要/次要/装饰
  64. desc: str = ""
  65. current: Dict = field(default_factory=dict) # 当前状态 (realm/location/items等)
  66. first_appearance: int = 0
  67. last_appearance: int = 0
  68. is_protagonist: bool = False
  69. is_archived: bool = False
  70. @dataclass
  71. class StateChangeMeta:
  72. """状态变化记录 (v5.1 引入)"""
  73. entity_id: str
  74. field: str
  75. old_value: str
  76. new_value: str
  77. reason: str
  78. chapter: int
  79. @dataclass
  80. class RelationshipMeta:
  81. """关系记录 (v5.1 引入)"""
  82. from_entity: str
  83. to_entity: str
  84. type: str
  85. description: str
  86. chapter: int
  87. @dataclass
  88. class OverrideContractMeta:
  89. """Override Contract (v5.3 引入)"""
  90. chapter: int
  91. constraint_type: str # SOFT_HOOK_STRENGTH / SOFT_MICROPAYOFF / etc.
  92. constraint_id: str # 具体约束标识
  93. rationale_type: str # TRANSITIONAL_SETUP / LOGIC_INTEGRITY / etc.
  94. rationale_text: str # 具体理由说明
  95. payback_plan: str # 偿还计划描述
  96. due_chapter: int # 偿还截止章节
  97. status: str = "pending" # pending / fulfilled / overdue / cancelled
  98. @dataclass
  99. class ChaseDebtMeta:
  100. """追读力债务 (v5.3 引入)"""
  101. id: int = 0
  102. debt_type: str = "" # hook_strength / micropayoff / coolpoint / etc.
  103. original_amount: float = 1.0 # 初始债务量
  104. current_amount: float = 1.0 # 当前债务量(含利息)
  105. interest_rate: float = 0.1 # 利息率(每章)
  106. source_chapter: int = 0 # 产生债务的章节
  107. due_chapter: int = 0 # 截止章节
  108. override_contract_id: int = 0 # 关联的Override Contract
  109. status: str = "active" # active / paid / overdue / written_off
  110. @dataclass
  111. class DebtEventMeta:
  112. """债务事件日志 (v5.3 引入)"""
  113. debt_id: int
  114. event_type: (
  115. str # created / interest_accrued / partial_payment / full_payment / overdue
  116. )
  117. amount: float
  118. chapter: int
  119. note: str = ""
  120. @dataclass
  121. class ChapterReadingPowerMeta:
  122. """章节追读力元数据 (v5.3 引入)"""
  123. chapter: int
  124. hook_type: str = "" # 章末钩子类型
  125. hook_strength: str = "medium" # strong / medium / weak
  126. coolpoint_patterns: List[str] = field(default_factory=list) # 使用的爽点模式
  127. micropayoffs: List[str] = field(default_factory=list) # 微兑现列表
  128. hard_violations: List[str] = field(default_factory=list) # 硬约束违规
  129. soft_suggestions: List[str] = field(default_factory=list) # 软建议
  130. is_transition: bool = False # 是否为过渡章
  131. override_count: int = 0 # Override Contract数量
  132. debt_balance: float = 0.0 # 当前债务余额
  133. @dataclass
  134. class ReviewMetrics:
  135. """审查指标记录 (v5.4 引入)"""
  136. start_chapter: int
  137. end_chapter: int
  138. overall_score: float = 0.0
  139. dimension_scores: Dict[str, float] = field(default_factory=dict)
  140. severity_counts: Dict[str, int] = field(default_factory=dict)
  141. critical_issues: List[str] = field(default_factory=list)
  142. report_file: str = ""
  143. notes: str = ""
  144. class IndexManager:
  145. """索引管理器"""
  146. def __init__(self, config=None):
  147. self.config = config or get_config()
  148. self._init_db()
  149. def _init_db(self):
  150. """初始化数据库表"""
  151. self.config.ensure_dirs()
  152. with self._get_conn() as conn:
  153. cursor = conn.cursor()
  154. # 章节表
  155. cursor.execute("""
  156. CREATE TABLE IF NOT EXISTS chapters (
  157. chapter INTEGER PRIMARY KEY,
  158. title TEXT,
  159. location TEXT,
  160. word_count INTEGER,
  161. characters TEXT,
  162. summary TEXT,
  163. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  164. )
  165. """)
  166. # 场景表
  167. cursor.execute("""
  168. CREATE TABLE IF NOT EXISTS scenes (
  169. id INTEGER PRIMARY KEY AUTOINCREMENT,
  170. chapter INTEGER,
  171. scene_index INTEGER,
  172. start_line INTEGER,
  173. end_line INTEGER,
  174. location TEXT,
  175. summary TEXT,
  176. characters TEXT,
  177. UNIQUE(chapter, scene_index)
  178. )
  179. """)
  180. # 实体出场表
  181. cursor.execute("""
  182. CREATE TABLE IF NOT EXISTS appearances (
  183. id INTEGER PRIMARY KEY AUTOINCREMENT,
  184. entity_id TEXT,
  185. chapter INTEGER,
  186. mentions TEXT,
  187. confidence REAL,
  188. UNIQUE(entity_id, chapter)
  189. )
  190. """)
  191. # 创建索引
  192. cursor.execute(
  193. "CREATE INDEX IF NOT EXISTS idx_scenes_chapter ON scenes(chapter)"
  194. )
  195. cursor.execute(
  196. "CREATE INDEX IF NOT EXISTS idx_appearances_entity ON appearances(entity_id)"
  197. )
  198. cursor.execute(
  199. "CREATE INDEX IF NOT EXISTS idx_appearances_chapter ON appearances(chapter)"
  200. )
  201. # ==================== v5.1 引入表 ====================
  202. # 实体表 (替代 state.json 中的 entities_v3)
  203. cursor.execute("""
  204. CREATE TABLE IF NOT EXISTS entities (
  205. id TEXT PRIMARY KEY,
  206. type TEXT NOT NULL,
  207. canonical_name TEXT NOT NULL,
  208. tier TEXT DEFAULT '装饰',
  209. desc TEXT,
  210. current_json TEXT,
  211. first_appearance INTEGER DEFAULT 0,
  212. last_appearance INTEGER DEFAULT 0,
  213. is_protagonist INTEGER DEFAULT 0,
  214. is_archived INTEGER DEFAULT 0,
  215. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  216. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  217. )
  218. """)
  219. # 别名表 (替代 state.json 中的 alias_index,支持一对多)
  220. cursor.execute("""
  221. CREATE TABLE IF NOT EXISTS aliases (
  222. alias TEXT NOT NULL,
  223. entity_id TEXT NOT NULL,
  224. entity_type TEXT NOT NULL,
  225. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  226. PRIMARY KEY (alias, entity_id, entity_type)
  227. )
  228. """)
  229. # 状态变化表 (替代 state.json 中的 state_changes)
  230. cursor.execute("""
  231. CREATE TABLE IF NOT EXISTS state_changes (
  232. id INTEGER PRIMARY KEY AUTOINCREMENT,
  233. entity_id TEXT NOT NULL,
  234. field TEXT NOT NULL,
  235. old_value TEXT,
  236. new_value TEXT,
  237. reason TEXT,
  238. chapter INTEGER NOT NULL,
  239. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  240. )
  241. """)
  242. # 关系表 (替代 state.json 中的 structured_relationships)
  243. cursor.execute("""
  244. CREATE TABLE IF NOT EXISTS relationships (
  245. id INTEGER PRIMARY KEY AUTOINCREMENT,
  246. from_entity TEXT NOT NULL,
  247. to_entity TEXT NOT NULL,
  248. type TEXT NOT NULL,
  249. description TEXT,
  250. chapter INTEGER NOT NULL,
  251. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  252. UNIQUE(from_entity, to_entity, type)
  253. )
  254. """)
  255. # v5.1 引入索引
  256. cursor.execute(
  257. "CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type)"
  258. )
  259. cursor.execute(
  260. "CREATE INDEX IF NOT EXISTS idx_entities_tier ON entities(tier)"
  261. )
  262. cursor.execute(
  263. "CREATE INDEX IF NOT EXISTS idx_entities_protagonist ON entities(is_protagonist)"
  264. )
  265. cursor.execute(
  266. "CREATE INDEX IF NOT EXISTS idx_aliases_entity ON aliases(entity_id)"
  267. )
  268. cursor.execute(
  269. "CREATE INDEX IF NOT EXISTS idx_aliases_alias ON aliases(alias)"
  270. )
  271. cursor.execute(
  272. "CREATE INDEX IF NOT EXISTS idx_state_changes_entity ON state_changes(entity_id)"
  273. )
  274. cursor.execute(
  275. "CREATE INDEX IF NOT EXISTS idx_state_changes_chapter ON state_changes(chapter)"
  276. )
  277. cursor.execute(
  278. "CREATE INDEX IF NOT EXISTS idx_relationships_from ON relationships(from_entity)"
  279. )
  280. cursor.execute(
  281. "CREATE INDEX IF NOT EXISTS idx_relationships_to ON relationships(to_entity)"
  282. )
  283. cursor.execute(
  284. "CREATE INDEX IF NOT EXISTS idx_relationships_chapter ON relationships(chapter)"
  285. )
  286. # ==================== v5.3 引入表:追读力债务管理 ====================
  287. # Override Contract 表
  288. cursor.execute("""
  289. CREATE TABLE IF NOT EXISTS override_contracts (
  290. id INTEGER PRIMARY KEY AUTOINCREMENT,
  291. chapter INTEGER NOT NULL,
  292. constraint_type TEXT NOT NULL,
  293. constraint_id TEXT NOT NULL,
  294. rationale_type TEXT NOT NULL,
  295. rationale_text TEXT,
  296. payback_plan TEXT,
  297. due_chapter INTEGER NOT NULL,
  298. status TEXT DEFAULT 'pending',
  299. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  300. fulfilled_at TIMESTAMP,
  301. UNIQUE(chapter, constraint_type, constraint_id)
  302. )
  303. """)
  304. # 追读力债务表
  305. cursor.execute("""
  306. CREATE TABLE IF NOT EXISTS chase_debt (
  307. id INTEGER PRIMARY KEY AUTOINCREMENT,
  308. debt_type TEXT NOT NULL,
  309. original_amount REAL DEFAULT 1.0,
  310. current_amount REAL DEFAULT 1.0,
  311. interest_rate REAL DEFAULT 0.1,
  312. source_chapter INTEGER NOT NULL,
  313. due_chapter INTEGER NOT NULL,
  314. override_contract_id INTEGER,
  315. status TEXT DEFAULT 'active',
  316. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  317. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  318. FOREIGN KEY (override_contract_id) REFERENCES override_contracts(id)
  319. )
  320. """)
  321. # 债务事件日志表
  322. cursor.execute("""
  323. CREATE TABLE IF NOT EXISTS debt_events (
  324. id INTEGER PRIMARY KEY AUTOINCREMENT,
  325. debt_id INTEGER NOT NULL,
  326. event_type TEXT NOT NULL,
  327. amount REAL NOT NULL,
  328. chapter INTEGER NOT NULL,
  329. note TEXT,
  330. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  331. FOREIGN KEY (debt_id) REFERENCES chase_debt(id)
  332. )
  333. """)
  334. # 章节追读力元数据表
  335. cursor.execute("""
  336. CREATE TABLE IF NOT EXISTS chapter_reading_power (
  337. chapter INTEGER PRIMARY KEY,
  338. hook_type TEXT,
  339. hook_strength TEXT DEFAULT 'medium',
  340. coolpoint_patterns TEXT,
  341. micropayoffs TEXT,
  342. hard_violations TEXT,
  343. soft_suggestions TEXT,
  344. is_transition INTEGER DEFAULT 0,
  345. override_count INTEGER DEFAULT 0,
  346. debt_balance REAL DEFAULT 0.0,
  347. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  348. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  349. )
  350. """)
  351. # v5.3 引入索引
  352. cursor.execute(
  353. "CREATE INDEX IF NOT EXISTS idx_override_contracts_chapter ON override_contracts(chapter)"
  354. )
  355. cursor.execute(
  356. "CREATE INDEX IF NOT EXISTS idx_override_contracts_status ON override_contracts(status)"
  357. )
  358. cursor.execute(
  359. "CREATE INDEX IF NOT EXISTS idx_override_contracts_due ON override_contracts(due_chapter)"
  360. )
  361. cursor.execute(
  362. "CREATE INDEX IF NOT EXISTS idx_chase_debt_status ON chase_debt(status)"
  363. )
  364. cursor.execute(
  365. "CREATE INDEX IF NOT EXISTS idx_chase_debt_source ON chase_debt(source_chapter)"
  366. )
  367. cursor.execute(
  368. "CREATE INDEX IF NOT EXISTS idx_chase_debt_due ON chase_debt(due_chapter)"
  369. )
  370. cursor.execute(
  371. "CREATE INDEX IF NOT EXISTS idx_debt_events_debt ON debt_events(debt_id)"
  372. )
  373. cursor.execute(
  374. "CREATE INDEX IF NOT EXISTS idx_debt_events_chapter ON debt_events(chapter)"
  375. )
  376. # ==================== v5.4 新增表:无效事实与日志 ====================
  377. # 无效事实表
  378. cursor.execute("""
  379. CREATE TABLE IF NOT EXISTS invalid_facts (
  380. id INTEGER PRIMARY KEY,
  381. source_type TEXT NOT NULL,
  382. source_id TEXT NOT NULL,
  383. reason TEXT NOT NULL,
  384. status TEXT DEFAULT 'pending',
  385. marked_by TEXT NOT NULL,
  386. marked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  387. confirmed_at TIMESTAMP,
  388. chapter_discovered INTEGER
  389. )
  390. """)
  391. cursor.execute(
  392. "CREATE INDEX IF NOT EXISTS idx_invalid_status ON invalid_facts(status)"
  393. )
  394. cursor.execute(
  395. "CREATE INDEX IF NOT EXISTS idx_invalid_source ON invalid_facts(source_type, source_id)"
  396. )
  397. # 审查指标表
  398. cursor.execute("""
  399. CREATE TABLE IF NOT EXISTS review_metrics (
  400. start_chapter INTEGER NOT NULL,
  401. end_chapter INTEGER NOT NULL,
  402. overall_score REAL DEFAULT 0,
  403. dimension_scores TEXT,
  404. severity_counts TEXT,
  405. critical_issues TEXT,
  406. report_file TEXT,
  407. notes TEXT,
  408. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  409. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  410. PRIMARY KEY (start_chapter, end_chapter)
  411. )
  412. """)
  413. cursor.execute(
  414. "CREATE INDEX IF NOT EXISTS idx_review_metrics_end ON review_metrics(end_chapter)"
  415. )
  416. # RAG 查询日志
  417. cursor.execute("""
  418. CREATE TABLE IF NOT EXISTS rag_query_log (
  419. id INTEGER PRIMARY KEY,
  420. query TEXT,
  421. query_type TEXT,
  422. results_count INTEGER,
  423. hit_sources TEXT,
  424. latency_ms INTEGER,
  425. chapter INTEGER,
  426. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  427. )
  428. """)
  429. cursor.execute(
  430. "CREATE INDEX IF NOT EXISTS idx_rag_query_type ON rag_query_log(query_type)"
  431. )
  432. cursor.execute(
  433. "CREATE INDEX IF NOT EXISTS idx_rag_query_chapter ON rag_query_log(chapter)"
  434. )
  435. # 工具调用统计
  436. cursor.execute("""
  437. CREATE TABLE IF NOT EXISTS tool_call_stats (
  438. id INTEGER PRIMARY KEY,
  439. tool_name TEXT,
  440. success BOOLEAN,
  441. retry_count INTEGER DEFAULT 0,
  442. error_code TEXT,
  443. error_message TEXT,
  444. chapter INTEGER,
  445. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  446. )
  447. """)
  448. cursor.execute(
  449. "CREATE INDEX IF NOT EXISTS idx_tool_stats_name ON tool_call_stats(tool_name)"
  450. )
  451. cursor.execute(
  452. "CREATE INDEX IF NOT EXISTS idx_tool_stats_chapter ON tool_call_stats(chapter)"
  453. )
  454. conn.commit()
  455. @contextmanager
  456. def _get_conn(self):
  457. """获取数据库连接"""
  458. conn = sqlite3.connect(str(self.config.index_db))
  459. conn.row_factory = sqlite3.Row
  460. try:
  461. yield conn
  462. finally:
  463. conn.close()
  464. # ==================== 章节操作 ====================
  465. def add_chapter(self, meta: ChapterMeta):
  466. """添加/更新章节元数据"""
  467. with self._get_conn() as conn:
  468. cursor = conn.cursor()
  469. cursor.execute(
  470. """
  471. INSERT OR REPLACE INTO chapters
  472. (chapter, title, location, word_count, characters, summary)
  473. VALUES (?, ?, ?, ?, ?, ?)
  474. """,
  475. (
  476. meta.chapter,
  477. meta.title,
  478. meta.location,
  479. meta.word_count,
  480. json.dumps(meta.characters, ensure_ascii=False),
  481. meta.summary,
  482. ),
  483. )
  484. conn.commit()
  485. def get_chapter(self, chapter: int) -> Optional[Dict]:
  486. """获取章节元数据"""
  487. with self._get_conn() as conn:
  488. cursor = conn.cursor()
  489. cursor.execute("SELECT * FROM chapters WHERE chapter = ?", (chapter,))
  490. row = cursor.fetchone()
  491. if row:
  492. return self._row_to_dict(row, parse_json=["characters"])
  493. return None
  494. def get_recent_chapters(self, limit: int = None) -> List[Dict]:
  495. """获取最近章节"""
  496. if limit is None:
  497. limit = self.config.query_recent_chapters_limit
  498. with self._get_conn() as conn:
  499. cursor = conn.cursor()
  500. cursor.execute(
  501. """
  502. SELECT * FROM chapters
  503. ORDER BY chapter DESC
  504. LIMIT ?
  505. """,
  506. (limit,),
  507. )
  508. return [
  509. self._row_to_dict(row, parse_json=["characters"])
  510. for row in cursor.fetchall()
  511. ]
  512. # ==================== 场景操作 ====================
  513. def add_scenes(self, chapter: int, scenes: List[SceneMeta]):
  514. """添加章节场景"""
  515. with self._get_conn() as conn:
  516. cursor = conn.cursor()
  517. # 先删除该章节旧场景
  518. cursor.execute("DELETE FROM scenes WHERE chapter = ?", (chapter,))
  519. # 插入新场景
  520. for scene in scenes:
  521. cursor.execute(
  522. """
  523. INSERT INTO scenes
  524. (chapter, scene_index, start_line, end_line, location, summary, characters)
  525. VALUES (?, ?, ?, ?, ?, ?, ?)
  526. """,
  527. (
  528. scene.chapter,
  529. scene.scene_index,
  530. scene.start_line,
  531. scene.end_line,
  532. scene.location,
  533. scene.summary,
  534. json.dumps(scene.characters, ensure_ascii=False),
  535. ),
  536. )
  537. conn.commit()
  538. def get_scenes(self, chapter: int) -> List[Dict]:
  539. """获取章节场景"""
  540. with self._get_conn() as conn:
  541. cursor = conn.cursor()
  542. cursor.execute(
  543. """
  544. SELECT * FROM scenes
  545. WHERE chapter = ?
  546. ORDER BY scene_index
  547. """,
  548. (chapter,),
  549. )
  550. return [
  551. self._row_to_dict(row, parse_json=["characters"])
  552. for row in cursor.fetchall()
  553. ]
  554. def search_scenes_by_location(self, location: str, limit: int = None) -> List[Dict]:
  555. """按地点搜索场景"""
  556. if limit is None:
  557. limit = self.config.query_scenes_by_location_limit
  558. with self._get_conn() as conn:
  559. cursor = conn.cursor()
  560. cursor.execute(
  561. """
  562. SELECT * FROM scenes
  563. WHERE location LIKE ?
  564. ORDER BY chapter DESC
  565. LIMIT ?
  566. """,
  567. (f"%{location}%", limit),
  568. )
  569. return [
  570. self._row_to_dict(row, parse_json=["characters"])
  571. for row in cursor.fetchall()
  572. ]
  573. # ==================== 出场记录操作 ====================
  574. def record_appearance(
  575. self,
  576. entity_id: str,
  577. chapter: int,
  578. mentions: List[str],
  579. confidence: float = 1.0,
  580. skip_if_exists: bool = False,
  581. ):
  582. """记录实体出场
  583. Args:
  584. entity_id: 实体ID
  585. chapter: 章节号
  586. mentions: 提及列表
  587. confidence: 置信度
  588. skip_if_exists: 如果为True,当记录已存在时跳过(避免覆盖已有mentions)
  589. """
  590. with self._get_conn() as conn:
  591. cursor = conn.cursor()
  592. if skip_if_exists:
  593. # 先检查是否已存在
  594. cursor.execute(
  595. "SELECT 1 FROM appearances WHERE entity_id = ? AND chapter = ?",
  596. (entity_id, chapter),
  597. )
  598. if cursor.fetchone():
  599. return # 已存在,跳过
  600. cursor.execute(
  601. """
  602. INSERT OR REPLACE INTO appearances
  603. (entity_id, chapter, mentions, confidence)
  604. VALUES (?, ?, ?, ?)
  605. """,
  606. (
  607. entity_id,
  608. chapter,
  609. json.dumps(mentions, ensure_ascii=False),
  610. confidence,
  611. ),
  612. )
  613. conn.commit()
  614. def get_entity_appearances(self, entity_id: str, limit: int = None) -> List[Dict]:
  615. """获取实体出场记录"""
  616. if limit is None:
  617. limit = self.config.query_entity_appearances_limit
  618. with self._get_conn() as conn:
  619. cursor = conn.cursor()
  620. cursor.execute(
  621. """
  622. SELECT * FROM appearances
  623. WHERE entity_id = ?
  624. ORDER BY chapter DESC
  625. LIMIT ?
  626. """,
  627. (entity_id, limit),
  628. )
  629. return [
  630. self._row_to_dict(row, parse_json=["mentions"])
  631. for row in cursor.fetchall()
  632. ]
  633. def get_recent_appearances(self, limit: int = None) -> List[Dict]:
  634. """获取最近出场的实体"""
  635. if limit is None:
  636. limit = self.config.query_recent_appearances_limit
  637. with self._get_conn() as conn:
  638. cursor = conn.cursor()
  639. cursor.execute(
  640. """
  641. SELECT entity_id, MAX(chapter) as last_chapter, COUNT(*) as total
  642. FROM appearances
  643. GROUP BY entity_id
  644. ORDER BY last_chapter DESC
  645. LIMIT ?
  646. """,
  647. (limit,),
  648. )
  649. return [dict(row) for row in cursor.fetchall()]
  650. def get_chapter_appearances(self, chapter: int) -> List[Dict]:
  651. """获取某章所有出场实体"""
  652. with self._get_conn() as conn:
  653. cursor = conn.cursor()
  654. cursor.execute(
  655. """
  656. SELECT * FROM appearances
  657. WHERE chapter = ?
  658. ORDER BY confidence DESC
  659. """,
  660. (chapter,),
  661. )
  662. return [
  663. self._row_to_dict(row, parse_json=["mentions"])
  664. for row in cursor.fetchall()
  665. ]
  666. # ==================== v5.1 实体操作 ====================
  667. def upsert_entity(self, entity: EntityMeta, update_metadata: bool = False) -> bool:
  668. """
  669. 插入或更新实体 (智能合并)
  670. - 新实体: 直接插入
  671. - 已存在: 更新 current_json, last_appearance, updated_at
  672. - update_metadata=True: 同时更新 canonical_name/tier/desc/is_protagonist/is_archived
  673. 返回是否为新实体
  674. """
  675. with self._get_conn() as conn:
  676. cursor = conn.cursor()
  677. # 检查是否存在
  678. cursor.execute(
  679. "SELECT id, current_json FROM entities WHERE id = ?", (entity.id,)
  680. )
  681. existing = cursor.fetchone()
  682. if existing:
  683. # 已存在: 智能合并 current_json
  684. old_current = {}
  685. if existing["current_json"]:
  686. try:
  687. old_current = json.loads(existing["current_json"])
  688. except json.JSONDecodeError:
  689. pass
  690. # 合并 current (新值覆盖旧值)
  691. merged_current = {**old_current, **entity.current}
  692. if update_metadata:
  693. # 完整更新(包括元数据)
  694. cursor.execute(
  695. """
  696. UPDATE entities SET
  697. canonical_name = ?,
  698. tier = ?,
  699. desc = ?,
  700. current_json = ?,
  701. last_appearance = ?,
  702. is_protagonist = ?,
  703. is_archived = ?,
  704. updated_at = CURRENT_TIMESTAMP
  705. WHERE id = ?
  706. """,
  707. (
  708. entity.canonical_name,
  709. entity.tier,
  710. entity.desc,
  711. json.dumps(merged_current, ensure_ascii=False),
  712. entity.last_appearance,
  713. 1 if entity.is_protagonist else 0,
  714. 1 if entity.is_archived else 0,
  715. entity.id,
  716. ),
  717. )
  718. else:
  719. # 只更新 current 和 last_appearance
  720. cursor.execute(
  721. """
  722. UPDATE entities SET
  723. current_json = ?,
  724. last_appearance = ?,
  725. updated_at = CURRENT_TIMESTAMP
  726. WHERE id = ?
  727. """,
  728. (
  729. json.dumps(merged_current, ensure_ascii=False),
  730. entity.last_appearance,
  731. entity.id,
  732. ),
  733. )
  734. conn.commit()
  735. return False
  736. else:
  737. # 新实体: 插入
  738. cursor.execute(
  739. """
  740. INSERT INTO entities
  741. (id, type, canonical_name, tier, desc, current_json,
  742. first_appearance, last_appearance, is_protagonist, is_archived)
  743. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  744. """,
  745. (
  746. entity.id,
  747. entity.type,
  748. entity.canonical_name,
  749. entity.tier,
  750. entity.desc,
  751. json.dumps(entity.current, ensure_ascii=False),
  752. entity.first_appearance,
  753. entity.last_appearance,
  754. 1 if entity.is_protagonist else 0,
  755. 1 if entity.is_archived else 0,
  756. ),
  757. )
  758. conn.commit()
  759. return True
  760. def get_entity(self, entity_id: str) -> Optional[Dict]:
  761. """获取单个实体"""
  762. with self._get_conn() as conn:
  763. cursor = conn.cursor()
  764. cursor.execute("SELECT * FROM entities WHERE id = ?", (entity_id,))
  765. row = cursor.fetchone()
  766. if row:
  767. return self._row_to_dict(row, parse_json=["current_json"])
  768. return None
  769. def get_entities_by_type(
  770. self, entity_type: str, include_archived: bool = False
  771. ) -> List[Dict]:
  772. """按类型获取实体"""
  773. with self._get_conn() as conn:
  774. cursor = conn.cursor()
  775. if include_archived:
  776. cursor.execute(
  777. """
  778. SELECT * FROM entities WHERE type = ?
  779. ORDER BY last_appearance DESC
  780. """,
  781. (entity_type,),
  782. )
  783. else:
  784. cursor.execute(
  785. """
  786. SELECT * FROM entities WHERE type = ? AND is_archived = 0
  787. ORDER BY last_appearance DESC
  788. """,
  789. (entity_type,),
  790. )
  791. return [
  792. self._row_to_dict(row, parse_json=["current_json"])
  793. for row in cursor.fetchall()
  794. ]
  795. def get_entities_by_tier(self, tier: str) -> List[Dict]:
  796. """按重要度获取实体 (核心/重要/次要/装饰)"""
  797. with self._get_conn() as conn:
  798. cursor = conn.cursor()
  799. cursor.execute(
  800. """
  801. SELECT * FROM entities WHERE tier = ? AND is_archived = 0
  802. ORDER BY last_appearance DESC
  803. """,
  804. (tier,),
  805. )
  806. return [
  807. self._row_to_dict(row, parse_json=["current_json"])
  808. for row in cursor.fetchall()
  809. ]
  810. def get_core_entities(self) -> List[Dict]:
  811. """获取所有核心实体 (用于 Context Agent 全量加载)"""
  812. with self._get_conn() as conn:
  813. cursor = conn.cursor()
  814. cursor.execute("""
  815. SELECT * FROM entities
  816. WHERE (tier IN ('核心', '重要') OR is_protagonist = 1) AND is_archived = 0
  817. ORDER BY is_protagonist DESC, tier, last_appearance DESC
  818. """)
  819. return [
  820. self._row_to_dict(row, parse_json=["current_json"])
  821. for row in cursor.fetchall()
  822. ]
  823. def get_protagonist(self) -> Optional[Dict]:
  824. """获取主角实体"""
  825. with self._get_conn() as conn:
  826. cursor = conn.cursor()
  827. cursor.execute("SELECT * FROM entities WHERE is_protagonist = 1 LIMIT 1")
  828. row = cursor.fetchone()
  829. if row:
  830. return self._row_to_dict(row, parse_json=["current_json"])
  831. return None
  832. def update_entity_current(self, entity_id: str, updates: Dict) -> bool:
  833. """
  834. 增量更新实体的 current 字段 (不覆盖其他字段)
  835. 例如: update_entity_current("xiaoyan", {"realm": "斗师"})
  836. """
  837. with self._get_conn() as conn:
  838. cursor = conn.cursor()
  839. cursor.execute(
  840. "SELECT current_json FROM entities WHERE id = ?", (entity_id,)
  841. )
  842. row = cursor.fetchone()
  843. if not row:
  844. return False
  845. current = {}
  846. if row["current_json"]:
  847. try:
  848. current = json.loads(row["current_json"])
  849. except json.JSONDecodeError:
  850. pass
  851. current.update(updates)
  852. cursor.execute(
  853. """
  854. UPDATE entities SET
  855. current_json = ?,
  856. updated_at = CURRENT_TIMESTAMP
  857. WHERE id = ?
  858. """,
  859. (json.dumps(current, ensure_ascii=False), entity_id),
  860. )
  861. conn.commit()
  862. return True
  863. def archive_entity(self, entity_id: str) -> bool:
  864. """归档实体 (不删除,只是标记)"""
  865. with self._get_conn() as conn:
  866. cursor = conn.cursor()
  867. cursor.execute(
  868. """
  869. UPDATE entities SET is_archived = 1, updated_at = CURRENT_TIMESTAMP
  870. WHERE id = ?
  871. """,
  872. (entity_id,),
  873. )
  874. conn.commit()
  875. return cursor.rowcount > 0
  876. # ==================== v5.1 别名操作 ====================
  877. def register_alias(self, alias: str, entity_id: str, entity_type: str) -> bool:
  878. """
  879. 注册别名 (支持一对多)
  880. 同一别名可映射多个实体 (如 "天云宗" → 地点 + 势力)
  881. """
  882. with self._get_conn() as conn:
  883. cursor = conn.cursor()
  884. try:
  885. cursor.execute(
  886. """
  887. INSERT OR IGNORE INTO aliases (alias, entity_id, entity_type)
  888. VALUES (?, ?, ?)
  889. """,
  890. (alias, entity_id, entity_type),
  891. )
  892. conn.commit()
  893. return cursor.rowcount > 0
  894. except sqlite3.IntegrityError:
  895. return False
  896. def get_entities_by_alias(self, alias: str) -> List[Dict]:
  897. """
  898. 根据别名查找实体 (一对多)
  899. 返回所有匹配的实体 (可能有多个不同类型)
  900. """
  901. with self._get_conn() as conn:
  902. cursor = conn.cursor()
  903. cursor.execute(
  904. """
  905. SELECT e.*, a.entity_type as alias_type
  906. FROM entities e
  907. JOIN aliases a ON e.id = a.entity_id
  908. WHERE a.alias = ?
  909. """,
  910. (alias,),
  911. )
  912. return [
  913. self._row_to_dict(row, parse_json=["current_json"])
  914. for row in cursor.fetchall()
  915. ]
  916. def get_entity_aliases(self, entity_id: str) -> List[str]:
  917. """获取实体的所有别名"""
  918. with self._get_conn() as conn:
  919. cursor = conn.cursor()
  920. cursor.execute(
  921. "SELECT alias FROM aliases WHERE entity_id = ?", (entity_id,)
  922. )
  923. return [row["alias"] for row in cursor.fetchall()]
  924. def remove_alias(self, alias: str, entity_id: str) -> bool:
  925. """移除别名"""
  926. with self._get_conn() as conn:
  927. cursor = conn.cursor()
  928. cursor.execute(
  929. "DELETE FROM aliases WHERE alias = ? AND entity_id = ?",
  930. (alias, entity_id),
  931. )
  932. conn.commit()
  933. return cursor.rowcount > 0
  934. # ==================== v5.1 状态变化操作 ====================
  935. def record_state_change(self, change: StateChangeMeta) -> int:
  936. """
  937. 记录状态变化
  938. 返回记录 ID
  939. """
  940. with self._get_conn() as conn:
  941. cursor = conn.cursor()
  942. cursor.execute(
  943. """
  944. INSERT INTO state_changes
  945. (entity_id, field, old_value, new_value, reason, chapter)
  946. VALUES (?, ?, ?, ?, ?, ?)
  947. """,
  948. (
  949. change.entity_id,
  950. change.field,
  951. change.old_value,
  952. change.new_value,
  953. change.reason,
  954. change.chapter,
  955. ),
  956. )
  957. conn.commit()
  958. return cursor.lastrowid
  959. def get_entity_state_changes(self, entity_id: str, limit: int = 20) -> List[Dict]:
  960. """获取实体的状态变化历史"""
  961. with self._get_conn() as conn:
  962. cursor = conn.cursor()
  963. cursor.execute(
  964. """
  965. SELECT * FROM state_changes
  966. WHERE entity_id = ?
  967. ORDER BY chapter DESC, id DESC
  968. LIMIT ?
  969. """,
  970. (entity_id, limit),
  971. )
  972. return [dict(row) for row in cursor.fetchall()]
  973. def get_recent_state_changes(self, limit: int = 50) -> List[Dict]:
  974. """获取最近的状态变化"""
  975. with self._get_conn() as conn:
  976. cursor = conn.cursor()
  977. cursor.execute(
  978. """
  979. SELECT * FROM state_changes
  980. ORDER BY chapter DESC, id DESC
  981. LIMIT ?
  982. """,
  983. (limit,),
  984. )
  985. return [dict(row) for row in cursor.fetchall()]
  986. def get_chapter_state_changes(self, chapter: int) -> List[Dict]:
  987. """获取某章的所有状态变化"""
  988. with self._get_conn() as conn:
  989. cursor = conn.cursor()
  990. cursor.execute(
  991. """
  992. SELECT * FROM state_changes
  993. WHERE chapter = ?
  994. ORDER BY id
  995. """,
  996. (chapter,),
  997. )
  998. return [dict(row) for row in cursor.fetchall()]
  999. # ==================== v5.1 关系操作 ====================
  1000. def upsert_relationship(self, rel: RelationshipMeta) -> bool:
  1001. """
  1002. 插入或更新关系
  1003. 相同 (from, to, type) 会更新 description 和 chapter
  1004. 返回是否为新关系
  1005. """
  1006. with self._get_conn() as conn:
  1007. cursor = conn.cursor()
  1008. # 检查是否存在
  1009. cursor.execute(
  1010. """
  1011. SELECT id FROM relationships
  1012. WHERE from_entity = ? AND to_entity = ? AND type = ?
  1013. """,
  1014. (rel.from_entity, rel.to_entity, rel.type),
  1015. )
  1016. existing = cursor.fetchone()
  1017. if existing:
  1018. cursor.execute(
  1019. """
  1020. UPDATE relationships SET
  1021. description = ?,
  1022. chapter = ?
  1023. WHERE id = ?
  1024. """,
  1025. (rel.description, rel.chapter, existing["id"]),
  1026. )
  1027. conn.commit()
  1028. return False
  1029. else:
  1030. cursor.execute(
  1031. """
  1032. INSERT INTO relationships
  1033. (from_entity, to_entity, type, description, chapter)
  1034. VALUES (?, ?, ?, ?, ?)
  1035. """,
  1036. (
  1037. rel.from_entity,
  1038. rel.to_entity,
  1039. rel.type,
  1040. rel.description,
  1041. rel.chapter,
  1042. ),
  1043. )
  1044. conn.commit()
  1045. return True
  1046. def get_entity_relationships(
  1047. self, entity_id: str, direction: str = "both"
  1048. ) -> List[Dict]:
  1049. """
  1050. 获取实体的关系
  1051. direction: "from" | "to" | "both"
  1052. """
  1053. with self._get_conn() as conn:
  1054. cursor = conn.cursor()
  1055. if direction == "from":
  1056. cursor.execute(
  1057. """
  1058. SELECT * FROM relationships WHERE from_entity = ?
  1059. ORDER BY chapter DESC
  1060. """,
  1061. (entity_id,),
  1062. )
  1063. elif direction == "to":
  1064. cursor.execute(
  1065. """
  1066. SELECT * FROM relationships WHERE to_entity = ?
  1067. ORDER BY chapter DESC
  1068. """,
  1069. (entity_id,),
  1070. )
  1071. else: # both
  1072. cursor.execute(
  1073. """
  1074. SELECT * FROM relationships
  1075. WHERE from_entity = ? OR to_entity = ?
  1076. ORDER BY chapter DESC
  1077. """,
  1078. (entity_id, entity_id),
  1079. )
  1080. return [dict(row) for row in cursor.fetchall()]
  1081. def get_relationship_between(self, entity1: str, entity2: str) -> List[Dict]:
  1082. """获取两个实体之间的所有关系"""
  1083. with self._get_conn() as conn:
  1084. cursor = conn.cursor()
  1085. cursor.execute(
  1086. """
  1087. SELECT * FROM relationships
  1088. WHERE (from_entity = ? AND to_entity = ?)
  1089. OR (from_entity = ? AND to_entity = ?)
  1090. ORDER BY chapter DESC
  1091. """,
  1092. (entity1, entity2, entity2, entity1),
  1093. )
  1094. return [dict(row) for row in cursor.fetchall()]
  1095. def get_recent_relationships(self, limit: int = 30) -> List[Dict]:
  1096. """获取最近建立的关系"""
  1097. with self._get_conn() as conn:
  1098. cursor = conn.cursor()
  1099. cursor.execute(
  1100. """
  1101. SELECT * FROM relationships
  1102. ORDER BY chapter DESC, id DESC
  1103. LIMIT ?
  1104. """,
  1105. (limit,),
  1106. )
  1107. return [dict(row) for row in cursor.fetchall()]
  1108. # ==================== v5.3 Override Contract 操作 ====================
  1109. def create_override_contract(self, contract: OverrideContractMeta) -> int:
  1110. """
  1111. 创建或更新 Override Contract
  1112. 使用 SQLite 的 INSERT ... ON CONFLICT ... DO UPDATE 实现原子 UPSERT:
  1113. - 并发安全,无需显式锁
  1114. - 保持 id 不变,避免 chase_debt.override_contract_id 悬挂
  1115. - 完全冻结终态:已 fulfilled/cancelled 的合约所有字段都不会被修改
  1116. 兼容性:支持 SQLite 3.24+(ON CONFLICT 语法),不依赖 RETURNING(3.35+)
  1117. 返回合约 ID
  1118. """
  1119. with self._get_conn() as conn:
  1120. cursor = conn.cursor()
  1121. # 使用 ON CONFLICT 实现原子 UPSERT(SQLite 3.24+)
  1122. # 终态完全冻结:fulfilled/cancelled 状态下所有字段都保持不变
  1123. cursor.execute(
  1124. """
  1125. INSERT INTO override_contracts
  1126. (chapter, constraint_type, constraint_id, rationale_type,
  1127. rationale_text, payback_plan, due_chapter, status)
  1128. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  1129. ON CONFLICT(chapter, constraint_type, constraint_id) DO UPDATE SET
  1130. rationale_type = CASE
  1131. WHEN override_contracts.status IN ('fulfilled', 'cancelled')
  1132. THEN override_contracts.rationale_type
  1133. ELSE excluded.rationale_type
  1134. END,
  1135. rationale_text = CASE
  1136. WHEN override_contracts.status IN ('fulfilled', 'cancelled')
  1137. THEN override_contracts.rationale_text
  1138. ELSE excluded.rationale_text
  1139. END,
  1140. payback_plan = CASE
  1141. WHEN override_contracts.status IN ('fulfilled', 'cancelled')
  1142. THEN override_contracts.payback_plan
  1143. ELSE excluded.payback_plan
  1144. END,
  1145. due_chapter = CASE
  1146. WHEN override_contracts.status IN ('fulfilled', 'cancelled')
  1147. THEN override_contracts.due_chapter
  1148. ELSE excluded.due_chapter
  1149. END,
  1150. status = CASE
  1151. WHEN override_contracts.status IN ('fulfilled', 'cancelled')
  1152. THEN override_contracts.status
  1153. ELSE excluded.status
  1154. END
  1155. """,
  1156. (
  1157. contract.chapter,
  1158. contract.constraint_type,
  1159. contract.constraint_id,
  1160. contract.rationale_type,
  1161. contract.rationale_text,
  1162. contract.payback_plan,
  1163. contract.due_chapter,
  1164. contract.status,
  1165. ),
  1166. )
  1167. # 不使用 RETURNING(需要 SQLite 3.35+),改用查询获取 id
  1168. cursor.execute(
  1169. """
  1170. SELECT id FROM override_contracts
  1171. WHERE chapter = ? AND constraint_type = ? AND constraint_id = ?
  1172. """,
  1173. (contract.chapter, contract.constraint_type, contract.constraint_id),
  1174. )
  1175. row = cursor.fetchone()
  1176. if not row:
  1177. # UPSERT 后查不到记录是异常情况,不应发生
  1178. raise RuntimeError(
  1179. f"Override Contract UPSERT 后无法获取 id: "
  1180. f"chapter={contract.chapter}, type={contract.constraint_type}, "
  1181. f"id={contract.constraint_id}"
  1182. )
  1183. contract_id = row[0]
  1184. conn.commit()
  1185. return contract_id
  1186. def get_pending_overrides(self, before_chapter: int = None) -> List[Dict]:
  1187. """获取待偿还的Override Contracts"""
  1188. with self._get_conn() as conn:
  1189. cursor = conn.cursor()
  1190. if before_chapter:
  1191. cursor.execute(
  1192. """
  1193. SELECT * FROM override_contracts
  1194. WHERE status = 'pending' AND due_chapter <= ?
  1195. ORDER BY due_chapter ASC
  1196. """,
  1197. (before_chapter,),
  1198. )
  1199. else:
  1200. cursor.execute("""
  1201. SELECT * FROM override_contracts
  1202. WHERE status = 'pending'
  1203. ORDER BY due_chapter ASC
  1204. """)
  1205. return [dict(row) for row in cursor.fetchall()]
  1206. def get_overdue_overrides(self, current_chapter: int) -> List[Dict]:
  1207. """获取已逾期的Override Contracts"""
  1208. with self._get_conn() as conn:
  1209. cursor = conn.cursor()
  1210. cursor.execute(
  1211. """
  1212. SELECT * FROM override_contracts
  1213. WHERE status = 'pending' AND due_chapter < ?
  1214. ORDER BY due_chapter ASC
  1215. """,
  1216. (current_chapter,),
  1217. )
  1218. return [dict(row) for row in cursor.fetchall()]
  1219. def fulfill_override(self, contract_id: int) -> bool:
  1220. """标记Override Contract为已偿还"""
  1221. with self._get_conn() as conn:
  1222. cursor = conn.cursor()
  1223. cursor.execute(
  1224. """
  1225. UPDATE override_contracts SET
  1226. status = 'fulfilled',
  1227. fulfilled_at = CURRENT_TIMESTAMP
  1228. WHERE id = ?
  1229. """,
  1230. (contract_id,),
  1231. )
  1232. conn.commit()
  1233. return cursor.rowcount > 0
  1234. def get_chapter_overrides(self, chapter: int) -> List[Dict]:
  1235. """获取某章创建的Override Contracts"""
  1236. with self._get_conn() as conn:
  1237. cursor = conn.cursor()
  1238. cursor.execute(
  1239. """
  1240. SELECT * FROM override_contracts WHERE chapter = ?
  1241. """,
  1242. (chapter,),
  1243. )
  1244. return [dict(row) for row in cursor.fetchall()]
  1245. # ==================== v5.3 追读力债务操作 ====================
  1246. def create_debt(self, debt: ChaseDebtMeta) -> int:
  1247. """
  1248. 创建追读力债务
  1249. 返回债务 ID
  1250. """
  1251. with self._get_conn() as conn:
  1252. cursor = conn.cursor()
  1253. cursor.execute(
  1254. """
  1255. INSERT INTO chase_debt
  1256. (debt_type, original_amount, current_amount, interest_rate,
  1257. source_chapter, due_chapter, override_contract_id, status)
  1258. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  1259. """,
  1260. (
  1261. debt.debt_type,
  1262. debt.original_amount,
  1263. debt.current_amount,
  1264. debt.interest_rate,
  1265. debt.source_chapter,
  1266. debt.due_chapter,
  1267. debt.override_contract_id if debt.override_contract_id else None,
  1268. debt.status,
  1269. ),
  1270. )
  1271. conn.commit()
  1272. debt_id = cursor.lastrowid
  1273. # 记录创建事件
  1274. self._record_debt_event(
  1275. cursor,
  1276. debt_id,
  1277. "created",
  1278. debt.original_amount,
  1279. debt.source_chapter,
  1280. f"创建债务: {debt.debt_type}",
  1281. )
  1282. conn.commit()
  1283. return debt_id
  1284. def get_active_debts(self) -> List[Dict]:
  1285. """获取所有活跃债务"""
  1286. with self._get_conn() as conn:
  1287. cursor = conn.cursor()
  1288. cursor.execute("""
  1289. SELECT * FROM chase_debt
  1290. WHERE status = 'active'
  1291. ORDER BY due_chapter ASC
  1292. """)
  1293. return [dict(row) for row in cursor.fetchall()]
  1294. def get_overdue_debts(self, current_chapter: int) -> List[Dict]:
  1295. """获取已逾期的债务(包括 active 但已过期的,以及已标记为 overdue 的)"""
  1296. with self._get_conn() as conn:
  1297. cursor = conn.cursor()
  1298. cursor.execute(
  1299. """
  1300. SELECT * FROM chase_debt
  1301. WHERE (status = 'overdue')
  1302. OR (status = 'active' AND due_chapter < ?)
  1303. ORDER BY due_chapter ASC
  1304. """,
  1305. (current_chapter,),
  1306. )
  1307. return [dict(row) for row in cursor.fetchall()]
  1308. def get_total_debt_balance(self) -> float:
  1309. """获取总债务余额(包括 active 和 overdue)"""
  1310. with self._get_conn() as conn:
  1311. cursor = conn.cursor()
  1312. cursor.execute("""
  1313. SELECT COALESCE(SUM(current_amount), 0) FROM chase_debt
  1314. WHERE status IN ('active', 'overdue')
  1315. """)
  1316. return cursor.fetchone()[0]
  1317. def accrue_interest(self, current_chapter: int) -> Dict[str, Any]:
  1318. """
  1319. 计算利息(每章调用一次)
  1320. - 对 active 和 overdue 债务都计息(逾期债务继续累积利息)
  1321. - 使用 debt_events 表防止同一章重复计息
  1322. - 检查逾期并更新状态
  1323. 返回: {debts_processed, total_interest, new_overdues, skipped_already_processed}
  1324. """
  1325. result = {
  1326. "debts_processed": 0,
  1327. "total_interest": 0.0,
  1328. "new_overdues": 0,
  1329. "skipped_already_processed": 0,
  1330. }
  1331. with self._get_conn() as conn:
  1332. cursor = conn.cursor()
  1333. # 获取所有未偿还债务(active + overdue 都继续计息)
  1334. cursor.execute("""
  1335. SELECT * FROM chase_debt WHERE status IN ('active', 'overdue')
  1336. """)
  1337. debts = cursor.fetchall()
  1338. for debt in debts:
  1339. debt_id = debt["id"]
  1340. current_amount = debt["current_amount"]
  1341. interest_rate = debt["interest_rate"]
  1342. due_chapter = debt["due_chapter"]
  1343. debt_status = debt["status"]
  1344. # 检查本章是否已计息(防止重复调用)
  1345. cursor.execute(
  1346. """
  1347. SELECT 1 FROM debt_events
  1348. WHERE debt_id = ? AND chapter = ? AND event_type = 'interest_accrued'
  1349. """,
  1350. (debt_id, current_chapter),
  1351. )
  1352. if cursor.fetchone():
  1353. result["skipped_already_processed"] += 1
  1354. continue
  1355. # 计算利息
  1356. interest = current_amount * interest_rate
  1357. new_amount = current_amount + interest
  1358. # 更新债务
  1359. cursor.execute(
  1360. """
  1361. UPDATE chase_debt SET
  1362. current_amount = ?,
  1363. updated_at = CURRENT_TIMESTAMP
  1364. WHERE id = ?
  1365. """,
  1366. (new_amount, debt_id),
  1367. )
  1368. # 记录利息事件
  1369. self._record_debt_event(
  1370. cursor,
  1371. debt_id,
  1372. "interest_accrued",
  1373. interest,
  1374. current_chapter,
  1375. f"利息: {interest:.2f} (利率: {interest_rate * 100:.0f}%)",
  1376. )
  1377. result["debts_processed"] += 1
  1378. result["total_interest"] += interest
  1379. # 检查是否逾期(仅对 active 状态的债务)
  1380. if debt_status == "active" and current_chapter > due_chapter:
  1381. cursor.execute(
  1382. """
  1383. UPDATE chase_debt SET status = 'overdue'
  1384. WHERE id = ? AND status = 'active'
  1385. """,
  1386. (debt_id,),
  1387. )
  1388. if cursor.rowcount > 0:
  1389. result["new_overdues"] += 1
  1390. self._record_debt_event(
  1391. cursor,
  1392. debt_id,
  1393. "overdue",
  1394. new_amount,
  1395. current_chapter,
  1396. f"债务逾期 (截止: 第{due_chapter}章)",
  1397. )
  1398. conn.commit()
  1399. return result
  1400. def pay_debt(self, debt_id: int, amount: float, chapter: int) -> Dict[str, Any]:
  1401. """
  1402. 偿还债务
  1403. - 校验 amount > 0
  1404. - 完全偿还时,使用原子 UPDATE 检查并标记关联 Override 为 fulfilled
  1405. (并发安全:用 NOT EXISTS 子查询确保所有债务都已清零)
  1406. 返回: {remaining, fully_paid, override_fulfilled}
  1407. """
  1408. # 校验偿还金额
  1409. if amount <= 0:
  1410. return {
  1411. "remaining": 0,
  1412. "fully_paid": False,
  1413. "error": "偿还金额必须大于0",
  1414. }
  1415. with self._get_conn() as conn:
  1416. cursor = conn.cursor()
  1417. cursor.execute(
  1418. "SELECT current_amount, override_contract_id FROM chase_debt WHERE id = ?",
  1419. (debt_id,),
  1420. )
  1421. row = cursor.fetchone()
  1422. if not row:
  1423. return {"remaining": 0, "fully_paid": False, "error": "债务不存在"}
  1424. current = row["current_amount"]
  1425. override_contract_id = row["override_contract_id"]
  1426. remaining = max(0, current - amount)
  1427. override_fulfilled = False
  1428. if remaining == 0:
  1429. # 完全偿还
  1430. cursor.execute(
  1431. """
  1432. UPDATE chase_debt SET
  1433. current_amount = 0,
  1434. status = 'paid',
  1435. updated_at = CURRENT_TIMESTAMP
  1436. WHERE id = ?
  1437. """,
  1438. (debt_id,),
  1439. )
  1440. self._record_debt_event(
  1441. cursor, debt_id, "full_payment", amount, chapter, "债务已完全偿还"
  1442. )
  1443. # 原子检查并标记 Override 为 fulfilled
  1444. # 使用 NOT EXISTS 子查询确保并发安全:只有当确实没有未清债务时才更新
  1445. if override_contract_id:
  1446. cursor.execute(
  1447. """
  1448. UPDATE override_contracts SET
  1449. status = 'fulfilled',
  1450. fulfilled_at = CURRENT_TIMESTAMP
  1451. WHERE id = ?
  1452. AND status = 'pending'
  1453. AND NOT EXISTS (
  1454. SELECT 1 FROM chase_debt
  1455. WHERE override_contract_id = ?
  1456. AND status IN ('active', 'overdue')
  1457. )
  1458. """,
  1459. (override_contract_id, override_contract_id),
  1460. )
  1461. if cursor.rowcount > 0:
  1462. override_fulfilled = True
  1463. else:
  1464. # 部分偿还
  1465. cursor.execute(
  1466. """
  1467. UPDATE chase_debt SET
  1468. current_amount = ?,
  1469. updated_at = CURRENT_TIMESTAMP
  1470. WHERE id = ?
  1471. """,
  1472. (remaining, debt_id),
  1473. )
  1474. self._record_debt_event(
  1475. cursor,
  1476. debt_id,
  1477. "partial_payment",
  1478. amount,
  1479. chapter,
  1480. f"部分偿还,剩余: {remaining:.2f}",
  1481. )
  1482. conn.commit()
  1483. return {
  1484. "remaining": remaining,
  1485. "fully_paid": remaining == 0,
  1486. "override_fulfilled": override_fulfilled,
  1487. }
  1488. def _record_debt_event(
  1489. self,
  1490. cursor,
  1491. debt_id: int,
  1492. event_type: str,
  1493. amount: float,
  1494. chapter: int,
  1495. note: str = "",
  1496. ):
  1497. """记录债务事件(内部方法)"""
  1498. cursor.execute(
  1499. """
  1500. INSERT INTO debt_events (debt_id, event_type, amount, chapter, note)
  1501. VALUES (?, ?, ?, ?, ?)
  1502. """,
  1503. (debt_id, event_type, amount, chapter, note),
  1504. )
  1505. def get_debt_history(self, debt_id: int) -> List[Dict]:
  1506. """获取债务的事件历史"""
  1507. with self._get_conn() as conn:
  1508. cursor = conn.cursor()
  1509. cursor.execute(
  1510. """
  1511. SELECT * FROM debt_events
  1512. WHERE debt_id = ?
  1513. ORDER BY created_at ASC
  1514. """,
  1515. (debt_id,),
  1516. )
  1517. return [dict(row) for row in cursor.fetchall()]
  1518. # ==================== v5.3 章节追读力元数据操作 ====================
  1519. def save_chapter_reading_power(self, meta: ChapterReadingPowerMeta):
  1520. """保存章节追读力元数据"""
  1521. with self._get_conn() as conn:
  1522. cursor = conn.cursor()
  1523. cursor.execute(
  1524. """
  1525. INSERT OR REPLACE INTO chapter_reading_power
  1526. (chapter, hook_type, hook_strength, coolpoint_patterns,
  1527. micropayoffs, hard_violations, soft_suggestions,
  1528. is_transition, override_count, debt_balance)
  1529. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1530. """,
  1531. (
  1532. meta.chapter,
  1533. meta.hook_type,
  1534. meta.hook_strength,
  1535. json.dumps(meta.coolpoint_patterns, ensure_ascii=False),
  1536. json.dumps(meta.micropayoffs, ensure_ascii=False),
  1537. json.dumps(meta.hard_violations, ensure_ascii=False),
  1538. json.dumps(meta.soft_suggestions, ensure_ascii=False),
  1539. 1 if meta.is_transition else 0,
  1540. meta.override_count,
  1541. meta.debt_balance,
  1542. ),
  1543. )
  1544. conn.commit()
  1545. def get_chapter_reading_power(self, chapter: int) -> Optional[Dict]:
  1546. """获取章节追读力元数据"""
  1547. with self._get_conn() as conn:
  1548. cursor = conn.cursor()
  1549. cursor.execute(
  1550. "SELECT * FROM chapter_reading_power WHERE chapter = ?", (chapter,)
  1551. )
  1552. row = cursor.fetchone()
  1553. if row:
  1554. return self._row_to_dict(
  1555. row,
  1556. parse_json=[
  1557. "coolpoint_patterns",
  1558. "micropayoffs",
  1559. "hard_violations",
  1560. "soft_suggestions",
  1561. ],
  1562. )
  1563. return None
  1564. def get_recent_reading_power(self, limit: int = 10) -> List[Dict]:
  1565. """获取最近章节的追读力元数据"""
  1566. with self._get_conn() as conn:
  1567. cursor = conn.cursor()
  1568. cursor.execute(
  1569. """
  1570. SELECT * FROM chapter_reading_power
  1571. ORDER BY chapter DESC
  1572. LIMIT ?
  1573. """,
  1574. (limit,),
  1575. )
  1576. return [
  1577. self._row_to_dict(
  1578. row,
  1579. parse_json=[
  1580. "coolpoint_patterns",
  1581. "micropayoffs",
  1582. "hard_violations",
  1583. "soft_suggestions",
  1584. ],
  1585. )
  1586. for row in cursor.fetchall()
  1587. ]
  1588. def get_pattern_usage_stats(self, last_n_chapters: int = 20) -> Dict[str, int]:
  1589. """获取最近N章的爽点模式使用统计"""
  1590. with self._get_conn() as conn:
  1591. cursor = conn.cursor()
  1592. cursor.execute(
  1593. """
  1594. SELECT coolpoint_patterns FROM chapter_reading_power
  1595. ORDER BY chapter DESC
  1596. LIMIT ?
  1597. """,
  1598. (last_n_chapters,),
  1599. )
  1600. stats = {}
  1601. for row in cursor.fetchall():
  1602. if row["coolpoint_patterns"]:
  1603. try:
  1604. patterns = json.loads(row["coolpoint_patterns"])
  1605. for p in patterns:
  1606. stats[p] = stats.get(p, 0) + 1
  1607. except json.JSONDecodeError:
  1608. pass
  1609. return stats
  1610. def get_hook_type_stats(self, last_n_chapters: int = 20) -> Dict[str, int]:
  1611. """获取最近N章的钩子类型使用统计"""
  1612. with self._get_conn() as conn:
  1613. cursor = conn.cursor()
  1614. cursor.execute(
  1615. """
  1616. SELECT hook_type FROM chapter_reading_power
  1617. WHERE hook_type IS NOT NULL AND hook_type != ''
  1618. ORDER BY chapter DESC
  1619. LIMIT ?
  1620. """,
  1621. (last_n_chapters,),
  1622. )
  1623. stats = {}
  1624. for row in cursor.fetchall():
  1625. hook = row["hook_type"]
  1626. stats[hook] = stats.get(hook, 0) + 1
  1627. return stats
  1628. # ==================== v5.4 审查指标 ====================
  1629. def save_review_metrics(self, metrics: ReviewMetrics) -> None:
  1630. """保存审查指标记录"""
  1631. with self._get_conn() as conn:
  1632. cursor = conn.cursor()
  1633. cursor.execute(
  1634. """
  1635. INSERT INTO review_metrics
  1636. (start_chapter, end_chapter, overall_score, dimension_scores,
  1637. severity_counts, critical_issues, report_file, notes, created_at, updated_at)
  1638. VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
  1639. ON CONFLICT(start_chapter, end_chapter)
  1640. DO UPDATE SET
  1641. overall_score = excluded.overall_score,
  1642. dimension_scores = excluded.dimension_scores,
  1643. severity_counts = excluded.severity_counts,
  1644. critical_issues = excluded.critical_issues,
  1645. report_file = excluded.report_file,
  1646. notes = excluded.notes,
  1647. updated_at = CURRENT_TIMESTAMP
  1648. """,
  1649. (
  1650. metrics.start_chapter,
  1651. metrics.end_chapter,
  1652. metrics.overall_score,
  1653. json.dumps(metrics.dimension_scores, ensure_ascii=False),
  1654. json.dumps(metrics.severity_counts, ensure_ascii=False),
  1655. json.dumps(metrics.critical_issues, ensure_ascii=False),
  1656. metrics.report_file,
  1657. metrics.notes,
  1658. ),
  1659. )
  1660. conn.commit()
  1661. def get_recent_review_metrics(self, limit: int = 5) -> List[Dict]:
  1662. """获取最近审查记录"""
  1663. with self._get_conn() as conn:
  1664. cursor = conn.cursor()
  1665. cursor.execute(
  1666. """
  1667. SELECT * FROM review_metrics
  1668. ORDER BY end_chapter DESC, start_chapter DESC
  1669. LIMIT ?
  1670. """,
  1671. (limit,),
  1672. )
  1673. return [
  1674. self._row_to_dict(
  1675. row,
  1676. parse_json=["dimension_scores", "severity_counts", "critical_issues"],
  1677. )
  1678. for row in cursor.fetchall()
  1679. ]
  1680. def get_review_trend_stats(self, last_n: int = 5) -> Dict[str, Any]:
  1681. """获取审查趋势统计"""
  1682. records = self.get_recent_review_metrics(last_n)
  1683. if not records:
  1684. return {
  1685. "count": 0,
  1686. "overall_avg": 0.0,
  1687. "dimension_avg": {},
  1688. "severity_totals": {},
  1689. "recent_ranges": [],
  1690. }
  1691. overall_scores: List[float] = []
  1692. dimension_totals: Dict[str, float] = {}
  1693. dimension_counts: Dict[str, int] = {}
  1694. severity_totals: Dict[str, int] = {}
  1695. for record in records:
  1696. score = record.get("overall_score")
  1697. if score is not None:
  1698. try:
  1699. overall_scores.append(float(score))
  1700. except (TypeError, ValueError):
  1701. pass
  1702. dimensions = record.get("dimension_scores") or {}
  1703. if isinstance(dimensions, dict):
  1704. for key, value in dimensions.items():
  1705. try:
  1706. val = float(value)
  1707. except (TypeError, ValueError):
  1708. continue
  1709. dimension_totals[key] = dimension_totals.get(key, 0.0) + val
  1710. dimension_counts[key] = dimension_counts.get(key, 0) + 1
  1711. severities = record.get("severity_counts") or {}
  1712. if isinstance(severities, dict):
  1713. for key, value in severities.items():
  1714. try:
  1715. count = int(value)
  1716. except (TypeError, ValueError):
  1717. continue
  1718. severity_totals[key] = severity_totals.get(key, 0) + count
  1719. overall_avg = round(sum(overall_scores) / len(overall_scores), 2) if overall_scores else 0.0
  1720. dimension_avg = {
  1721. key: round(dimension_totals[key] / dimension_counts[key], 2)
  1722. for key in dimension_totals
  1723. if dimension_counts.get(key, 0) > 0
  1724. }
  1725. recent_ranges = [
  1726. {
  1727. "start_chapter": record.get("start_chapter"),
  1728. "end_chapter": record.get("end_chapter"),
  1729. "overall_score": record.get("overall_score", 0),
  1730. }
  1731. for record in records
  1732. ]
  1733. return {
  1734. "count": len(records),
  1735. "overall_avg": overall_avg,
  1736. "dimension_avg": dimension_avg,
  1737. "severity_totals": severity_totals,
  1738. "recent_ranges": recent_ranges,
  1739. }
  1740. def get_debt_summary(self) -> Dict[str, Any]:
  1741. """获取债务汇总信息"""
  1742. with self._get_conn() as conn:
  1743. cursor = conn.cursor()
  1744. # 活跃债务
  1745. cursor.execute("""
  1746. SELECT COUNT(*) as count, COALESCE(SUM(current_amount), 0) as total
  1747. FROM chase_debt WHERE status = 'active'
  1748. """)
  1749. active = cursor.fetchone()
  1750. # 逾期债务
  1751. cursor.execute("""
  1752. SELECT COUNT(*) as count, COALESCE(SUM(current_amount), 0) as total
  1753. FROM chase_debt WHERE status = 'overdue'
  1754. """)
  1755. overdue = cursor.fetchone()
  1756. # 待偿还Override
  1757. cursor.execute("""
  1758. SELECT COUNT(*) FROM override_contracts WHERE status = 'pending'
  1759. """)
  1760. pending_overrides = cursor.fetchone()[0]
  1761. return {
  1762. "active_debts": active["count"],
  1763. "active_total": active["total"],
  1764. "overdue_debts": overdue["count"],
  1765. "overdue_total": overdue["total"],
  1766. "pending_overrides": pending_overrides,
  1767. "total_balance": active["total"] + overdue["total"],
  1768. }
  1769. # ==================== 批量操作 ====================
  1770. def process_chapter_data(
  1771. self,
  1772. chapter: int,
  1773. title: str,
  1774. location: str,
  1775. word_count: int,
  1776. entities: List[Dict],
  1777. scenes: List[Dict],
  1778. ) -> Dict[str, int]:
  1779. """
  1780. 处理章节数据,批量写入索引
  1781. 返回写入统计
  1782. """
  1783. stats = {"chapters": 0, "scenes": 0, "appearances": 0}
  1784. # 提取出场角色
  1785. characters = [e.get("id") for e in entities if e.get("type") == "角色"]
  1786. # 写入章节元数据
  1787. self.add_chapter(
  1788. ChapterMeta(
  1789. chapter=chapter,
  1790. title=title,
  1791. location=location,
  1792. word_count=word_count,
  1793. characters=characters,
  1794. summary="", # 可后续由 Data Agent 生成
  1795. )
  1796. )
  1797. stats["chapters"] = 1
  1798. # 写入场景
  1799. scene_metas = []
  1800. for s in scenes:
  1801. scene_metas.append(
  1802. SceneMeta(
  1803. chapter=chapter,
  1804. scene_index=s.get("index", 0),
  1805. start_line=s.get("start_line", 0),
  1806. end_line=s.get("end_line", 0),
  1807. location=s.get("location", ""),
  1808. summary=s.get("summary", ""),
  1809. characters=s.get("characters", []),
  1810. )
  1811. )
  1812. self.add_scenes(chapter, scene_metas)
  1813. stats["scenes"] = len(scene_metas)
  1814. # 写入出场记录
  1815. for entity in entities:
  1816. entity_id = entity.get("id")
  1817. if entity_id and entity_id != "NEW":
  1818. self.record_appearance(
  1819. entity_id=entity_id,
  1820. chapter=chapter,
  1821. mentions=entity.get("mentions", []),
  1822. confidence=entity.get("confidence", 1.0),
  1823. )
  1824. stats["appearances"] += 1
  1825. return stats
  1826. # ==================== 辅助方法 ====================
  1827. def _row_to_dict(self, row: sqlite3.Row, parse_json: List[str] = None) -> Dict:
  1828. """将 Row 转换为字典"""
  1829. d = dict(row)
  1830. if parse_json:
  1831. for key in parse_json:
  1832. if key in d and d[key]:
  1833. try:
  1834. d[key] = json.loads(d[key])
  1835. except json.JSONDecodeError:
  1836. pass
  1837. return d
  1838. # ==================== 无效事实管理 ====================
  1839. def mark_invalid_fact(
  1840. self,
  1841. source_type: str,
  1842. source_id: str,
  1843. reason: str,
  1844. marked_by: str = "user",
  1845. chapter_discovered: Optional[int] = None,
  1846. ) -> int:
  1847. """标记无效事实(pending)"""
  1848. with self._get_conn() as conn:
  1849. cursor = conn.cursor()
  1850. cursor.execute(
  1851. """
  1852. INSERT INTO invalid_facts
  1853. (source_type, source_id, reason, status, marked_by, chapter_discovered)
  1854. VALUES (?, ?, ?, 'pending', ?, ?)
  1855. """,
  1856. (source_type, str(source_id), reason, marked_by, chapter_discovered),
  1857. )
  1858. conn.commit()
  1859. return int(cursor.lastrowid)
  1860. def resolve_invalid_fact(self, invalid_id: int, action: str) -> bool:
  1861. """确认或撤销无效标记"""
  1862. action = action.lower()
  1863. with self._get_conn() as conn:
  1864. cursor = conn.cursor()
  1865. if action == "confirm":
  1866. cursor.execute(
  1867. """
  1868. UPDATE invalid_facts
  1869. SET status = 'confirmed', confirmed_at = CURRENT_TIMESTAMP
  1870. WHERE id = ?
  1871. """,
  1872. (invalid_id,),
  1873. )
  1874. elif action == "dismiss":
  1875. cursor.execute("DELETE FROM invalid_facts WHERE id = ?", (invalid_id,))
  1876. else:
  1877. return False
  1878. conn.commit()
  1879. return cursor.rowcount > 0
  1880. def list_invalid_facts(self, status: Optional[str] = None) -> List[Dict]:
  1881. """列出无效事实"""
  1882. with self._get_conn() as conn:
  1883. cursor = conn.cursor()
  1884. if status:
  1885. cursor.execute(
  1886. "SELECT * FROM invalid_facts WHERE status = ? ORDER BY id DESC",
  1887. (status,),
  1888. )
  1889. else:
  1890. cursor.execute("SELECT * FROM invalid_facts ORDER BY id DESC")
  1891. return [dict(r) for r in cursor.fetchall()]
  1892. def get_invalid_ids(self, source_type: str, status: str = "confirmed") -> set[str]:
  1893. """获取无效事实 ID 集合"""
  1894. with self._get_conn() as conn:
  1895. cursor = conn.cursor()
  1896. cursor.execute(
  1897. "SELECT source_id FROM invalid_facts WHERE source_type = ? AND status = ?",
  1898. (source_type, status),
  1899. )
  1900. return {str(r[0]) for r in cursor.fetchall() if r and r[0] is not None}
  1901. # ==================== 日志记录 ====================
  1902. def log_rag_query(
  1903. self,
  1904. query: str,
  1905. query_type: str,
  1906. results_count: int,
  1907. hit_sources: Optional[str] = None,
  1908. latency_ms: Optional[int] = None,
  1909. chapter: Optional[int] = None,
  1910. ) -> None:
  1911. with self._get_conn() as conn:
  1912. cursor = conn.cursor()
  1913. cursor.execute(
  1914. """
  1915. INSERT INTO rag_query_log
  1916. (query, query_type, results_count, hit_sources, latency_ms, chapter)
  1917. VALUES (?, ?, ?, ?, ?, ?)
  1918. """,
  1919. (query, query_type, results_count, hit_sources, latency_ms, chapter),
  1920. )
  1921. conn.commit()
  1922. def log_tool_call(
  1923. self,
  1924. tool_name: str,
  1925. success: bool,
  1926. retry_count: int = 0,
  1927. error_code: Optional[str] = None,
  1928. error_message: Optional[str] = None,
  1929. chapter: Optional[int] = None,
  1930. ) -> None:
  1931. with self._get_conn() as conn:
  1932. cursor = conn.cursor()
  1933. cursor.execute(
  1934. """
  1935. INSERT INTO tool_call_stats
  1936. (tool_name, success, retry_count, error_code, error_message, chapter)
  1937. VALUES (?, ?, ?, ?, ?, ?)
  1938. """,
  1939. (tool_name, int(bool(success)), retry_count, error_code, error_message, chapter),
  1940. )
  1941. conn.commit()
  1942. def get_stats(self) -> Dict[str, int]:
  1943. """获取索引统计"""
  1944. with self._get_conn() as conn:
  1945. cursor = conn.cursor()
  1946. cursor.execute("SELECT COUNT(*) FROM chapters")
  1947. chapters = cursor.fetchone()[0]
  1948. cursor.execute("SELECT COUNT(*) FROM scenes")
  1949. scenes = cursor.fetchone()[0]
  1950. cursor.execute("SELECT COUNT(DISTINCT entity_id) FROM appearances")
  1951. appearances = cursor.fetchone()[0]
  1952. cursor.execute("SELECT MAX(chapter) FROM chapters")
  1953. max_chapter = cursor.fetchone()[0] or 0
  1954. # v5.1 引入统计
  1955. cursor.execute("SELECT COUNT(*) FROM entities")
  1956. entities = cursor.fetchone()[0]
  1957. cursor.execute("SELECT COUNT(*) FROM entities WHERE is_archived = 0")
  1958. active_entities = cursor.fetchone()[0]
  1959. cursor.execute("SELECT COUNT(*) FROM aliases")
  1960. aliases = cursor.fetchone()[0]
  1961. cursor.execute("SELECT COUNT(*) FROM state_changes")
  1962. state_changes = cursor.fetchone()[0]
  1963. cursor.execute("SELECT COUNT(*) FROM relationships")
  1964. relationships = cursor.fetchone()[0]
  1965. # v5.3 引入统计
  1966. cursor.execute("SELECT COUNT(*) FROM override_contracts")
  1967. override_contracts = cursor.fetchone()[0]
  1968. cursor.execute(
  1969. "SELECT COUNT(*) FROM override_contracts WHERE status = 'pending'"
  1970. )
  1971. pending_overrides = cursor.fetchone()[0]
  1972. cursor.execute("SELECT COUNT(*) FROM chase_debt WHERE status = 'active'")
  1973. active_debts = cursor.fetchone()[0]
  1974. cursor.execute(
  1975. "SELECT COALESCE(SUM(current_amount), 0) FROM chase_debt WHERE status IN ('active', 'overdue')"
  1976. )
  1977. total_debt = cursor.fetchone()[0]
  1978. cursor.execute("SELECT COUNT(*) FROM chapter_reading_power")
  1979. reading_power_records = cursor.fetchone()[0]
  1980. cursor.execute("SELECT COUNT(*) FROM review_metrics")
  1981. review_metrics = cursor.fetchone()[0]
  1982. return {
  1983. "chapters": chapters,
  1984. "scenes": scenes,
  1985. "appearances": appearances,
  1986. "max_chapter": max_chapter,
  1987. # v5.1 引入
  1988. "entities": entities,
  1989. "active_entities": active_entities,
  1990. "aliases": aliases,
  1991. "state_changes": state_changes,
  1992. "relationships": relationships,
  1993. # v5.3 引入
  1994. "override_contracts": override_contracts,
  1995. "pending_overrides": pending_overrides,
  1996. "active_debts": active_debts,
  1997. "total_debt": total_debt,
  1998. "reading_power_records": reading_power_records,
  1999. "review_metrics": review_metrics,
  2000. }
  2001. # ==================== CLI 接口 ====================
  2002. def main():
  2003. import argparse
  2004. from .cli_output import print_success, print_error
  2005. parser = argparse.ArgumentParser(description="Index Manager CLI (v5.4)")
  2006. parser.add_argument("--project-root", type=str, help="项目根目录")
  2007. subparsers = parser.add_subparsers(dest="command")
  2008. # 获取统计
  2009. subparsers.add_parser("stats")
  2010. # 查询章节
  2011. chapter_parser = subparsers.add_parser("get-chapter")
  2012. chapter_parser.add_argument("--chapter", type=int, required=True)
  2013. # 查询最近出场
  2014. recent_parser = subparsers.add_parser("recent-appearances")
  2015. recent_parser.add_argument("--limit", type=int, default=None)
  2016. # 查询实体出场
  2017. entity_parser = subparsers.add_parser("entity-appearances")
  2018. entity_parser.add_argument("--entity", required=True)
  2019. entity_parser.add_argument("--limit", type=int, default=None)
  2020. # 搜索场景
  2021. search_parser = subparsers.add_parser("search-scenes")
  2022. search_parser.add_argument("--location", required=True)
  2023. search_parser.add_argument("--limit", type=int, default=None)
  2024. # 处理章节数据 (写入)
  2025. process_parser = subparsers.add_parser("process-chapter")
  2026. process_parser.add_argument("--chapter", type=int, required=True)
  2027. process_parser.add_argument("--title", required=True)
  2028. process_parser.add_argument("--location", required=True)
  2029. process_parser.add_argument("--word-count", type=int, required=True)
  2030. process_parser.add_argument("--entities", required=True, help="JSON 格式的实体列表")
  2031. process_parser.add_argument("--scenes", required=True, help="JSON 格式的场景列表")
  2032. # ==================== v5.1 引入命令 ====================
  2033. # 获取实体
  2034. get_entity_parser = subparsers.add_parser("get-entity")
  2035. get_entity_parser.add_argument("--id", required=True, help="实体 ID")
  2036. # 获取核心实体
  2037. subparsers.add_parser("get-core-entities")
  2038. # 获取主角
  2039. subparsers.add_parser("get-protagonist")
  2040. # 按类型获取实体
  2041. type_parser = subparsers.add_parser("get-entities-by-type")
  2042. type_parser.add_argument(
  2043. "--type", required=True, help="实体类型 (角色/地点/物品/势力/招式)"
  2044. )
  2045. type_parser.add_argument("--include-archived", action="store_true")
  2046. # 按别名查找实体
  2047. alias_parser = subparsers.add_parser("get-by-alias")
  2048. alias_parser.add_argument("--alias", required=True, help="别名")
  2049. # 获取实体别名
  2050. aliases_parser = subparsers.add_parser("get-aliases")
  2051. aliases_parser.add_argument("--entity", required=True, help="实体 ID")
  2052. # 注册别名
  2053. reg_alias_parser = subparsers.add_parser("register-alias")
  2054. reg_alias_parser.add_argument("--alias", required=True)
  2055. reg_alias_parser.add_argument("--entity", required=True)
  2056. reg_alias_parser.add_argument("--type", required=True, help="实体类型")
  2057. # 获取实体关系
  2058. rel_parser = subparsers.add_parser("get-relationships")
  2059. rel_parser.add_argument("--entity", required=True)
  2060. rel_parser.add_argument(
  2061. "--direction", choices=["from", "to", "both"], default="both"
  2062. )
  2063. # 获取状态变化
  2064. changes_parser = subparsers.add_parser("get-state-changes")
  2065. changes_parser.add_argument("--entity", required=True)
  2066. changes_parser.add_argument("--limit", type=int, default=20)
  2067. # 写入实体
  2068. upsert_entity_parser = subparsers.add_parser("upsert-entity")
  2069. upsert_entity_parser.add_argument(
  2070. "--data", required=True, help="JSON 格式的实体数据"
  2071. )
  2072. # 写入关系
  2073. upsert_rel_parser = subparsers.add_parser("upsert-relationship")
  2074. upsert_rel_parser.add_argument("--data", required=True, help="JSON 格式的关系数据")
  2075. # 写入状态变化
  2076. state_change_parser = subparsers.add_parser("record-state-change")
  2077. state_change_parser.add_argument(
  2078. "--data", required=True, help="JSON 格式的状态变化数据"
  2079. )
  2080. # ==================== v5.4 新增命令 ====================
  2081. invalid_parser = subparsers.add_parser("mark-invalid")
  2082. invalid_parser.add_argument("--source-type", required=True)
  2083. invalid_parser.add_argument("--source-id", required=True)
  2084. invalid_parser.add_argument("--reason", required=True)
  2085. invalid_parser.add_argument("--marked-by", default="user")
  2086. invalid_parser.add_argument("--chapter", type=int, default=None)
  2087. resolve_parser = subparsers.add_parser("resolve-invalid")
  2088. resolve_parser.add_argument("--id", type=int, required=True)
  2089. resolve_parser.add_argument("--action", choices=["confirm", "dismiss"], required=True)
  2090. list_invalid_parser = subparsers.add_parser("list-invalid")
  2091. list_invalid_parser.add_argument("--status", choices=["pending", "confirmed"], default=None)
  2092. review_save_parser = subparsers.add_parser("save-review-metrics")
  2093. review_save_parser.add_argument("--data", required=True, help="JSON 格式的审查指标数据")
  2094. review_recent_parser = subparsers.add_parser("get-recent-review-metrics")
  2095. review_recent_parser.add_argument("--limit", type=int, default=5)
  2096. review_trend_parser = subparsers.add_parser("get-review-trend-stats")
  2097. review_trend_parser.add_argument("--last-n", type=int, default=5)
  2098. # ==================== v5.3 引入命令 ====================
  2099. # 获取债务汇总
  2100. subparsers.add_parser("get-debt-summary")
  2101. # 获取最近章节追读力元数据
  2102. reading_power_parser = subparsers.add_parser("get-recent-reading-power")
  2103. reading_power_parser.add_argument("--limit", type=int, default=10)
  2104. # 获取章节追读力元数据
  2105. chapter_rp_parser = subparsers.add_parser("get-chapter-reading-power")
  2106. chapter_rp_parser.add_argument("--chapter", type=int, required=True)
  2107. # 获取爽点模式使用统计
  2108. pattern_stats_parser = subparsers.add_parser("get-pattern-usage-stats")
  2109. pattern_stats_parser.add_argument("--last-n", type=int, default=20)
  2110. # 获取钩子类型使用统计
  2111. hook_stats_parser = subparsers.add_parser("get-hook-type-stats")
  2112. hook_stats_parser.add_argument("--last-n", type=int, default=20)
  2113. # 获取待偿还Override
  2114. pending_override_parser = subparsers.add_parser("get-pending-overrides")
  2115. pending_override_parser.add_argument("--before-chapter", type=int, default=None)
  2116. # 获取逾期Override
  2117. overdue_override_parser = subparsers.add_parser("get-overdue-overrides")
  2118. overdue_override_parser.add_argument("--current-chapter", type=int, required=True)
  2119. # 获取活跃债务
  2120. subparsers.add_parser("get-active-debts")
  2121. # 获取逾期债务
  2122. overdue_debt_parser = subparsers.add_parser("get-overdue-debts")
  2123. overdue_debt_parser.add_argument("--current-chapter", type=int, required=True)
  2124. # 计算利息
  2125. accrue_parser = subparsers.add_parser("accrue-interest")
  2126. accrue_parser.add_argument("--current-chapter", type=int, required=True)
  2127. # 偿还债务
  2128. pay_debt_parser = subparsers.add_parser("pay-debt")
  2129. pay_debt_parser.add_argument("--debt-id", type=int, required=True)
  2130. pay_debt_parser.add_argument("--amount", type=float, required=True)
  2131. pay_debt_parser.add_argument("--chapter", type=int, required=True)
  2132. # 创建Override Contract
  2133. create_override_parser = subparsers.add_parser("create-override-contract")
  2134. create_override_parser.add_argument(
  2135. "--data", required=True, help="JSON 格式的Override Contract数据"
  2136. )
  2137. # 创建债务
  2138. create_debt_parser = subparsers.add_parser("create-debt")
  2139. create_debt_parser.add_argument("--data", required=True, help="JSON 格式的债务数据")
  2140. # 标记Override已偿还
  2141. fulfill_override_parser = subparsers.add_parser("fulfill-override")
  2142. fulfill_override_parser.add_argument("--contract-id", type=int, required=True)
  2143. # 保存章节追读力元数据
  2144. save_rp_parser = subparsers.add_parser("save-chapter-reading-power")
  2145. save_rp_parser.add_argument(
  2146. "--data", required=True, help="JSON 格式的章节追读力元数据"
  2147. )
  2148. args = parser.parse_args()
  2149. # 初始化
  2150. config = None
  2151. if args.project_root:
  2152. from .config import DataModulesConfig
  2153. config = DataModulesConfig.from_project_root(args.project_root)
  2154. manager = IndexManager(config)
  2155. tool_name = f"index_manager:{args.command or 'unknown'}"
  2156. def emit_success(data=None, message: str = "ok", chapter: Optional[int] = None):
  2157. print_success(data, message=message)
  2158. try:
  2159. manager.log_tool_call(tool_name, True, chapter=chapter)
  2160. except Exception:
  2161. pass
  2162. def emit_error(code: str, message: str, suggestion: Optional[str] = None, chapter: Optional[int] = None):
  2163. print_error(code, message, suggestion=suggestion)
  2164. try:
  2165. manager.log_tool_call(tool_name, False, error_code=code, error_message=message, chapter=chapter)
  2166. except Exception:
  2167. pass
  2168. if args.command == "stats":
  2169. emit_success(manager.get_stats(), message="stats")
  2170. elif args.command == "get-chapter":
  2171. chapter = manager.get_chapter(args.chapter)
  2172. if chapter:
  2173. emit_success(chapter, message="chapter")
  2174. else:
  2175. emit_error("NOT_FOUND", f"未找到章节: {args.chapter}")
  2176. elif args.command == "recent-appearances":
  2177. appearances = manager.get_recent_appearances(args.limit)
  2178. emit_success(appearances, message="recent_appearances")
  2179. elif args.command == "entity-appearances":
  2180. appearances = manager.get_entity_appearances(args.entity, args.limit)
  2181. emit_success({"entity": args.entity, "appearances": appearances}, message="entity_appearances")
  2182. elif args.command == "search-scenes":
  2183. scenes = manager.search_scenes_by_location(args.location, args.limit)
  2184. emit_success(scenes, message="scenes")
  2185. elif args.command == "process-chapter":
  2186. entities = json.loads(args.entities)
  2187. scenes = json.loads(args.scenes)
  2188. stats = manager.process_chapter_data(
  2189. chapter=args.chapter,
  2190. title=args.title,
  2191. location=args.location,
  2192. word_count=args.word_count,
  2193. entities=entities,
  2194. scenes=scenes,
  2195. )
  2196. emit_success(stats, message="chapter_processed", chapter=args.chapter)
  2197. # ==================== v5.1 引入命令处理 ====================
  2198. elif args.command == "get-entity":
  2199. entity = manager.get_entity(args.id)
  2200. if entity:
  2201. emit_success(entity, message="entity")
  2202. else:
  2203. emit_error("NOT_FOUND", f"未找到实体: {args.id}")
  2204. elif args.command == "get-core-entities":
  2205. entities = manager.get_core_entities()
  2206. emit_success(entities, message="core_entities")
  2207. elif args.command == "get-protagonist":
  2208. protagonist = manager.get_protagonist()
  2209. if protagonist:
  2210. emit_success(protagonist, message="protagonist")
  2211. else:
  2212. emit_error("NOT_FOUND", "未设置主角")
  2213. elif args.command == "get-entities-by-type":
  2214. entities = manager.get_entities_by_type(args.type, args.include_archived)
  2215. emit_success(entities, message="entities_by_type")
  2216. elif args.command == "get-by-alias":
  2217. entities = manager.get_entities_by_alias(args.alias)
  2218. if entities:
  2219. emit_success(entities, message="entities_by_alias")
  2220. else:
  2221. emit_error("NOT_FOUND", f"未找到别名: {args.alias}")
  2222. elif args.command == "get-aliases":
  2223. aliases = manager.get_entity_aliases(args.entity)
  2224. if aliases:
  2225. emit_success({"entity": args.entity, "aliases": aliases}, message="aliases")
  2226. else:
  2227. emit_error("NOT_FOUND", f"{args.entity} 没有别名")
  2228. elif args.command == "register-alias":
  2229. success = manager.register_alias(args.alias, args.entity, args.type)
  2230. if success:
  2231. emit_success(
  2232. {"alias": args.alias, "entity": args.entity, "type": args.type},
  2233. message="alias_registered",
  2234. )
  2235. else:
  2236. emit_error("ALIAS_EXISTS", f"别名已存在或注册失败: {args.alias}")
  2237. elif args.command == "get-relationships":
  2238. rels = manager.get_entity_relationships(args.entity, args.direction)
  2239. emit_success(rels, message="relationships")
  2240. elif args.command == "get-state-changes":
  2241. changes = manager.get_entity_state_changes(args.entity, args.limit)
  2242. emit_success(changes, message="state_changes")
  2243. elif args.command == "upsert-entity":
  2244. data = json.loads(args.data)
  2245. entity = EntityMeta(
  2246. id=data["id"],
  2247. type=data["type"],
  2248. canonical_name=data["canonical_name"],
  2249. tier=data.get("tier", "装饰"),
  2250. desc=data.get("desc", ""),
  2251. current=data.get("current", {}),
  2252. first_appearance=data.get("first_appearance", 0),
  2253. last_appearance=data.get("last_appearance", 0),
  2254. is_protagonist=data.get("is_protagonist", False),
  2255. is_archived=data.get("is_archived", False),
  2256. )
  2257. is_new = manager.upsert_entity(entity)
  2258. emit_success({"id": entity.id, "created": is_new}, message="entity_upserted")
  2259. elif args.command == "upsert-relationship":
  2260. data = json.loads(args.data)
  2261. rel = RelationshipMeta(
  2262. from_entity=data["from_entity"],
  2263. to_entity=data["to_entity"],
  2264. type=data["type"],
  2265. description=data.get("description", ""),
  2266. chapter=data["chapter"],
  2267. )
  2268. is_new = manager.upsert_relationship(rel)
  2269. emit_success(
  2270. {"from": rel.from_entity, "to": rel.to_entity, "type": rel.type, "created": is_new},
  2271. message="relationship_upserted",
  2272. )
  2273. elif args.command == "record-state-change":
  2274. data = json.loads(args.data)
  2275. change = StateChangeMeta(
  2276. entity_id=data["entity_id"],
  2277. field=data["field"],
  2278. old_value=data.get("old_value", ""),
  2279. new_value=data["new_value"],
  2280. reason=data.get("reason", ""),
  2281. chapter=data["chapter"],
  2282. )
  2283. record_id = manager.record_state_change(change)
  2284. emit_success({"id": record_id, "entity": change.entity_id, "field": change.field}, message="state_change_recorded")
  2285. # ==================== v5.4 无效事实命令处理 ====================
  2286. elif args.command == "mark-invalid":
  2287. invalid_id = manager.mark_invalid_fact(
  2288. args.source_type,
  2289. args.source_id,
  2290. args.reason,
  2291. marked_by=args.marked_by,
  2292. chapter_discovered=args.chapter,
  2293. )
  2294. emit_success({"id": invalid_id}, message="invalid_marked")
  2295. elif args.command == "resolve-invalid":
  2296. ok = manager.resolve_invalid_fact(args.id, args.action)
  2297. if ok:
  2298. emit_success({"id": args.id, "action": args.action}, message="invalid_resolved")
  2299. else:
  2300. emit_error("INVALID_ACTION", f"无法处理 action: {args.action}")
  2301. elif args.command == "list-invalid":
  2302. rows = manager.list_invalid_facts(args.status)
  2303. emit_success(rows, message="invalid_list")
  2304. elif args.command == "save-review-metrics":
  2305. data = json.loads(args.data)
  2306. metrics = ReviewMetrics(
  2307. start_chapter=data["start_chapter"],
  2308. end_chapter=data["end_chapter"],
  2309. overall_score=data.get("overall_score", 0.0),
  2310. dimension_scores=data.get("dimension_scores", {}),
  2311. severity_counts=data.get("severity_counts", {}),
  2312. critical_issues=data.get("critical_issues", []),
  2313. report_file=data.get("report_file", ""),
  2314. notes=data.get("notes", ""),
  2315. )
  2316. manager.save_review_metrics(metrics)
  2317. emit_success(
  2318. {"start_chapter": metrics.start_chapter, "end_chapter": metrics.end_chapter},
  2319. message="review_metrics_saved",
  2320. )
  2321. elif args.command == "get-recent-review-metrics":
  2322. records = manager.get_recent_review_metrics(args.limit)
  2323. emit_success(records, message="recent_review_metrics")
  2324. elif args.command == "get-review-trend-stats":
  2325. stats = manager.get_review_trend_stats(args.last_n)
  2326. emit_success(stats, message="review_trend_stats")
  2327. # ==================== v5.3 引入命令处理 ====================
  2328. elif args.command == "get-debt-summary":
  2329. summary = manager.get_debt_summary()
  2330. emit_success(summary, message="debt_summary")
  2331. elif args.command == "get-recent-reading-power":
  2332. records = manager.get_recent_reading_power(args.limit)
  2333. emit_success(records, message="recent_reading_power")
  2334. elif args.command == "get-chapter-reading-power":
  2335. record = manager.get_chapter_reading_power(args.chapter)
  2336. if record:
  2337. emit_success(record, message="chapter_reading_power")
  2338. else:
  2339. emit_error("NOT_FOUND", f"未找到第 {args.chapter} 章的追读力元数据")
  2340. elif args.command == "get-pattern-usage-stats":
  2341. stats = manager.get_pattern_usage_stats(args.last_n)
  2342. emit_success(stats, message="pattern_usage_stats")
  2343. elif args.command == "get-hook-type-stats":
  2344. stats = manager.get_hook_type_stats(args.last_n)
  2345. emit_success(stats, message="hook_type_stats")
  2346. elif args.command == "get-pending-overrides":
  2347. overrides = manager.get_pending_overrides(args.before_chapter)
  2348. emit_success(overrides, message="pending_overrides")
  2349. elif args.command == "get-overdue-overrides":
  2350. overrides = manager.get_overdue_overrides(args.current_chapter)
  2351. emit_success(overrides, message="overdue_overrides")
  2352. elif args.command == "get-active-debts":
  2353. debts = manager.get_active_debts()
  2354. emit_success(debts, message="active_debts")
  2355. elif args.command == "get-overdue-debts":
  2356. debts = manager.get_overdue_debts(args.current_chapter)
  2357. emit_success(debts, message="overdue_debts")
  2358. elif args.command == "accrue-interest":
  2359. result = manager.accrue_interest(args.current_chapter)
  2360. emit_success(result, message="interest_accrued", chapter=args.current_chapter)
  2361. elif args.command == "pay-debt":
  2362. result = manager.pay_debt(args.debt_id, args.amount, args.chapter)
  2363. if "error" in result:
  2364. emit_error("PAY_DEBT_FAILED", result["error"], chapter=args.chapter)
  2365. else:
  2366. emit_success(result, message="debt_payment", chapter=args.chapter)
  2367. elif args.command == "create-override-contract":
  2368. data = json.loads(args.data)
  2369. contract = OverrideContractMeta(
  2370. chapter=data["chapter"],
  2371. constraint_type=data["constraint_type"],
  2372. constraint_id=data["constraint_id"],
  2373. rationale_type=data["rationale_type"],
  2374. rationale_text=data.get("rationale_text", ""),
  2375. payback_plan=data.get("payback_plan", ""),
  2376. due_chapter=data["due_chapter"],
  2377. status=data.get("status", "pending"),
  2378. )
  2379. contract_id = manager.create_override_contract(contract)
  2380. emit_success({"id": contract_id}, message="override_contract_created")
  2381. elif args.command == "create-debt":
  2382. data = json.loads(args.data)
  2383. debt = ChaseDebtMeta(
  2384. debt_type=data["debt_type"],
  2385. original_amount=data.get("original_amount", 1.0),
  2386. current_amount=data.get("current_amount", data.get("original_amount", 1.0)),
  2387. interest_rate=data.get("interest_rate", 0.1),
  2388. source_chapter=data["source_chapter"],
  2389. due_chapter=data["due_chapter"],
  2390. override_contract_id=data.get("override_contract_id", 0),
  2391. status=data.get("status", "active"),
  2392. )
  2393. debt_id = manager.create_debt(debt)
  2394. emit_success({"id": debt_id, "debt_type": debt.debt_type}, message="debt_created")
  2395. elif args.command == "fulfill-override":
  2396. success = manager.fulfill_override(args.contract_id)
  2397. if success:
  2398. emit_success({"id": args.contract_id}, message="override_fulfilled")
  2399. else:
  2400. emit_error("NOT_FOUND", f"未找到 Override Contract #{args.contract_id}")
  2401. elif args.command == "save-chapter-reading-power":
  2402. data = json.loads(args.data)
  2403. meta = ChapterReadingPowerMeta(
  2404. chapter=data["chapter"],
  2405. hook_type=data.get("hook_type", ""),
  2406. hook_strength=data.get("hook_strength", "medium"),
  2407. coolpoint_patterns=data.get("coolpoint_patterns", []),
  2408. micropayoffs=data.get("micropayoffs", []),
  2409. hard_violations=data.get("hard_violations", []),
  2410. soft_suggestions=data.get("soft_suggestions", []),
  2411. is_transition=data.get("is_transition", False),
  2412. override_count=data.get("override_count", 0),
  2413. debt_balance=data.get("debt_balance", 0.0),
  2414. )
  2415. manager.save_chapter_reading_power(meta)
  2416. emit_success({"chapter": meta.chapter}, message="reading_power_saved")
  2417. else:
  2418. emit_error("UNKNOWN_COMMAND", "未指定有效命令", suggestion="请查看 --help")
  2419. if __name__ == "__main__":
  2420. import sys
  2421. if sys.platform == "win32":
  2422. import io
  2423. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
  2424. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
  2425. main()