index_manager.py 83 KB

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