runner.ts 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948
  1. import type { LLMClient, OnStreamProgress } from "../llm/provider.js";
  2. import { chatCompletion, createLLMClient } from "../llm/provider.js";
  3. import type { Logger } from "../utils/logger.js";
  4. import type { BookConfig, FanficMode } from "../models/book.js";
  5. import type { ChapterMeta } from "../models/chapter.js";
  6. import type { NotifyChannel, LLMConfig, AgentLLMOverride, InputGovernanceMode } from "../models/project.js";
  7. import type { GenreProfile } from "../models/genre-profile.js";
  8. import { ArchitectAgent, type ArchitectOutput } from "../agents/architect.js";
  9. import { FoundationReviewerAgent } from "../agents/foundation-reviewer.js";
  10. import { PlannerAgent, type PlanChapterOutput } from "../agents/planner.js";
  11. import { ComposerAgent } from "../agents/composer.js";
  12. import { WriterAgent, type WriteChapterInput, type WriteChapterOutput } from "../agents/writer.js";
  13. import { LengthNormalizerAgent } from "../agents/length-normalizer.js";
  14. import { ChapterAnalyzerAgent } from "../agents/chapter-analyzer.js";
  15. import { ContinuityAuditor } from "../agents/continuity.js";
  16. import { ReviserAgent, DEFAULT_REVISE_MODE, type ReviseMode } from "../agents/reviser.js";
  17. import { StateValidatorAgent, type ValidationResult, type ValidationWarning } from "../agents/state-validator.js";
  18. import { RadarAgent } from "../agents/radar.js";
  19. import type { RadarSource } from "../agents/radar-source.js";
  20. import { readGenreProfile } from "../agents/rules-reader.js";
  21. import { analyzeAITells } from "../agents/ai-tells.js";
  22. import { analyzeSensitiveWords } from "../agents/sensitive-words.js";
  23. import { StateManager } from "../state/manager.js";
  24. import { MemoryDB, type Fact } from "../state/memory-db.js";
  25. import { dispatchNotification, dispatchWebhookEvent } from "../notify/dispatcher.js";
  26. import type { WebhookEvent } from "../notify/webhook.js";
  27. import type { AgentContext } from "../agents/base.js";
  28. import type { AuditResult, AuditIssue } from "../agents/continuity.js";
  29. import type { RadarResult } from "../agents/radar.js";
  30. import type { LengthSpec, LengthTelemetry } from "../models/length-governance.js";
  31. import type { ContextPackage, RuleStack } from "../models/input-governance.js";
  32. import { buildLengthSpec, countChapterLength, formatLengthCount, isOutsideHardRange, isOutsideSoftRange, resolveLengthCountingMode, type LengthLanguage } from "../utils/length-metrics.js";
  33. import { analyzeLongSpanFatigue } from "../utils/long-span-fatigue.js";
  34. import { loadNarrativeMemorySeed, loadSnapshotCurrentStateFacts } from "../state/runtime-state-store.js";
  35. import { rewriteStructuredStateFromMarkdown } from "../state/state-bootstrap.js";
  36. import { readFile, readdir, writeFile, mkdir, rename, rm, stat } from "node:fs/promises";
  37. import { join } from "node:path";
  38. import {
  39. parseStateDegradedReviewNote,
  40. resolveStateDegradedBaseStatus,
  41. retrySettlementAfterValidationFailure,
  42. } from "./chapter-state-recovery.js";
  43. import { persistChapterArtifacts } from "./chapter-persistence.js";
  44. import { runChapterReviewCycle } from "./chapter-review-cycle.js";
  45. import { validateChapterTruthPersistence } from "./chapter-truth-validation.js";
  46. import { loadPersistedPlan, relativeToBookDir } from "./persisted-governed-plan.js";
  47. const SEQUENCE_LEVEL_CATEGORIES = new Set([
  48. "Pacing Monotony", "节奏单调",
  49. "Mood Monotony", "情绪单调",
  50. "Title Collapse", "标题重复",
  51. "Title Clustering", "标题聚集",
  52. "Opening Pattern Repetition", "开头同构",
  53. "Ending Pattern Repetition", "结尾同构",
  54. ]);
  55. function isSequenceLevelCategory(category: string): boolean {
  56. return SEQUENCE_LEVEL_CATEGORIES.has(category);
  57. }
  58. export interface PipelineConfig {
  59. readonly client: LLMClient;
  60. readonly model: string;
  61. readonly projectRoot: string;
  62. readonly defaultLLMConfig?: LLMConfig;
  63. readonly notifyChannels?: ReadonlyArray<NotifyChannel>;
  64. readonly radarSources?: ReadonlyArray<RadarSource>;
  65. readonly externalContext?: string;
  66. readonly modelOverrides?: Record<string, string | AgentLLMOverride>;
  67. readonly inputGovernanceMode?: InputGovernanceMode;
  68. readonly logger?: Logger;
  69. readonly onStreamProgress?: OnStreamProgress;
  70. }
  71. export interface TokenUsageSummary {
  72. readonly promptTokens: number;
  73. readonly completionTokens: number;
  74. readonly totalTokens: number;
  75. }
  76. export interface ChapterPipelineResult {
  77. readonly chapterNumber: number;
  78. readonly title: string;
  79. readonly wordCount: number;
  80. readonly auditResult: AuditResult;
  81. readonly revised: boolean;
  82. readonly status: "ready-for-review" | "audit-failed" | "state-degraded";
  83. readonly lengthWarnings?: ReadonlyArray<string>;
  84. readonly lengthTelemetry?: LengthTelemetry;
  85. readonly tokenUsage?: TokenUsageSummary;
  86. }
  87. // Atomic operation results
  88. export interface DraftResult {
  89. readonly chapterNumber: number;
  90. readonly title: string;
  91. readonly wordCount: number;
  92. readonly filePath: string;
  93. readonly lengthWarnings?: ReadonlyArray<string>;
  94. readonly lengthTelemetry?: LengthTelemetry;
  95. readonly tokenUsage?: TokenUsageSummary;
  96. }
  97. export interface PlanChapterResult {
  98. readonly bookId: string;
  99. readonly chapterNumber: number;
  100. readonly intentPath: string;
  101. readonly goal: string;
  102. readonly conflicts: ReadonlyArray<string>;
  103. }
  104. export interface ComposeChapterResult extends PlanChapterResult {
  105. readonly contextPath: string;
  106. readonly ruleStackPath: string;
  107. readonly tracePath: string;
  108. }
  109. export interface ReviseResult {
  110. readonly chapterNumber: number;
  111. readonly wordCount: number;
  112. readonly fixedIssues: ReadonlyArray<string>;
  113. readonly applied: boolean;
  114. readonly status: "unchanged" | "ready-for-review" | "audit-failed";
  115. readonly skippedReason?: string;
  116. readonly lengthWarnings?: ReadonlyArray<string>;
  117. readonly lengthTelemetry?: LengthTelemetry;
  118. }
  119. export interface TruthFiles {
  120. readonly currentState: string;
  121. readonly particleLedger: string;
  122. readonly pendingHooks: string;
  123. readonly storyBible: string;
  124. readonly volumeOutline: string;
  125. readonly bookRules: string;
  126. }
  127. export interface BookStatusInfo {
  128. readonly bookId: string;
  129. readonly title: string;
  130. readonly genre: string;
  131. readonly platform: string;
  132. readonly status: string;
  133. readonly chaptersWritten: number;
  134. readonly totalWords: number;
  135. readonly nextChapter: number;
  136. readonly chapters: ReadonlyArray<ChapterMeta>;
  137. }
  138. interface MergedAuditEvaluation {
  139. readonly auditResult: AuditResult;
  140. readonly aiTellCount: number;
  141. readonly blockingCount: number;
  142. readonly criticalCount: number;
  143. readonly revisionBlockingIssues: ReadonlyArray<AuditIssue>;
  144. }
  145. export interface ImportChaptersInput {
  146. readonly bookId: string;
  147. readonly chapters: ReadonlyArray<{ readonly title: string; readonly content: string }>;
  148. readonly resumeFrom?: number;
  149. /** "continuation" (default) = pick up where the text left off, no new spacetime.
  150. * "series" = shared universe but independent new story, requires new spacetime. */
  151. readonly importMode?: "continuation" | "series";
  152. }
  153. export interface ImportChaptersResult {
  154. readonly bookId: string;
  155. readonly importedCount: number;
  156. readonly totalWords: number;
  157. readonly nextChapter: number;
  158. }
  159. export interface InitBookOptions {
  160. readonly externalContext?: string;
  161. readonly authorIntent?: string;
  162. readonly currentFocus?: string;
  163. }
  164. export class PipelineRunner {
  165. private readonly state: StateManager;
  166. private readonly config: PipelineConfig;
  167. private readonly agentClients = new Map<string, LLMClient>();
  168. private memoryIndexFallbackWarned = false;
  169. constructor(config: PipelineConfig) {
  170. this.config = config;
  171. this.state = new StateManager(config.projectRoot);
  172. }
  173. private localize(language: LengthLanguage, messages: { zh: string; en: string }): string {
  174. return language === "en" ? messages.en : messages.zh;
  175. }
  176. private async resolveBookLanguage(
  177. book: Pick<BookConfig, "genre" | "language">,
  178. ): Promise<LengthLanguage> {
  179. if (book.language) {
  180. return book.language;
  181. }
  182. try {
  183. const { profile } = await this.loadGenreProfile(book.genre);
  184. return profile.language;
  185. } catch {
  186. return "zh";
  187. }
  188. }
  189. private async resolveBookLanguageById(bookId: string): Promise<LengthLanguage> {
  190. try {
  191. const book = await this.state.loadBookConfig(bookId);
  192. return await this.resolveBookLanguage(book);
  193. } catch {
  194. return "zh";
  195. }
  196. }
  197. private languageFromLengthSpec(lengthSpec: Pick<LengthSpec, "countingMode">): LengthLanguage {
  198. return lengthSpec.countingMode === "en_words" ? "en" : "zh";
  199. }
  200. private logStage(language: LengthLanguage, message: { zh: string; en: string }): void {
  201. this.config.logger?.info(
  202. `${this.localize(language, { zh: "阶段:", en: "Stage: " })}${this.localize(language, message)}`,
  203. );
  204. }
  205. private logInfo(language: LengthLanguage, message: { zh: string; en: string }): void {
  206. this.config.logger?.info(this.localize(language, message));
  207. }
  208. private logWarn(language: LengthLanguage, message: { zh: string; en: string }): void {
  209. this.config.logger?.warn(this.localize(language, message));
  210. }
  211. private async tryGenerateStyleGuide(
  212. bookId: string,
  213. referenceText: string,
  214. sourceName: string | undefined,
  215. language?: LengthLanguage,
  216. ): Promise<void> {
  217. try {
  218. await this.generateStyleGuide(bookId, referenceText, sourceName);
  219. } catch (error) {
  220. const resolvedLanguage = language ?? await this.resolveBookLanguageById(bookId);
  221. const detail = error instanceof Error ? error.message : String(error);
  222. this.logWarn(resolvedLanguage, {
  223. zh: `风格指纹提取失败,已跳过:${detail}`,
  224. en: `Style fingerprint extraction failed and was skipped: ${detail}`,
  225. });
  226. }
  227. }
  228. private async generateAndReviewFoundation(params: {
  229. readonly generate: (reviewFeedback?: string) => Promise<ArchitectOutput>;
  230. readonly reviewer: FoundationReviewerAgent;
  231. readonly mode: "original" | "fanfic" | "series";
  232. readonly sourceCanon?: string;
  233. readonly styleGuide?: string;
  234. readonly language: "zh" | "en";
  235. readonly stageLanguage: LengthLanguage;
  236. readonly maxRetries?: number;
  237. }): Promise<ArchitectOutput> {
  238. const maxRetries = params.maxRetries ?? 2;
  239. let foundation = await params.generate();
  240. for (let attempt = 0; attempt < maxRetries; attempt++) {
  241. this.logStage(params.stageLanguage, {
  242. zh: `审核基础设定(第${attempt + 1}轮)`,
  243. en: `reviewing foundation (round ${attempt + 1})`,
  244. });
  245. const review = await params.reviewer.review({
  246. foundation,
  247. mode: params.mode,
  248. sourceCanon: params.sourceCanon,
  249. styleGuide: params.styleGuide,
  250. language: params.language,
  251. });
  252. this.config.logger?.info(
  253. `Foundation review: ${review.totalScore}/100 ${review.passed ? "PASSED" : "REJECTED"}`,
  254. );
  255. for (const dim of review.dimensions) {
  256. this.config.logger?.info(` [${dim.score}] ${dim.name.slice(0, 40)}`);
  257. }
  258. if (review.passed) {
  259. return foundation;
  260. }
  261. this.logWarn(params.stageLanguage, {
  262. zh: `基础设定未通过审核(${review.totalScore}分),正在重新生成...`,
  263. en: `Foundation rejected (${review.totalScore}/100), regenerating...`,
  264. });
  265. foundation = await params.generate(this.buildFoundationReviewFeedback(review, params.language));
  266. }
  267. // Final review
  268. const finalReview = await params.reviewer.review({
  269. foundation,
  270. mode: params.mode,
  271. sourceCanon: params.sourceCanon,
  272. styleGuide: params.styleGuide,
  273. language: params.language,
  274. });
  275. this.config.logger?.info(
  276. `Foundation final review: ${finalReview.totalScore}/100 ${finalReview.passed ? "PASSED" : "ACCEPTED (max retries)"}`,
  277. );
  278. return foundation;
  279. }
  280. private buildFoundationReviewFeedback(
  281. review: {
  282. readonly dimensions: ReadonlyArray<{
  283. readonly name: string;
  284. readonly score: number;
  285. readonly feedback: string;
  286. }>;
  287. readonly overallFeedback: string;
  288. },
  289. language: "zh" | "en",
  290. ): string {
  291. const dimensionLines = review.dimensions
  292. .map((dimension) => (
  293. language === "en"
  294. ? `- ${dimension.name} [${dimension.score}]: ${dimension.feedback}`
  295. : `- ${dimension.name}(${dimension.score}分):${dimension.feedback}`
  296. ))
  297. .join("\n");
  298. return language === "en"
  299. ? [
  300. "## Overall Feedback",
  301. review.overallFeedback,
  302. "",
  303. "## Dimension Notes",
  304. dimensionLines || "- none",
  305. ].join("\n")
  306. : [
  307. "## 总评",
  308. review.overallFeedback,
  309. "",
  310. "## 分项问题",
  311. dimensionLines || "- 无",
  312. ].join("\n");
  313. }
  314. private agentCtx(bookId?: string): AgentContext {
  315. return {
  316. client: this.config.client,
  317. model: this.config.model,
  318. projectRoot: this.config.projectRoot,
  319. bookId,
  320. logger: this.config.logger,
  321. onStreamProgress: this.config.onStreamProgress,
  322. };
  323. }
  324. private resolveOverride(agentName: string): { model: string; client: LLMClient } {
  325. const override = this.config.modelOverrides?.[agentName];
  326. if (!override) {
  327. return { model: this.config.model, client: this.config.client };
  328. }
  329. if (typeof override === "string") {
  330. return { model: override, client: this.config.client };
  331. }
  332. // Full override — needs its own client if baseUrl differs
  333. if (!override.baseUrl) {
  334. return { model: override.model, client: this.config.client };
  335. }
  336. const base = this.config.defaultLLMConfig;
  337. const provider = override.provider ?? base?.provider ?? "custom";
  338. const apiKeySource = override.apiKeyEnv
  339. ? `env:${override.apiKeyEnv}`
  340. : `base:${base?.apiKey ?? ""}`;
  341. const stream = override.stream ?? base?.stream ?? true;
  342. const apiFormat = base?.apiFormat ?? "chat";
  343. const cacheKey = [
  344. provider,
  345. override.baseUrl,
  346. apiKeySource,
  347. `stream:${stream}`,
  348. `format:${apiFormat}`,
  349. ].join("|");
  350. let client = this.agentClients.get(cacheKey);
  351. if (!client) {
  352. const apiKey = override.apiKeyEnv
  353. ? process.env[override.apiKeyEnv] ?? ""
  354. : base?.apiKey ?? "";
  355. client = createLLMClient({
  356. provider,
  357. baseUrl: override.baseUrl,
  358. apiKey,
  359. model: override.model,
  360. temperature: base?.temperature ?? 0.7,
  361. maxTokens: base?.maxTokens ?? 8192,
  362. thinkingBudget: base?.thinkingBudget ?? 0,
  363. apiFormat,
  364. stream,
  365. });
  366. this.agentClients.set(cacheKey, client);
  367. }
  368. return { model: override.model, client };
  369. }
  370. private agentCtxFor(agent: string, bookId?: string): AgentContext {
  371. const { model, client } = this.resolveOverride(agent);
  372. return {
  373. client,
  374. model,
  375. projectRoot: this.config.projectRoot,
  376. bookId,
  377. logger: this.config.logger?.child(agent),
  378. onStreamProgress: this.config.onStreamProgress,
  379. };
  380. }
  381. private async pathExists(path: string): Promise<boolean> {
  382. try {
  383. await stat(path);
  384. return true;
  385. } catch {
  386. return false;
  387. }
  388. }
  389. private async loadGenreProfile(genre: string): Promise<{ profile: GenreProfile }> {
  390. const parsed = await readGenreProfile(this.config.projectRoot, genre);
  391. return { profile: parsed.profile };
  392. }
  393. // ---------------------------------------------------------------------------
  394. // Atomic operations (composable by OpenClaw or agent mode)
  395. // ---------------------------------------------------------------------------
  396. async runRadar(): Promise<RadarResult> {
  397. const radar = new RadarAgent(this.agentCtxFor("radar"), this.config.radarSources);
  398. return radar.scan();
  399. }
  400. async initBook(book: BookConfig, options: InitBookOptions = {}): Promise<void> {
  401. const architect = new ArchitectAgent(this.agentCtxFor("architect", book.id));
  402. const bookDir = this.state.bookDir(book.id);
  403. const stagingBookDir = join(
  404. this.state.booksDir,
  405. `.tmp-book-create-${book.id}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
  406. );
  407. const stageLanguage = await this.resolveBookLanguage(book);
  408. this.logStage(stageLanguage, { zh: "生成基础设定", en: "generating foundation" });
  409. const { profile: gp } = await this.loadGenreProfile(book.genre);
  410. const reviewer = new FoundationReviewerAgent(this.agentCtxFor("foundation-reviewer", book.id));
  411. const resolvedLanguage = (book.language ?? gp.language) === "en" ? "en" as const : "zh" as const;
  412. const foundation = await this.generateAndReviewFoundation({
  413. generate: (reviewFeedback) => architect.generateFoundation(
  414. book,
  415. options.externalContext ?? this.config.externalContext,
  416. reviewFeedback,
  417. ),
  418. reviewer,
  419. mode: "original",
  420. language: resolvedLanguage,
  421. stageLanguage,
  422. });
  423. try {
  424. this.logStage(stageLanguage, { zh: "保存书籍配置", en: "saving book config" });
  425. await this.state.saveBookConfigAt(stagingBookDir, book);
  426. this.logStage(stageLanguage, { zh: "写入基础设定文件", en: "writing foundation files" });
  427. await architect.writeFoundationFiles(
  428. stagingBookDir,
  429. foundation,
  430. gp.numericalSystem,
  431. book.language ?? gp.language,
  432. );
  433. this.logStage(stageLanguage, { zh: "初始化控制文档", en: "initializing control documents" });
  434. await this.state.ensureControlDocumentsAt(
  435. stagingBookDir,
  436. book.language ?? gp.language,
  437. options.authorIntent ?? this.config.externalContext,
  438. );
  439. if (options.currentFocus?.trim()) {
  440. await writeFile(
  441. join(stagingBookDir, "story", "current_focus.md"),
  442. options.currentFocus.trimEnd() + "\n",
  443. "utf-8",
  444. );
  445. }
  446. await this.state.saveChapterIndexAt(stagingBookDir, []);
  447. this.logStage(stageLanguage, { zh: "创建初始快照", en: "creating initial snapshot" });
  448. await this.state.snapshotStateAt(stagingBookDir, 0);
  449. if (await this.pathExists(bookDir)) {
  450. if (await this.state.isCompleteBookDirectory(bookDir)) {
  451. throw new Error(`Book "${book.id}" already exists at books/${book.id}/. Use a different title or delete the existing book first.`);
  452. }
  453. await rm(bookDir, { recursive: true, force: true });
  454. }
  455. await rename(stagingBookDir, bookDir);
  456. } catch (error) {
  457. await rm(stagingBookDir, { recursive: true, force: true }).catch(() => undefined);
  458. throw error;
  459. }
  460. }
  461. /** Import external source material and generate fanfic_canon.md */
  462. async importFanficCanon(
  463. bookId: string,
  464. sourceText: string,
  465. sourceName: string,
  466. fanficMode: FanficMode,
  467. ): Promise<string> {
  468. const { FanficCanonImporter } = await import("../agents/fanfic-canon-importer.js");
  469. const importer = new FanficCanonImporter(this.agentCtxFor("fanfic-canon-importer", bookId));
  470. const result = await importer.importFromText(sourceText, sourceName, fanficMode);
  471. const bookDir = this.state.bookDir(bookId);
  472. const storyDir = join(bookDir, "story");
  473. await mkdir(storyDir, { recursive: true });
  474. await writeFile(join(storyDir, "fanfic_canon.md"), result.fullDocument, "utf-8");
  475. return result.fullDocument;
  476. }
  477. /** One-step fanfic book creation: create book + import canon + generate foundation */
  478. async initFanficBook(
  479. book: BookConfig,
  480. sourceText: string,
  481. sourceName: string,
  482. fanficMode: FanficMode,
  483. ): Promise<void> {
  484. const bookDir = this.state.bookDir(book.id);
  485. const stageLanguage = await this.resolveBookLanguage(book);
  486. this.logStage(stageLanguage, { zh: "保存书籍配置", en: "saving book config" });
  487. await this.state.saveBookConfig(book.id, book);
  488. // Step 1: Import source material → fanfic_canon.md
  489. this.logStage(stageLanguage, { zh: "导入同人正典", en: "importing fanfic canon" });
  490. const fanficCanon = await this.importFanficCanon(book.id, sourceText, sourceName, fanficMode);
  491. // Step 2: Generate foundation with review loop
  492. const architect = new ArchitectAgent(this.agentCtxFor("architect", book.id));
  493. const reviewer = new FoundationReviewerAgent(this.agentCtxFor("foundation-reviewer", book.id));
  494. this.logStage(stageLanguage, { zh: "生成同人基础设定", en: "generating fanfic foundation" });
  495. const { profile: gp } = await this.loadGenreProfile(book.genre);
  496. const resolvedLanguage = (book.language ?? gp.language) === "en" ? "en" as const : "zh" as const;
  497. const foundation = await this.generateAndReviewFoundation({
  498. generate: (reviewFeedback) => architect.generateFanficFoundation(
  499. book,
  500. fanficCanon,
  501. fanficMode,
  502. reviewFeedback,
  503. ),
  504. reviewer,
  505. mode: "fanfic",
  506. sourceCanon: fanficCanon,
  507. language: resolvedLanguage,
  508. stageLanguage,
  509. });
  510. this.logStage(stageLanguage, { zh: "写入基础设定文件", en: "writing foundation files" });
  511. await architect.writeFoundationFiles(
  512. bookDir,
  513. foundation,
  514. gp.numericalSystem,
  515. book.language ?? gp.language,
  516. );
  517. this.logStage(stageLanguage, { zh: "初始化控制文档", en: "initializing control documents" });
  518. await this.state.ensureControlDocuments(book.id, this.config.externalContext);
  519. // Step 3: Generate style guide from source material
  520. if (sourceText.length >= 500) {
  521. this.logStage(stageLanguage, { zh: "提取原作风格指纹", en: "extracting source style fingerprint" });
  522. await this.tryGenerateStyleGuide(book.id, sourceText, sourceName, stageLanguage);
  523. }
  524. // Step 4: Initialize chapters directory + snapshot
  525. this.logStage(stageLanguage, { zh: "创建初始快照", en: "creating initial snapshot" });
  526. await mkdir(join(bookDir, "chapters"), { recursive: true });
  527. await this.state.saveChapterIndex(book.id, []);
  528. await this.state.snapshotState(book.id, 0);
  529. }
  530. /** Write a single draft chapter. Saves chapter file + truth files + index + snapshot. */
  531. async writeDraft(bookId: string, context?: string, wordCount?: number): Promise<DraftResult> {
  532. const releaseLock = await this.state.acquireBookLock(bookId);
  533. try {
  534. await this.state.ensureControlDocuments(bookId);
  535. const book = await this.state.loadBookConfig(bookId);
  536. const bookDir = this.state.bookDir(bookId);
  537. const chapterNumber = await this.state.getNextChapterNumber(bookId);
  538. const stageLanguage = await this.resolveBookLanguage(book);
  539. this.logStage(stageLanguage, { zh: "准备章节输入", en: "preparing chapter inputs" });
  540. const writeInput = await this.prepareWriteInput(
  541. book,
  542. bookDir,
  543. chapterNumber,
  544. context ?? this.config.externalContext,
  545. );
  546. const { profile: gp } = await this.loadGenreProfile(book.genre);
  547. const lengthSpec = buildLengthSpec(
  548. wordCount ?? book.chapterWordCount,
  549. book.language ?? gp.language,
  550. );
  551. const writer = new WriterAgent(this.agentCtxFor("writer", bookId));
  552. this.logStage(stageLanguage, { zh: "撰写章节草稿", en: "writing chapter draft" });
  553. const output = await writer.writeChapter({
  554. book,
  555. bookDir,
  556. chapterNumber,
  557. ...writeInput,
  558. lengthSpec,
  559. ...(wordCount ? { wordCountOverride: wordCount } : {}),
  560. });
  561. const writerCount = countChapterLength(output.content, lengthSpec.countingMode);
  562. let totalUsage: TokenUsageSummary = output.tokenUsage ?? {
  563. promptTokens: 0,
  564. completionTokens: 0,
  565. totalTokens: 0,
  566. };
  567. const normalizedDraft = await this.normalizeDraftLengthIfNeeded({
  568. bookId,
  569. chapterNumber,
  570. chapterContent: output.content,
  571. lengthSpec,
  572. chapterIntent: writeInput.chapterIntent,
  573. });
  574. totalUsage = PipelineRunner.addUsage(totalUsage, normalizedDraft.tokenUsage);
  575. const draftOutput: WriteChapterOutput = {
  576. ...output,
  577. content: normalizedDraft.content,
  578. wordCount: normalizedDraft.wordCount,
  579. tokenUsage: totalUsage,
  580. };
  581. const lengthWarnings = this.buildLengthWarnings(
  582. chapterNumber,
  583. draftOutput.wordCount,
  584. lengthSpec,
  585. );
  586. const lengthTelemetry = this.buildLengthTelemetry({
  587. lengthSpec,
  588. writerCount,
  589. postWriterNormalizeCount: normalizedDraft.wordCount,
  590. postReviseCount: 0,
  591. finalCount: draftOutput.wordCount,
  592. normalizeApplied: normalizedDraft.applied,
  593. lengthWarning: lengthWarnings.length > 0,
  594. });
  595. this.logLengthWarnings(lengthWarnings);
  596. // Save chapter file
  597. const chaptersDir = join(bookDir, "chapters");
  598. const paddedNum = String(chapterNumber).padStart(4, "0");
  599. const sanitized = draftOutput.title.replace(/[/\\?%*:|"<>]/g, "").replace(/\s+/g, "_").slice(0, 50);
  600. const filename = `${paddedNum}_${sanitized}.md`;
  601. const filePath = join(chaptersDir, filename);
  602. const resolvedLang = book.language ?? gp.language;
  603. const heading = resolvedLang === "en"
  604. ? `# Chapter ${chapterNumber}: ${draftOutput.title}`
  605. : `# 第${chapterNumber}章 ${draftOutput.title}`;
  606. await writeFile(filePath, `${heading}\n\n${draftOutput.content}`, "utf-8");
  607. // Save truth files
  608. this.logStage(stageLanguage, { zh: "落盘草稿与真相文件", en: "persisting draft and truth files" });
  609. await writer.saveChapter(bookDir, draftOutput, gp.numericalSystem, resolvedLang);
  610. await writer.saveNewTruthFiles(bookDir, draftOutput, resolvedLang);
  611. await this.syncLegacyStructuredStateFromMarkdown(bookDir, chapterNumber, draftOutput);
  612. await this.syncNarrativeMemoryIndex(bookId);
  613. // Update index
  614. const existingIndex = await this.state.loadChapterIndex(bookId);
  615. const now = new Date().toISOString();
  616. const newEntry: ChapterMeta = {
  617. number: chapterNumber,
  618. title: draftOutput.title,
  619. status: "drafted",
  620. wordCount: draftOutput.wordCount,
  621. createdAt: now,
  622. updatedAt: now,
  623. auditIssues: [],
  624. lengthWarnings,
  625. lengthTelemetry,
  626. ...(draftOutput.tokenUsage ? { tokenUsage: draftOutput.tokenUsage } : {}),
  627. };
  628. await this.state.saveChapterIndex(bookId, [...existingIndex, newEntry]);
  629. await this.markBookActiveIfNeeded(bookId);
  630. // Snapshot
  631. this.logStage(stageLanguage, { zh: "更新章节索引与快照", en: "updating chapter index and snapshots" });
  632. await this.state.snapshotState(bookId, chapterNumber);
  633. await this.syncCurrentStateFactHistory(bookId, chapterNumber);
  634. await this.emitWebhook("chapter-complete", bookId, chapterNumber, {
  635. title: draftOutput.title,
  636. wordCount: draftOutput.wordCount,
  637. });
  638. return {
  639. chapterNumber,
  640. title: draftOutput.title,
  641. wordCount: draftOutput.wordCount,
  642. filePath,
  643. lengthWarnings,
  644. lengthTelemetry,
  645. tokenUsage: draftOutput.tokenUsage,
  646. };
  647. } finally {
  648. await releaseLock();
  649. }
  650. }
  651. async planChapter(bookId: string, context?: string): Promise<PlanChapterResult> {
  652. await this.state.ensureControlDocuments(bookId);
  653. const book = await this.state.loadBookConfig(bookId);
  654. const bookDir = this.state.bookDir(bookId);
  655. const chapterNumber = await this.state.getNextChapterNumber(bookId);
  656. const stageLanguage = await this.resolveBookLanguage(book);
  657. this.logStage(stageLanguage, { zh: "规划下一章意图", en: "planning next chapter intent" });
  658. const { plan } = await this.createGovernedArtifacts(
  659. book,
  660. bookDir,
  661. chapterNumber,
  662. context ?? this.config.externalContext,
  663. { reuseExistingIntentWhenContextMissing: false },
  664. );
  665. return {
  666. bookId,
  667. chapterNumber,
  668. intentPath: relativeToBookDir(bookDir, plan.runtimePath),
  669. goal: plan.intent.goal,
  670. conflicts: plan.intent.conflicts.map((conflict) => `${conflict.type}: ${conflict.resolution}`),
  671. };
  672. }
  673. async composeChapter(bookId: string, context?: string): Promise<ComposeChapterResult> {
  674. await this.state.ensureControlDocuments(bookId);
  675. const book = await this.state.loadBookConfig(bookId);
  676. const bookDir = this.state.bookDir(bookId);
  677. const chapterNumber = await this.state.getNextChapterNumber(bookId);
  678. const stageLanguage = await this.resolveBookLanguage(book);
  679. this.logStage(stageLanguage, { zh: "组装章节运行时上下文", en: "composing chapter runtime context" });
  680. const { plan, composed } = await this.createGovernedArtifacts(
  681. book,
  682. bookDir,
  683. chapterNumber,
  684. context ?? this.config.externalContext,
  685. { reuseExistingIntentWhenContextMissing: true },
  686. );
  687. return {
  688. bookId,
  689. chapterNumber,
  690. intentPath: relativeToBookDir(bookDir, plan.runtimePath),
  691. goal: plan.intent.goal,
  692. conflicts: plan.intent.conflicts.map((conflict) => `${conflict.type}: ${conflict.resolution}`),
  693. contextPath: relativeToBookDir(bookDir, composed.contextPath),
  694. ruleStackPath: relativeToBookDir(bookDir, composed.ruleStackPath),
  695. tracePath: relativeToBookDir(bookDir, composed.tracePath),
  696. };
  697. }
  698. /** Audit the latest (or specified) chapter. Read-only, no lock needed. */
  699. async auditDraft(bookId: string, chapterNumber?: number): Promise<AuditResult & { readonly chapterNumber: number }> {
  700. const book = await this.state.loadBookConfig(bookId);
  701. const bookDir = this.state.bookDir(bookId);
  702. const targetChapter = chapterNumber ?? (await this.state.getNextChapterNumber(bookId)) - 1;
  703. if (targetChapter < 1) {
  704. throw new Error(`No chapters to audit for "${bookId}"`);
  705. }
  706. const content = await this.readChapterContent(bookDir, targetChapter);
  707. const auditor = new ContinuityAuditor(this.agentCtxFor("auditor", bookId));
  708. const { profile: gp } = await this.loadGenreProfile(book.genre);
  709. const language = book.language ?? gp.language;
  710. this.logStage(language, {
  711. zh: `审计第${targetChapter}章`,
  712. en: `auditing chapter ${targetChapter}`,
  713. });
  714. const evaluation = await this.evaluateMergedAudit({
  715. auditor,
  716. book,
  717. bookDir,
  718. chapterContent: content,
  719. chapterNumber: targetChapter,
  720. language,
  721. });
  722. const result = evaluation.auditResult;
  723. // Update index with audit result
  724. const index = await this.state.loadChapterIndex(bookId);
  725. const updated = index.map((ch) =>
  726. ch.number === targetChapter
  727. ? {
  728. ...ch,
  729. status: (result.passed ? "ready-for-review" : "audit-failed") as ChapterMeta["status"],
  730. updatedAt: new Date().toISOString(),
  731. auditIssues: result.issues.map((i) => `[${i.severity}] ${i.description}`),
  732. }
  733. : ch,
  734. );
  735. await this.state.saveChapterIndex(bookId, updated);
  736. const latestChapter = index.length > 0 ? Math.max(...index.map((chapter) => chapter.number)) : targetChapter;
  737. if (targetChapter === latestChapter) {
  738. await this.persistAuditDriftGuidance({
  739. bookDir,
  740. chapterNumber: targetChapter,
  741. issues: result.issues.filter((issue) => issue.severity === "critical" || issue.severity === "warning"),
  742. language,
  743. }).catch(() => undefined);
  744. }
  745. await this.emitWebhook(
  746. result.passed ? "audit-passed" : "audit-failed",
  747. bookId,
  748. targetChapter,
  749. { summary: result.summary, issueCount: result.issues.length },
  750. );
  751. return { ...result, chapterNumber: targetChapter };
  752. }
  753. /** Revise the latest (or specified) chapter based on audit issues. */
  754. async reviseDraft(bookId: string, chapterNumber?: number, mode: ReviseMode = DEFAULT_REVISE_MODE): Promise<ReviseResult> {
  755. const releaseLock = await this.state.acquireBookLock(bookId);
  756. try {
  757. const book = await this.state.loadBookConfig(bookId);
  758. const bookDir = this.state.bookDir(bookId);
  759. const targetChapter = chapterNumber ?? (await this.state.getNextChapterNumber(bookId)) - 1;
  760. if (targetChapter < 1) {
  761. throw new Error(`No chapters to revise for "${bookId}"`);
  762. }
  763. const stageLanguage = await this.resolveBookLanguage(book);
  764. // Read the current audit issues from index
  765. this.logStage(stageLanguage, {
  766. zh: `加载第${targetChapter}章修订上下文`,
  767. en: `loading revision context for chapter ${targetChapter}`,
  768. });
  769. const index = await this.state.loadChapterIndex(bookId);
  770. const chapterMeta = index.find((ch) => ch.number === targetChapter);
  771. if (!chapterMeta) {
  772. throw new Error(`Chapter ${targetChapter} not found in index`);
  773. }
  774. // Re-audit to get structured issues (index only stores strings)
  775. const content = await this.readChapterContent(bookDir, targetChapter);
  776. const auditor = new ContinuityAuditor(this.agentCtxFor("auditor", bookId));
  777. const { profile: gp } = await this.loadGenreProfile(book.genre);
  778. const language = book.language ?? gp.language;
  779. const countingMode = resolveLengthCountingMode(language);
  780. const reviseControlInput = (this.config.inputGovernanceMode ?? "v2") === "legacy"
  781. ? undefined
  782. : await this.createGovernedArtifacts(
  783. book,
  784. bookDir,
  785. targetChapter,
  786. this.config.externalContext,
  787. { reuseExistingIntentWhenContextMissing: true },
  788. );
  789. const preRevision = await this.evaluateMergedAudit({
  790. auditor,
  791. book,
  792. bookDir,
  793. chapterContent: content,
  794. chapterNumber: targetChapter,
  795. language,
  796. auditOptions: reviseControlInput
  797. ? {
  798. chapterIntent: reviseControlInput.plan.intentMarkdown,
  799. contextPackage: reviseControlInput.composed.contextPackage,
  800. ruleStack: reviseControlInput.composed.ruleStack,
  801. }
  802. : undefined,
  803. });
  804. if (preRevision.blockingCount === 0 && preRevision.aiTellCount === 0) {
  805. return {
  806. chapterNumber: targetChapter,
  807. wordCount: countChapterLength(content, countingMode),
  808. fixedIssues: [],
  809. applied: false,
  810. status: "unchanged",
  811. skippedReason: "No warning, critical, or AI-tell issues to fix.",
  812. };
  813. }
  814. const chapterLengthTarget = chapterMeta.lengthTelemetry?.target ?? book.chapterWordCount;
  815. const lengthLanguage = chapterMeta.lengthTelemetry?.countingMode === "en_words"
  816. ? "en"
  817. : language;
  818. const lengthSpec = buildLengthSpec(
  819. chapterLengthTarget,
  820. lengthLanguage,
  821. );
  822. const reviser = new ReviserAgent(this.agentCtxFor("reviser", bookId));
  823. this.logStage(stageLanguage, {
  824. zh: `修订第${targetChapter}章`,
  825. en: `revising chapter ${targetChapter}`,
  826. });
  827. const reviseOutput = await reviser.reviseChapter(
  828. bookDir,
  829. content,
  830. targetChapter,
  831. preRevision.auditResult.issues,
  832. mode,
  833. book.genre,
  834. reviseControlInput
  835. ? {
  836. chapterIntent: reviseControlInput.plan.intentMarkdown,
  837. contextPackage: reviseControlInput.composed.contextPackage,
  838. ruleStack: reviseControlInput.composed.ruleStack,
  839. lengthSpec,
  840. }
  841. : { lengthSpec },
  842. );
  843. if (reviseOutput.revisedContent.length === 0) {
  844. throw new Error("Reviser returned empty content");
  845. }
  846. const normalizedRevision = await this.normalizeDraftLengthIfNeeded({
  847. bookId,
  848. chapterNumber: targetChapter,
  849. chapterContent: reviseOutput.revisedContent,
  850. lengthSpec,
  851. });
  852. const postRevision = await this.evaluateMergedAudit({
  853. auditor,
  854. book,
  855. bookDir,
  856. chapterContent: normalizedRevision.content,
  857. chapterNumber: targetChapter,
  858. language,
  859. auditOptions: reviseControlInput
  860. ? {
  861. temperature: 0,
  862. chapterIntent: reviseControlInput.plan.intentMarkdown,
  863. contextPackage: reviseControlInput.composed.contextPackage,
  864. ruleStack: reviseControlInput.composed.ruleStack,
  865. truthFileOverrides: {
  866. currentState: reviseOutput.updatedState !== "(状态卡未更新)" ? reviseOutput.updatedState : undefined,
  867. ledger: reviseOutput.updatedLedger !== "(账本未更新)" ? reviseOutput.updatedLedger : undefined,
  868. hooks: reviseOutput.updatedHooks !== "(伏笔池未更新)" ? reviseOutput.updatedHooks : undefined,
  869. },
  870. }
  871. : {
  872. temperature: 0,
  873. truthFileOverrides: {
  874. currentState: reviseOutput.updatedState !== "(状态卡未更新)" ? reviseOutput.updatedState : undefined,
  875. ledger: reviseOutput.updatedLedger !== "(账本未更新)" ? reviseOutput.updatedLedger : undefined,
  876. hooks: reviseOutput.updatedHooks !== "(伏笔池未更新)" ? reviseOutput.updatedHooks : undefined,
  877. },
  878. },
  879. });
  880. const effectivePostRevision = this.restoreActionableAuditIfLost(
  881. preRevision,
  882. postRevision,
  883. );
  884. const revisionBaseCount = countChapterLength(content, lengthSpec.countingMode);
  885. const lengthWarnings = this.buildLengthWarnings(
  886. targetChapter,
  887. normalizedRevision.wordCount,
  888. lengthSpec,
  889. );
  890. const lengthTelemetry = this.buildLengthTelemetry({
  891. lengthSpec,
  892. writerCount: revisionBaseCount,
  893. postWriterNormalizeCount: 0,
  894. postReviseCount: normalizedRevision.wordCount,
  895. finalCount: normalizedRevision.wordCount,
  896. normalizeApplied: normalizedRevision.applied,
  897. lengthWarning: lengthWarnings.length > 0,
  898. });
  899. const improvedBlocking = effectivePostRevision.blockingCount < preRevision.blockingCount;
  900. const improvedAITells = effectivePostRevision.aiTellCount < preRevision.aiTellCount;
  901. const blockingDidNotWorsen = effectivePostRevision.blockingCount <= preRevision.blockingCount;
  902. const criticalDidNotWorsen = effectivePostRevision.criticalCount <= preRevision.criticalCount;
  903. const aiDidNotWorsen = effectivePostRevision.aiTellCount <= preRevision.aiTellCount;
  904. const shouldApplyRevision = blockingDidNotWorsen
  905. && criticalDidNotWorsen
  906. && aiDidNotWorsen
  907. && (improvedBlocking || improvedAITells);
  908. if (!shouldApplyRevision) {
  909. return {
  910. chapterNumber: targetChapter,
  911. wordCount: revisionBaseCount,
  912. fixedIssues: [],
  913. applied: false,
  914. status: "unchanged",
  915. skippedReason: "Manual revision did not improve merged audit or AI-tell metrics; kept original chapter.",
  916. };
  917. }
  918. this.logLengthWarnings(lengthWarnings);
  919. // Save revised chapter file
  920. this.logStage(stageLanguage, {
  921. zh: `落盘第${targetChapter}章修订结果`,
  922. en: `persisting revision for chapter ${targetChapter}`,
  923. });
  924. const chaptersDir = join(bookDir, "chapters");
  925. const files = await readdir(chaptersDir);
  926. const paddedNum = String(targetChapter).padStart(4, "0");
  927. const existingFile = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  928. if (!existingFile) {
  929. throw new Error(`Chapter ${targetChapter} file not found in ${chaptersDir} (expected filename starting with ${paddedNum})`);
  930. }
  931. const reviseLang = book.language ?? gp.language;
  932. const reviseHeading = reviseLang === "en"
  933. ? `# Chapter ${targetChapter}: ${chapterMeta.title}`
  934. : `# 第${targetChapter}章 ${chapterMeta.title}`;
  935. await writeFile(
  936. join(chaptersDir, existingFile),
  937. `${reviseHeading}\n\n${normalizedRevision.content}`,
  938. "utf-8",
  939. );
  940. // Update truth files
  941. const storyDir = join(bookDir, "story");
  942. if (reviseOutput.updatedState !== "(状态卡未更新)") {
  943. await writeFile(join(storyDir, "current_state.md"), reviseOutput.updatedState, "utf-8");
  944. }
  945. if (gp.numericalSystem && reviseOutput.updatedLedger && reviseOutput.updatedLedger !== "(账本未更新)") {
  946. await writeFile(join(storyDir, "particle_ledger.md"), reviseOutput.updatedLedger, "utf-8");
  947. }
  948. if (reviseOutput.updatedHooks !== "(伏笔池未更新)") {
  949. await writeFile(join(storyDir, "pending_hooks.md"), reviseOutput.updatedHooks, "utf-8");
  950. }
  951. await this.syncLegacyStructuredStateFromMarkdown(bookDir, targetChapter);
  952. // Update index
  953. const updatedIndex = index.map((ch) =>
  954. ch.number === targetChapter
  955. ? {
  956. ...ch,
  957. status: (effectivePostRevision.auditResult.passed ? "ready-for-review" : "audit-failed") as ChapterMeta["status"],
  958. wordCount: normalizedRevision.wordCount,
  959. updatedAt: new Date().toISOString(),
  960. auditIssues: effectivePostRevision.auditResult.issues.map((i) => `[${i.severity}] ${i.description}`),
  961. lengthWarnings,
  962. lengthTelemetry,
  963. }
  964. : ch,
  965. );
  966. await this.state.saveChapterIndex(bookId, updatedIndex);
  967. const latestChapter = index.length > 0 ? Math.max(...index.map((chapter) => chapter.number)) : targetChapter;
  968. if (targetChapter === latestChapter) {
  969. await this.persistAuditDriftGuidance({
  970. bookDir,
  971. chapterNumber: targetChapter,
  972. issues: effectivePostRevision.auditResult.issues.filter(
  973. (issue) => issue.severity === "critical" || issue.severity === "warning",
  974. ),
  975. language,
  976. }).catch(() => undefined);
  977. }
  978. // Re-snapshot
  979. this.logStage(stageLanguage, {
  980. zh: `更新第${targetChapter}章索引与快照`,
  981. en: `updating chapter index and snapshots for chapter ${targetChapter}`,
  982. });
  983. await this.state.snapshotState(bookId, targetChapter);
  984. await this.syncNarrativeMemoryIndex(bookId);
  985. await this.syncCurrentStateFactHistory(bookId, targetChapter);
  986. await this.emitWebhook("revision-complete", bookId, targetChapter, {
  987. wordCount: normalizedRevision.wordCount,
  988. fixedCount: reviseOutput.fixedIssues.length,
  989. });
  990. return {
  991. chapterNumber: targetChapter,
  992. wordCount: normalizedRevision.wordCount,
  993. fixedIssues: reviseOutput.fixedIssues,
  994. applied: true,
  995. status: effectivePostRevision.auditResult.passed ? "ready-for-review" : "audit-failed",
  996. lengthWarnings,
  997. lengthTelemetry,
  998. };
  999. } finally {
  1000. await releaseLock();
  1001. }
  1002. }
  1003. /** Read all truth files for a book. */
  1004. async readTruthFiles(bookId: string): Promise<TruthFiles> {
  1005. const bookDir = this.state.bookDir(bookId);
  1006. const storyDir = join(bookDir, "story");
  1007. const readSafe = async (path: string): Promise<string> => {
  1008. try {
  1009. return await readFile(path, "utf-8");
  1010. } catch {
  1011. return "(文件不存在)";
  1012. }
  1013. };
  1014. const [currentState, particleLedger, pendingHooks, storyBible, volumeOutline, bookRules] =
  1015. await Promise.all([
  1016. readSafe(join(storyDir, "current_state.md")),
  1017. readSafe(join(storyDir, "particle_ledger.md")),
  1018. readSafe(join(storyDir, "pending_hooks.md")),
  1019. readSafe(join(storyDir, "story_bible.md")),
  1020. readSafe(join(storyDir, "volume_outline.md")),
  1021. readSafe(join(storyDir, "book_rules.md")),
  1022. ]);
  1023. return { currentState, particleLedger, pendingHooks, storyBible, volumeOutline, bookRules };
  1024. }
  1025. /** Get book status overview. */
  1026. async getBookStatus(bookId: string): Promise<BookStatusInfo> {
  1027. const book = await this.state.loadBookConfig(bookId);
  1028. const chapters = await this.state.loadChapterIndex(bookId);
  1029. const nextChapter = await this.state.getNextChapterNumber(bookId);
  1030. const totalWords = chapters.reduce((sum, ch) => sum + ch.wordCount, 0);
  1031. return {
  1032. bookId,
  1033. title: book.title,
  1034. genre: book.genre,
  1035. platform: book.platform,
  1036. status: book.status,
  1037. chaptersWritten: chapters.length,
  1038. totalWords,
  1039. nextChapter,
  1040. chapters: [...chapters],
  1041. };
  1042. }
  1043. // ---------------------------------------------------------------------------
  1044. // Full pipeline (convenience — runs draft + audit + revise in one shot)
  1045. // ---------------------------------------------------------------------------
  1046. async writeNextChapter(bookId: string, wordCount?: number, temperatureOverride?: number): Promise<ChapterPipelineResult> {
  1047. const releaseLock = await this.state.acquireBookLock(bookId);
  1048. try {
  1049. return await this._writeNextChapterLocked(bookId, wordCount, temperatureOverride);
  1050. } finally {
  1051. await releaseLock();
  1052. }
  1053. }
  1054. async repairChapterState(bookId: string, chapterNumber?: number): Promise<ChapterPipelineResult> {
  1055. const releaseLock = await this.state.acquireBookLock(bookId);
  1056. try {
  1057. return await this._repairChapterStateLocked(bookId, chapterNumber);
  1058. } finally {
  1059. await releaseLock();
  1060. }
  1061. }
  1062. async resyncChapterArtifacts(bookId: string, chapterNumber?: number): Promise<ChapterPipelineResult> {
  1063. const releaseLock = await this.state.acquireBookLock(bookId);
  1064. try {
  1065. return await this._resyncChapterArtifactsLocked(bookId, chapterNumber);
  1066. } finally {
  1067. await releaseLock();
  1068. }
  1069. }
  1070. private async _writeNextChapterLocked(bookId: string, wordCount?: number, temperatureOverride?: number): Promise<ChapterPipelineResult> {
  1071. await this.state.ensureControlDocuments(bookId);
  1072. const book = await this.state.loadBookConfig(bookId);
  1073. const bookDir = this.state.bookDir(bookId);
  1074. await this.assertNoPendingStateRepair(bookId);
  1075. const chapterNumber = await this.state.getNextChapterNumber(bookId);
  1076. const stageLanguage = await this.resolveBookLanguage(book);
  1077. this.logStage(stageLanguage, { zh: "准备章节输入", en: "preparing chapter inputs" });
  1078. const writeInput = await this.prepareWriteInput(
  1079. book,
  1080. bookDir,
  1081. chapterNumber,
  1082. this.config.externalContext,
  1083. );
  1084. const reducedControlInput = writeInput.chapterIntent && writeInput.contextPackage && writeInput.ruleStack
  1085. ? {
  1086. chapterIntent: writeInput.chapterIntent,
  1087. contextPackage: writeInput.contextPackage,
  1088. ruleStack: writeInput.ruleStack,
  1089. }
  1090. : undefined;
  1091. const { profile: gp } = await this.loadGenreProfile(book.genre);
  1092. const pipelineLang = book.language ?? gp.language;
  1093. const lengthSpec = buildLengthSpec(
  1094. wordCount ?? book.chapterWordCount,
  1095. pipelineLang,
  1096. );
  1097. // 1. Write chapter
  1098. const writer = new WriterAgent(this.agentCtxFor("writer", bookId));
  1099. this.logStage(stageLanguage, { zh: "撰写章节草稿", en: "writing chapter draft" });
  1100. const output = await writer.writeChapter({
  1101. book,
  1102. bookDir,
  1103. chapterNumber,
  1104. ...writeInput,
  1105. lengthSpec,
  1106. ...(wordCount ? { wordCountOverride: wordCount } : {}),
  1107. ...(temperatureOverride ? { temperatureOverride } : {}),
  1108. });
  1109. const writerCount = countChapterLength(output.content, lengthSpec.countingMode);
  1110. // Token usage accumulator
  1111. let totalUsage: TokenUsageSummary = output.tokenUsage ?? { promptTokens: 0, completionTokens: 0, totalTokens: 0 };
  1112. const auditor = new ContinuityAuditor(this.agentCtxFor("auditor", bookId));
  1113. const reviewResult = await runChapterReviewCycle({
  1114. book: { genre: book.genre },
  1115. bookDir,
  1116. chapterNumber,
  1117. initialOutput: output,
  1118. reducedControlInput,
  1119. lengthSpec,
  1120. initialUsage: totalUsage,
  1121. createReviser: () => new ReviserAgent(this.agentCtxFor("reviser", bookId)),
  1122. auditor,
  1123. normalizeDraftLengthIfNeeded: (chapterContent) => this.normalizeDraftLengthIfNeeded({
  1124. bookId,
  1125. chapterNumber,
  1126. chapterContent,
  1127. lengthSpec,
  1128. chapterIntent: writeInput.chapterIntent,
  1129. }),
  1130. assertChapterContentNotEmpty: (content, stage) =>
  1131. this.assertChapterContentNotEmpty(content, chapterNumber, stage),
  1132. addUsage: PipelineRunner.addUsage,
  1133. restoreLostAuditIssues: (previous, next) => this.restoreLostAuditIssues(previous, next),
  1134. analyzeAITells,
  1135. analyzeSensitiveWords,
  1136. logWarn: (message) => this.logWarn(pipelineLang, message),
  1137. logStage: (message) => this.logStage(stageLanguage, message),
  1138. });
  1139. totalUsage = reviewResult.totalUsage;
  1140. let finalContent = reviewResult.finalContent;
  1141. let finalWordCount = reviewResult.finalWordCount;
  1142. let revised = reviewResult.revised;
  1143. let auditResult = reviewResult.auditResult;
  1144. const postReviseCount = reviewResult.postReviseCount;
  1145. const normalizeApplied = reviewResult.normalizeApplied;
  1146. // 4. Save the final chapter and truth files from a single persistence source
  1147. this.logStage(stageLanguage, { zh: "落盘最终章节", en: "persisting final chapter" });
  1148. this.logStage(stageLanguage, { zh: "生成最终真相文件", en: "rebuilding final truth files" });
  1149. const chapterIndexBeforePersist = await this.state.loadChapterIndex(bookId);
  1150. const { resolveDuplicateTitle } = await import("../agents/post-write-validator.js");
  1151. const initialTitleResolution = resolveDuplicateTitle(
  1152. output.title,
  1153. chapterIndexBeforePersist.map((chapter) => chapter.title),
  1154. pipelineLang,
  1155. { content: finalContent },
  1156. );
  1157. let persistenceOutput = await this.buildPersistenceOutput(
  1158. bookId,
  1159. book,
  1160. bookDir,
  1161. chapterNumber,
  1162. initialTitleResolution.title === output.title
  1163. ? output
  1164. : { ...output, title: initialTitleResolution.title },
  1165. finalContent,
  1166. lengthSpec.countingMode,
  1167. reducedControlInput,
  1168. );
  1169. const finalTitleResolution = resolveDuplicateTitle(
  1170. persistenceOutput.title,
  1171. chapterIndexBeforePersist.map((chapter) => chapter.title),
  1172. pipelineLang,
  1173. { content: finalContent },
  1174. );
  1175. if (finalTitleResolution.title !== persistenceOutput.title) {
  1176. persistenceOutput = {
  1177. ...persistenceOutput,
  1178. title: finalTitleResolution.title,
  1179. };
  1180. }
  1181. if (persistenceOutput.title !== output.title) {
  1182. const description = pipelineLang === "en"
  1183. ? `Chapter title "${output.title}" was auto-adjusted to "${persistenceOutput.title}".`
  1184. : `章节标题"${output.title}"已自动调整为"${persistenceOutput.title}"。`;
  1185. this.config.logger?.warn(`[title] ${description}`);
  1186. auditResult = {
  1187. ...auditResult,
  1188. issues: [...auditResult.issues, {
  1189. severity: "warning",
  1190. category: "title-dedup",
  1191. description,
  1192. suggestion: pipelineLang === "en"
  1193. ? "If the auto-renamed title is weak, revise the chapter title manually."
  1194. : "如果自动改名不理想,可以在后续手动修订章节标题。",
  1195. }],
  1196. };
  1197. }
  1198. const longSpanFatigue = await analyzeLongSpanFatigue({
  1199. bookDir,
  1200. chapterNumber,
  1201. chapterContent: finalContent,
  1202. chapterSummary: persistenceOutput.chapterSummary,
  1203. language: pipelineLang,
  1204. });
  1205. auditResult = {
  1206. ...auditResult,
  1207. issues: [
  1208. ...auditResult.issues,
  1209. ...longSpanFatigue.issues,
  1210. ...(persistenceOutput.hookHealthIssues ?? []),
  1211. ],
  1212. };
  1213. finalWordCount = persistenceOutput.wordCount;
  1214. const lengthWarnings = this.buildLengthWarnings(
  1215. chapterNumber,
  1216. finalWordCount,
  1217. lengthSpec,
  1218. );
  1219. const lengthTelemetry = this.buildLengthTelemetry({
  1220. lengthSpec,
  1221. writerCount,
  1222. postWriterNormalizeCount: reviewResult.preAuditNormalizedWordCount,
  1223. postReviseCount,
  1224. finalCount: finalWordCount,
  1225. normalizeApplied,
  1226. lengthWarning: lengthWarnings.length > 0,
  1227. });
  1228. this.logLengthWarnings(lengthWarnings);
  1229. // 4.1 Validate settler output before writing
  1230. this.logStage(stageLanguage, { zh: "校验真相文件变更", en: "validating truth file updates" });
  1231. const storyDir = join(bookDir, "story");
  1232. const [oldState, oldHooks, oldLedger] = await Promise.all([
  1233. readFile(join(storyDir, "current_state.md"), "utf-8").catch(() => ""),
  1234. readFile(join(storyDir, "pending_hooks.md"), "utf-8").catch(() => ""),
  1235. readFile(join(storyDir, "particle_ledger.md"), "utf-8").catch(() => ""),
  1236. ]);
  1237. const validator = new StateValidatorAgent(this.agentCtxFor("state-validator", bookId));
  1238. const truthValidation = await validateChapterTruthPersistence({
  1239. writer,
  1240. validator,
  1241. book,
  1242. bookDir,
  1243. chapterNumber,
  1244. title: persistenceOutput.title,
  1245. content: finalContent,
  1246. persistenceOutput,
  1247. auditResult,
  1248. previousTruth: {
  1249. oldState,
  1250. oldHooks,
  1251. oldLedger,
  1252. },
  1253. reducedControlInput,
  1254. language: pipelineLang,
  1255. logWarn: (message) => this.logWarn(pipelineLang, message),
  1256. logger: this.config.logger,
  1257. });
  1258. let chapterStatus: ChapterPipelineResult["status"] | null = truthValidation.chapterStatus;
  1259. let degradedIssues: ReadonlyArray<AuditIssue> = truthValidation.degradedIssues;
  1260. persistenceOutput = truthValidation.persistenceOutput;
  1261. auditResult = truthValidation.auditResult;
  1262. // 4.2 Final paragraph shape check on persisted content (post-normalize, post-revise)
  1263. {
  1264. const {
  1265. detectParagraphLengthDrift,
  1266. detectParagraphShapeWarnings,
  1267. } = await import("../agents/post-write-validator.js");
  1268. const chapDir = join(bookDir, "chapters");
  1269. const recentFiles = (await readdir(chapDir).catch(() => [] as string[]))
  1270. .filter((f) => f.endsWith(".md") && /^\d{4}/.test(f))
  1271. .sort()
  1272. .slice(-5);
  1273. const recentContent = (await Promise.all(
  1274. recentFiles.map((f) => readFile(join(chapDir, f), "utf-8").catch(() => "")),
  1275. )).join("\n\n");
  1276. const paragraphIssues = [
  1277. ...detectParagraphShapeWarnings(finalContent, pipelineLang),
  1278. ...detectParagraphLengthDrift(finalContent, recentContent, pipelineLang),
  1279. ];
  1280. if (paragraphIssues.length > 0) {
  1281. for (const issue of paragraphIssues) {
  1282. this.config.logger?.warn(`[paragraph] ${issue.description}`);
  1283. }
  1284. auditResult = {
  1285. ...auditResult,
  1286. issues: [...auditResult.issues, ...paragraphIssues.map((v) => ({
  1287. severity: v.severity as "warning",
  1288. category: "paragraph-shape",
  1289. description: v.description,
  1290. suggestion: v.suggestion,
  1291. }))],
  1292. };
  1293. }
  1294. }
  1295. const resolvedStatus = chapterStatus ?? (auditResult.passed ? "ready-for-review" : "audit-failed");
  1296. await persistChapterArtifacts({
  1297. chapterNumber,
  1298. chapterTitle: persistenceOutput.title,
  1299. status: resolvedStatus,
  1300. auditResult,
  1301. finalWordCount,
  1302. lengthWarnings,
  1303. lengthTelemetry,
  1304. degradedIssues,
  1305. tokenUsage: totalUsage,
  1306. loadChapterIndex: () => this.state.loadChapterIndex(bookId),
  1307. saveChapter: () => writer.saveChapter(bookDir, persistenceOutput, gp.numericalSystem, pipelineLang),
  1308. saveTruthFiles: async () => {
  1309. await writer.saveNewTruthFiles(bookDir, persistenceOutput, pipelineLang);
  1310. await this.syncLegacyStructuredStateFromMarkdown(bookDir, chapterNumber, persistenceOutput);
  1311. this.logStage(stageLanguage, { zh: "同步记忆索引", en: "syncing memory indexes" });
  1312. await this.syncNarrativeMemoryIndex(bookId);
  1313. },
  1314. saveChapterIndex: (index) => this.state.saveChapterIndex(bookId, index),
  1315. markBookActiveIfNeeded: () => this.markBookActiveIfNeeded(bookId),
  1316. persistAuditDriftGuidance: (issues) => this.persistAuditDriftGuidance({
  1317. bookDir,
  1318. chapterNumber,
  1319. issues,
  1320. language: stageLanguage,
  1321. }).catch(() => undefined),
  1322. snapshotState: () => this.state.snapshotState(bookId, chapterNumber),
  1323. syncCurrentStateFactHistory: () => this.syncCurrentStateFactHistory(bookId, chapterNumber),
  1324. logSnapshotStage: () =>
  1325. this.logStage(stageLanguage, { zh: "更新章节索引与快照", en: "updating chapter index and snapshots" }),
  1326. });
  1327. // 6. Send notification
  1328. if (this.config.notifyChannels && this.config.notifyChannels.length > 0) {
  1329. const statusEmoji = resolvedStatus === "state-degraded"
  1330. ? "🧯"
  1331. : auditResult.passed ? "✅" : "⚠️";
  1332. const chapterLength = formatLengthCount(finalWordCount, lengthSpec.countingMode);
  1333. await dispatchNotification(this.config.notifyChannels, {
  1334. title: `${statusEmoji} ${book.title} 第${chapterNumber}章`,
  1335. body: [
  1336. `**${persistenceOutput.title}** | ${chapterLength}`,
  1337. revised ? "📝 已自动修正" : "",
  1338. resolvedStatus === "state-degraded"
  1339. ? "状态结算: 已降级保存,需先修复 state 再继续"
  1340. : `审稿: ${auditResult.passed ? "通过" : "需人工审核"}`,
  1341. ...auditResult.issues
  1342. .filter((i) => i.severity !== "info")
  1343. .map((i) => `- [${i.severity}] ${i.description}`),
  1344. ]
  1345. .filter(Boolean)
  1346. .join("\n"),
  1347. });
  1348. }
  1349. await this.emitWebhook("pipeline-complete", bookId, chapterNumber, {
  1350. title: persistenceOutput.title,
  1351. wordCount: finalWordCount,
  1352. passed: auditResult.passed,
  1353. revised,
  1354. status: resolvedStatus,
  1355. });
  1356. return {
  1357. chapterNumber,
  1358. title: persistenceOutput.title,
  1359. wordCount: finalWordCount,
  1360. auditResult,
  1361. revised,
  1362. status: resolvedStatus,
  1363. lengthWarnings,
  1364. lengthTelemetry,
  1365. tokenUsage: totalUsage,
  1366. };
  1367. }
  1368. private async _repairChapterStateLocked(bookId: string, chapterNumber?: number): Promise<ChapterPipelineResult> {
  1369. const book = await this.state.loadBookConfig(bookId);
  1370. const bookDir = this.state.bookDir(bookId);
  1371. const stageLanguage = await this.resolveBookLanguage(book);
  1372. const index = [...(await this.state.loadChapterIndex(bookId))];
  1373. if (index.length === 0) {
  1374. throw new Error(`Book "${bookId}" has no persisted chapters to repair.`);
  1375. }
  1376. const targetChapter = chapterNumber ?? index[index.length - 1]!.number;
  1377. const targetIndex = index.findIndex((chapter) => chapter.number === targetChapter);
  1378. if (targetIndex < 0) {
  1379. throw new Error(`Chapter ${targetChapter} not found in "${bookId}".`);
  1380. }
  1381. const targetMeta = index[targetIndex]!;
  1382. const latestChapter = Math.max(...index.map((chapter) => chapter.number));
  1383. if (targetMeta.status !== "state-degraded") {
  1384. throw new Error(`Chapter ${targetChapter} is not state-degraded.`);
  1385. }
  1386. if (targetChapter !== latestChapter) {
  1387. throw new Error(`Only the latest state-degraded chapter can be repaired safely (latest is ${latestChapter}).`);
  1388. }
  1389. this.logStage(stageLanguage, { zh: "修复章节状态结算", en: "repairing chapter state settlement" });
  1390. const { profile: gp } = await this.loadGenreProfile(book.genre);
  1391. const pipelineLang = book.language ?? gp.language;
  1392. const content = await this.readChapterContent(bookDir, targetChapter);
  1393. const storyDir = join(bookDir, "story");
  1394. const [oldState, oldHooks] = await Promise.all([
  1395. readFile(join(storyDir, "current_state.md"), "utf-8").catch(() => ""),
  1396. readFile(join(storyDir, "pending_hooks.md"), "utf-8").catch(() => ""),
  1397. ]);
  1398. const writer = new WriterAgent(this.agentCtxFor("writer", bookId));
  1399. let repairedOutput = await writer.settleChapterState({
  1400. book,
  1401. bookDir,
  1402. chapterNumber: targetChapter,
  1403. title: targetMeta.title,
  1404. content,
  1405. allowReapply: true,
  1406. });
  1407. const validator = new StateValidatorAgent(this.agentCtxFor("state-validator", bookId));
  1408. let validation = await validator.validate(
  1409. content,
  1410. targetChapter,
  1411. oldState,
  1412. repairedOutput.updatedState,
  1413. oldHooks,
  1414. repairedOutput.updatedHooks,
  1415. pipelineLang,
  1416. );
  1417. if (!validation.passed) {
  1418. const recovery = await retrySettlementAfterValidationFailure({
  1419. writer,
  1420. validator,
  1421. book,
  1422. bookDir,
  1423. chapterNumber: targetChapter,
  1424. title: targetMeta.title,
  1425. content,
  1426. oldState,
  1427. oldHooks,
  1428. originalValidation: validation,
  1429. language: pipelineLang,
  1430. logWarn: (message) => this.logWarn(pipelineLang, message),
  1431. logger: this.config.logger,
  1432. });
  1433. if (recovery.kind !== "recovered") {
  1434. throw new Error(
  1435. recovery.issues[0]?.description
  1436. ?? `State repair still failed for chapter ${targetChapter}.`,
  1437. );
  1438. }
  1439. repairedOutput = recovery.output;
  1440. validation = recovery.validation;
  1441. }
  1442. if (!validation.passed) {
  1443. throw new Error(`State repair still failed for chapter ${targetChapter}.`);
  1444. }
  1445. await writer.saveChapter(bookDir, repairedOutput, gp.numericalSystem, pipelineLang);
  1446. await writer.saveNewTruthFiles(bookDir, repairedOutput, pipelineLang);
  1447. await this.syncLegacyStructuredStateFromMarkdown(bookDir, targetChapter, repairedOutput);
  1448. await this.syncNarrativeMemoryIndex(bookId);
  1449. await this.state.snapshotState(bookId, targetChapter);
  1450. await this.syncCurrentStateFactHistory(bookId, targetChapter);
  1451. const baseStatus = resolveStateDegradedBaseStatus(targetMeta);
  1452. const degradedMetadata = parseStateDegradedReviewNote(targetMeta.reviewNote);
  1453. const injectedIssues = new Set(degradedMetadata?.injectedIssues ?? []);
  1454. index[targetIndex] = {
  1455. ...targetMeta,
  1456. status: baseStatus,
  1457. updatedAt: new Date().toISOString(),
  1458. auditIssues: targetMeta.auditIssues.filter((issue) => !injectedIssues.has(issue)),
  1459. reviewNote: undefined,
  1460. };
  1461. await this.state.saveChapterIndex(bookId, index);
  1462. const repairedPassesAudit = baseStatus !== "audit-failed";
  1463. return {
  1464. chapterNumber: targetChapter,
  1465. title: targetMeta.title,
  1466. wordCount: targetMeta.wordCount,
  1467. auditResult: {
  1468. passed: repairedPassesAudit,
  1469. issues: [],
  1470. summary: repairedPassesAudit ? "state repaired" : "state repaired but chapter still needs review",
  1471. },
  1472. revised: false,
  1473. status: baseStatus,
  1474. lengthWarnings: targetMeta.lengthWarnings,
  1475. lengthTelemetry: targetMeta.lengthTelemetry,
  1476. tokenUsage: targetMeta.tokenUsage,
  1477. };
  1478. }
  1479. private async _resyncChapterArtifactsLocked(bookId: string, chapterNumber?: number): Promise<ChapterPipelineResult> {
  1480. const book = await this.state.loadBookConfig(bookId);
  1481. const bookDir = this.state.bookDir(bookId);
  1482. const stageLanguage = await this.resolveBookLanguage(book);
  1483. const index = [...(await this.state.loadChapterIndex(bookId))];
  1484. if (index.length === 0) {
  1485. throw new Error(`Book "${bookId}" has no persisted chapters to sync.`);
  1486. }
  1487. const targetChapter = chapterNumber ?? index[index.length - 1]!.number;
  1488. const targetIndex = index.findIndex((chapter) => chapter.number === targetChapter);
  1489. if (targetIndex < 0) {
  1490. throw new Error(`Chapter ${targetChapter} not found in "${bookId}".`);
  1491. }
  1492. const targetMeta = index[targetIndex]!;
  1493. const latestChapter = Math.max(...index.map((chapter) => chapter.number));
  1494. if (targetChapter !== latestChapter) {
  1495. throw new Error(`Only the latest persisted chapter can be synced safely (latest is ${latestChapter}).`);
  1496. }
  1497. this.logStage(stageLanguage, { zh: "根据已编辑正文同步真相文件与索引", en: "syncing truth files and indexes from edited chapter body" });
  1498. const { profile: gp } = await this.loadGenreProfile(book.genre);
  1499. const pipelineLang = book.language ?? gp.language;
  1500. const content = await this.readChapterContent(bookDir, targetChapter);
  1501. const storyDir = join(bookDir, "story");
  1502. const [oldState, oldHooks] = await Promise.all([
  1503. readFile(join(storyDir, "current_state.md"), "utf-8").catch(() => ""),
  1504. readFile(join(storyDir, "pending_hooks.md"), "utf-8").catch(() => ""),
  1505. ]);
  1506. const reducedControlInput = (this.config.inputGovernanceMode ?? "v2") === "legacy"
  1507. ? undefined
  1508. : await this.createGovernedArtifacts(
  1509. book,
  1510. bookDir,
  1511. targetChapter,
  1512. this.config.externalContext,
  1513. { reuseExistingIntentWhenContextMissing: true },
  1514. );
  1515. const writer = new WriterAgent(this.agentCtxFor("writer", bookId));
  1516. let syncedOutput = await writer.settleChapterState({
  1517. book,
  1518. bookDir,
  1519. chapterNumber: targetChapter,
  1520. title: targetMeta.title,
  1521. content,
  1522. chapterIntent: reducedControlInput?.plan.intentMarkdown,
  1523. contextPackage: reducedControlInput?.composed.contextPackage,
  1524. ruleStack: reducedControlInput?.composed.ruleStack,
  1525. allowReapply: true,
  1526. });
  1527. const validator = new StateValidatorAgent(this.agentCtxFor("state-validator", bookId));
  1528. let validation = await validator.validate(
  1529. content,
  1530. targetChapter,
  1531. oldState,
  1532. syncedOutput.updatedState,
  1533. oldHooks,
  1534. syncedOutput.updatedHooks,
  1535. pipelineLang,
  1536. );
  1537. if (!validation.passed) {
  1538. const recovery = await retrySettlementAfterValidationFailure({
  1539. writer,
  1540. validator,
  1541. book,
  1542. bookDir,
  1543. chapterNumber: targetChapter,
  1544. title: targetMeta.title,
  1545. content,
  1546. reducedControlInput: reducedControlInput
  1547. ? {
  1548. chapterIntent: reducedControlInput.plan.intentMarkdown,
  1549. contextPackage: reducedControlInput.composed.contextPackage,
  1550. ruleStack: reducedControlInput.composed.ruleStack,
  1551. }
  1552. : undefined,
  1553. oldState,
  1554. oldHooks,
  1555. originalValidation: validation,
  1556. language: pipelineLang,
  1557. logWarn: (message) => this.logWarn(pipelineLang, message),
  1558. logger: this.config.logger,
  1559. });
  1560. if (recovery.kind !== "recovered") {
  1561. throw new Error(
  1562. recovery.issues[0]?.description
  1563. ?? `Chapter sync still failed for chapter ${targetChapter}.`,
  1564. );
  1565. }
  1566. syncedOutput = recovery.output;
  1567. validation = recovery.validation;
  1568. }
  1569. if (!validation.passed) {
  1570. throw new Error(`Chapter sync still failed for chapter ${targetChapter}.`);
  1571. }
  1572. await writer.saveChapter(bookDir, syncedOutput, gp.numericalSystem, pipelineLang);
  1573. await writer.saveNewTruthFiles(bookDir, syncedOutput, pipelineLang);
  1574. await this.syncLegacyStructuredStateFromMarkdown(bookDir, targetChapter, syncedOutput);
  1575. await this.syncNarrativeMemoryIndex(bookId);
  1576. await this.state.snapshotState(bookId, targetChapter);
  1577. await this.syncCurrentStateFactHistory(bookId, targetChapter);
  1578. const finalStatus: "ready-for-review" | "audit-failed" = targetMeta.status === "state-degraded"
  1579. ? resolveStateDegradedBaseStatus(targetMeta)
  1580. : "ready-for-review";
  1581. if (targetMeta.status === "state-degraded") {
  1582. const degradedMetadata = parseStateDegradedReviewNote(targetMeta.reviewNote);
  1583. const injectedIssues = new Set(degradedMetadata?.injectedIssues ?? []);
  1584. index[targetIndex] = {
  1585. ...targetMeta,
  1586. status: finalStatus,
  1587. updatedAt: new Date().toISOString(),
  1588. auditIssues: targetMeta.auditIssues.filter((issue) => !injectedIssues.has(issue)),
  1589. reviewNote: undefined,
  1590. };
  1591. } else {
  1592. index[targetIndex] = {
  1593. ...targetMeta,
  1594. status: "ready-for-review",
  1595. updatedAt: new Date().toISOString(),
  1596. };
  1597. }
  1598. await this.state.saveChapterIndex(bookId, index);
  1599. return {
  1600. chapterNumber: targetChapter,
  1601. title: targetMeta.title,
  1602. wordCount: targetMeta.wordCount,
  1603. auditResult: {
  1604. passed: finalStatus !== "audit-failed",
  1605. issues: [],
  1606. summary: finalStatus === "audit-failed"
  1607. ? "chapter truth/state resynced from edited body, but chapter still needs audit fixes"
  1608. : "chapter truth/state resynced from edited body",
  1609. },
  1610. revised: false,
  1611. status: finalStatus,
  1612. lengthWarnings: targetMeta.lengthWarnings,
  1613. lengthTelemetry: targetMeta.lengthTelemetry,
  1614. tokenUsage: targetMeta.tokenUsage,
  1615. };
  1616. }
  1617. // ---------------------------------------------------------------------------
  1618. // Import operations (style imitation + canon for spinoff)
  1619. // ---------------------------------------------------------------------------
  1620. /**
  1621. * Generate a qualitative style guide from reference text via LLM.
  1622. * Also saves the statistical style_profile.json.
  1623. */
  1624. async generateStyleGuide(bookId: string, referenceText: string, sourceName?: string): Promise<string> {
  1625. if (referenceText.length < 500) {
  1626. throw new Error(`Reference text too short (${referenceText.length} chars, minimum 500). Provide at least 2000 chars for reliable style extraction.`);
  1627. }
  1628. const { analyzeStyle } = await import("../agents/style-analyzer.js");
  1629. const bookDir = this.state.bookDir(bookId);
  1630. const storyDir = join(bookDir, "story");
  1631. await mkdir(storyDir, { recursive: true });
  1632. // Statistical fingerprint
  1633. const profile = analyzeStyle(referenceText, sourceName);
  1634. await writeFile(join(storyDir, "style_profile.json"), JSON.stringify(profile, null, 2), "utf-8");
  1635. // LLM qualitative extraction
  1636. const response = await chatCompletion(this.config.client, this.config.model, [
  1637. {
  1638. role: "system",
  1639. content: `你是一位文学风格分析专家。分析参考文本的写作风格,提取可供模仿的定性特征。
  1640. 输出格式(Markdown):
  1641. ## 叙事声音与语气
  1642. (冷峻/热烈/讽刺/温情/...,附1-2个原文例句)
  1643. ## 对话风格
  1644. (角色说话的共性特征:句子长短、口头禅倾向、方言痕迹、对话节奏)
  1645. ## 场景描写特征
  1646. (五感偏好、意象选择、描写密度、环境与情绪的关联方式)
  1647. ## 转折与衔接手法
  1648. (场景如何切换、时间跳跃的处理方式、段落间的过渡特征)
  1649. ## 节奏特征
  1650. (长短句分布、段落长度偏好、高潮/舒缓的交替方式)
  1651. ## 词汇偏好
  1652. (高频特色用词、比喻/修辞倾向、口语化程度)
  1653. ## 情绪表达方式
  1654. (直白抒情 vs 动作外化、内心独白的频率和风格)
  1655. ## 独特习惯
  1656. (任何值得模仿的个人写作习惯)
  1657. 分析必须基于原文实际特征,不要泛泛而谈。每个部分用1-2个原文例句佐证。`,
  1658. },
  1659. {
  1660. role: "user",
  1661. content: `分析以下参考文本的写作风格:\n\n${referenceText.slice(0, 20000)}`,
  1662. },
  1663. ], { temperature: 0.3, maxTokens: 4096 });
  1664. await writeFile(join(storyDir, "style_guide.md"), response.content, "utf-8");
  1665. return response.content;
  1666. }
  1667. /**
  1668. * Import canon from parent book for spinoff writing.
  1669. * Reads parent's truth files, uses LLM to generate parent_canon.md in target book.
  1670. */
  1671. async importCanon(targetBookId: string, parentBookId: string): Promise<string> {
  1672. // Validate both books exist
  1673. const bookIds = await this.state.listBooks();
  1674. if (!bookIds.includes(parentBookId)) {
  1675. throw new Error(`Parent book "${parentBookId}" not found. Available: ${bookIds.join(", ") || "(none)"}`);
  1676. }
  1677. if (!bookIds.includes(targetBookId)) {
  1678. throw new Error(`Target book "${targetBookId}" not found. Available: ${bookIds.join(", ") || "(none)"}`);
  1679. }
  1680. const parentDir = this.state.bookDir(parentBookId);
  1681. const targetDir = this.state.bookDir(targetBookId);
  1682. const storyDir = join(targetDir, "story");
  1683. await mkdir(storyDir, { recursive: true });
  1684. const readSafe = async (path: string): Promise<string> => {
  1685. try { return await readFile(path, "utf-8"); } catch { return "(无)"; }
  1686. };
  1687. const parentBook = await this.state.loadBookConfig(parentBookId);
  1688. const [storyBible, currentState, ledger, hooks, summaries, subplots, emotions, matrix] =
  1689. await Promise.all([
  1690. readSafe(join(parentDir, "story/story_bible.md")),
  1691. readSafe(join(parentDir, "story/current_state.md")),
  1692. readSafe(join(parentDir, "story/particle_ledger.md")),
  1693. readSafe(join(parentDir, "story/pending_hooks.md")),
  1694. readSafe(join(parentDir, "story/chapter_summaries.md")),
  1695. readSafe(join(parentDir, "story/subplot_board.md")),
  1696. readSafe(join(parentDir, "story/emotional_arcs.md")),
  1697. readSafe(join(parentDir, "story/character_matrix.md")),
  1698. ]);
  1699. const response = await chatCompletion(this.config.client, this.config.model, [
  1700. {
  1701. role: "system",
  1702. content: `你是一位网络小说架构师。基于正传的全部设定和状态文件,生成一份完整的"正传正典参照"文档,供番外写作和审计使用。
  1703. 输出格式(Markdown):
  1704. # 正传正典(《{正传书名}》)
  1705. ## 世界规则(完整,来自正传设定)
  1706. (力量体系、地理设定、阵营关系、核心规则——完整复制,不压缩)
  1707. ## 正典约束(不可违反的事实)
  1708. | 约束ID | 类型 | 约束内容 | 严重性 |
  1709. |---|---|---|---|
  1710. | C01 | 人物存亡 | ... | critical |
  1711. (列出所有硬性约束:谁活着、谁死了、什么事件已经发生、什么规则不可违反)
  1712. ## 角色快照
  1713. | 角色 | 当前状态 | 性格底色 | 对话特征 | 已知信息 | 未知信息 |
  1714. |---|---|---|---|---|---|
  1715. (从状态卡和角色矩阵中提取每个重要角色的完整快照)
  1716. ## 角色双态处理原则
  1717. - 未来会变强的角色:写潜力暗示
  1718. - 未来会黑化的角色:写微小裂痕
  1719. - 未来会死的角色:写导致死亡的性格底色
  1720. ## 关键事件时间线
  1721. | 章节 | 事件 | 涉及角色 | 对番外的约束 |
  1722. |---|---|---|---|
  1723. (从章节摘要中提取关键事件)
  1724. ## 伏笔状态
  1725. | Hook ID | 类型 | 状态 | 内容 | 预期回收 |
  1726. |---|---|---|---|---|
  1727. ## 资源账本快照
  1728. (当前资源状态)
  1729. ---
  1730. meta:
  1731. parentBookId: "{parentBookId}"
  1732. parentTitle: "{正传书名}"
  1733. generatedAt: "{ISO timestamp}"
  1734. 要求:
  1735. 1. 世界规则完整复制,不压缩——准确性优先
  1736. 2. 正典约束必须穷尽,遗漏会导致番外与正传矛盾
  1737. 3. 角色快照必须包含信息边界(已知/未知),防止番外中角色引用不该知道的信息`,
  1738. },
  1739. {
  1740. role: "user",
  1741. content: `正传书名:${parentBook.title}
  1742. 正传ID:${parentBookId}
  1743. ## 正传世界设定
  1744. ${storyBible}
  1745. ## 正传当前状态卡
  1746. ${currentState}
  1747. ## 正传资源账本
  1748. ${ledger}
  1749. ## 正传伏笔池
  1750. ${hooks}
  1751. ## 正传章节摘要
  1752. ${summaries}
  1753. ## 正传支线进度
  1754. ${subplots}
  1755. ## 正传情感弧线
  1756. ${emotions}
  1757. ## 正传角色矩阵
  1758. ${matrix}`,
  1759. },
  1760. ], { temperature: 0.3, maxTokens: 16384 });
  1761. // Append deterministic meta block (LLM may hallucinate timestamps)
  1762. const metaBlock = [
  1763. "",
  1764. "---",
  1765. "meta:",
  1766. ` parentBookId: "${parentBookId}"`,
  1767. ` parentTitle: "${parentBook.title}"`,
  1768. ` generatedAt: "${new Date().toISOString()}"`,
  1769. ].join("\n");
  1770. const canon = response.content + metaBlock;
  1771. await writeFile(join(storyDir, "parent_canon.md"), canon, "utf-8");
  1772. // Also generate style guide from parent's chapter text if available
  1773. const parentChaptersDir = join(parentDir, "chapters");
  1774. const parentChapterText = await this.readParentChapterSample(parentChaptersDir);
  1775. if (parentChapterText.length >= 500) {
  1776. await this.tryGenerateStyleGuide(targetBookId, parentChapterText, parentBook.title);
  1777. }
  1778. return canon;
  1779. }
  1780. private async readParentChapterSample(chaptersDir: string): Promise<string> {
  1781. try {
  1782. const entries = await readdir(chaptersDir);
  1783. const mdFiles = entries
  1784. .filter((file) => file.endsWith(".md"))
  1785. .sort()
  1786. .slice(0, 5);
  1787. const chunks: string[] = [];
  1788. let totalLength = 0;
  1789. for (const file of mdFiles) {
  1790. if (totalLength >= 20000) break;
  1791. const content = await readFile(join(chaptersDir, file), "utf-8");
  1792. chunks.push(content);
  1793. totalLength += content.length;
  1794. }
  1795. return chunks.join("\n\n---\n\n");
  1796. } catch {
  1797. return "";
  1798. }
  1799. }
  1800. // ---------------------------------------------------------------------------
  1801. // Chapter import (for continuation writing from existing chapters)
  1802. // ---------------------------------------------------------------------------
  1803. /**
  1804. * Import existing chapters into a book. Reverse-engineers all truth files
  1805. * via sequential replay so the Writer and Auditor can continue naturally.
  1806. *
  1807. * Step 1: Generate foundation (story_bible, volume_outline, book_rules) from all chapters.
  1808. * Step 2: Sequentially replay each chapter through ChapterAnalyzer to build truth files.
  1809. */
  1810. async importChapters(input: ImportChaptersInput): Promise<ImportChaptersResult> {
  1811. const releaseLock = await this.state.acquireBookLock(input.bookId);
  1812. try {
  1813. const book = await this.state.loadBookConfig(input.bookId);
  1814. const bookDir = this.state.bookDir(input.bookId);
  1815. const { profile: gp } = await this.loadGenreProfile(book.genre);
  1816. const resolvedLanguage = book.language ?? gp.language;
  1817. const startFrom = input.resumeFrom ?? 1;
  1818. const log = this.config.logger?.child("import");
  1819. // Step 1: Generate foundation on first run (not on resume)
  1820. if (startFrom === 1) {
  1821. log?.info(this.localize(resolvedLanguage, {
  1822. zh: `步骤 1:从 ${input.chapters.length} 章生成基础设定...`,
  1823. en: `Step 1: Generating foundation from ${input.chapters.length} chapters...`,
  1824. }));
  1825. const allText = input.chapters.map((c, i) =>
  1826. resolvedLanguage === "en"
  1827. ? `Chapter ${i + 1}: ${c.title}\n\n${c.content}`
  1828. : `第${i + 1}章 ${c.title}\n\n${c.content}`,
  1829. ).join("\n\n---\n\n");
  1830. const architect = new ArchitectAgent(this.agentCtxFor("architect", input.bookId));
  1831. const isSeries = input.importMode === "series";
  1832. const foundation = isSeries
  1833. ? await this.generateAndReviewFoundation({
  1834. generate: (reviewFeedback) => architect.generateFoundationFromImport(book, allText, undefined, reviewFeedback, { importMode: "series" }),
  1835. reviewer: new FoundationReviewerAgent(this.agentCtxFor("foundation-reviewer", input.bookId)),
  1836. mode: "series",
  1837. language: resolvedLanguage === "en" ? "en" : "zh",
  1838. stageLanguage: resolvedLanguage,
  1839. })
  1840. : await architect.generateFoundationFromImport(book, allText);
  1841. await architect.writeFoundationFiles(
  1842. bookDir,
  1843. foundation,
  1844. gp.numericalSystem,
  1845. resolvedLanguage,
  1846. );
  1847. await this.resetImportReplayTruthFiles(bookDir, resolvedLanguage);
  1848. await this.state.saveChapterIndex(input.bookId, []);
  1849. await this.state.snapshotState(input.bookId, 0);
  1850. // Generate style guide from imported chapters
  1851. if (allText.length >= 500) {
  1852. log?.info(this.localize(resolvedLanguage, {
  1853. zh: "提取原文风格指纹...",
  1854. en: "Extracting source style fingerprint...",
  1855. }));
  1856. await this.tryGenerateStyleGuide(input.bookId, allText, book.title, resolvedLanguage);
  1857. }
  1858. log?.info(this.localize(resolvedLanguage, {
  1859. zh: "基础设定已生成。",
  1860. en: "Foundation generated.",
  1861. }));
  1862. }
  1863. // Step 2: Sequential replay
  1864. log?.info(this.localize(resolvedLanguage, {
  1865. zh: `步骤 2:从第 ${startFrom} 章开始顺序回放...`,
  1866. en: `Step 2: Sequential replay from chapter ${startFrom}...`,
  1867. }));
  1868. const analyzer = new ChapterAnalyzerAgent(this.agentCtxFor("chapter-analyzer", input.bookId));
  1869. const writer = new WriterAgent(this.agentCtxFor("writer", input.bookId));
  1870. const countingMode = resolveLengthCountingMode(book.language ?? gp.language);
  1871. let totalWords = 0;
  1872. let importedCount = 0;
  1873. for (let i = startFrom - 1; i < input.chapters.length; i++) {
  1874. const ch = input.chapters[i]!;
  1875. const chapterNumber = i + 1;
  1876. const governedInput = await this.prepareWriteInput(book, bookDir, chapterNumber);
  1877. log?.info(this.localize(resolvedLanguage, {
  1878. zh: `分析章节 ${chapterNumber}/${input.chapters.length}:${ch.title}...`,
  1879. en: `Analyzing chapter ${chapterNumber}/${input.chapters.length}: ${ch.title}...`,
  1880. }));
  1881. // Analyze chapter to get truth file updates
  1882. const output = await analyzer.analyzeChapter({
  1883. book,
  1884. bookDir,
  1885. chapterNumber,
  1886. chapterContent: ch.content,
  1887. chapterTitle: ch.title,
  1888. chapterIntent: governedInput.chapterIntent,
  1889. contextPackage: governedInput.contextPackage,
  1890. ruleStack: governedInput.ruleStack,
  1891. });
  1892. // Save chapter file + core truth files (state, ledger, hooks)
  1893. await writer.saveChapter(bookDir, {
  1894. ...output,
  1895. postWriteErrors: [],
  1896. postWriteWarnings: [],
  1897. }, gp.numericalSystem, resolvedLanguage);
  1898. // Save extended truth files (summaries, subplots, emotional arcs, character matrix)
  1899. await writer.saveNewTruthFiles(bookDir, {
  1900. ...output,
  1901. postWriteErrors: [],
  1902. postWriteWarnings: [],
  1903. }, resolvedLanguage);
  1904. await this.syncLegacyStructuredStateFromMarkdown(bookDir, chapterNumber, output);
  1905. await this.syncNarrativeMemoryIndex(input.bookId);
  1906. // Update chapter index
  1907. const existingIndex = await this.state.loadChapterIndex(input.bookId);
  1908. const now = new Date().toISOString();
  1909. const chapterWordCount = countChapterLength(ch.content, countingMode);
  1910. const newEntry: ChapterMeta = {
  1911. number: chapterNumber,
  1912. title: output.title,
  1913. status: "imported",
  1914. wordCount: chapterWordCount,
  1915. createdAt: now,
  1916. updatedAt: now,
  1917. auditIssues: [],
  1918. lengthWarnings: [],
  1919. };
  1920. // Replace if exists (resume case), otherwise append
  1921. const existingIdx = existingIndex.findIndex((e) => e.number === chapterNumber);
  1922. const updatedIndex = existingIdx >= 0
  1923. ? existingIndex.map((e, idx) => idx === existingIdx ? newEntry : e)
  1924. : [...existingIndex, newEntry];
  1925. await this.state.saveChapterIndex(input.bookId, updatedIndex);
  1926. // Snapshot state after each chapter for rollback + resume support
  1927. await this.state.snapshotState(input.bookId, chapterNumber);
  1928. importedCount++;
  1929. totalWords += chapterWordCount;
  1930. }
  1931. if (input.chapters.length > 0) {
  1932. await this.markBookActiveIfNeeded(input.bookId);
  1933. await this.syncCurrentStateFactHistory(input.bookId, input.chapters.length);
  1934. }
  1935. const nextChapter = input.chapters.length + 1;
  1936. log?.info(this.localize(resolvedLanguage, {
  1937. zh: `完成。已导入 ${importedCount} 章,共 ${formatLengthCount(totalWords, countingMode)}。下一章:${nextChapter}`,
  1938. en: `Done. ${importedCount} chapters imported, ${formatLengthCount(totalWords, countingMode)}. Next chapter: ${nextChapter}`,
  1939. }));
  1940. return {
  1941. bookId: input.bookId,
  1942. importedCount,
  1943. totalWords,
  1944. nextChapter,
  1945. };
  1946. } finally {
  1947. await releaseLock();
  1948. }
  1949. }
  1950. private static addUsage(
  1951. a: TokenUsageSummary,
  1952. b?: { readonly promptTokens: number; readonly completionTokens: number; readonly totalTokens: number },
  1953. ): TokenUsageSummary {
  1954. if (!b) return a;
  1955. return {
  1956. promptTokens: a.promptTokens + b.promptTokens,
  1957. completionTokens: a.completionTokens + b.completionTokens,
  1958. totalTokens: a.totalTokens + b.totalTokens,
  1959. };
  1960. }
  1961. private async buildPersistenceOutput(
  1962. bookId: string,
  1963. book: BookConfig,
  1964. bookDir: string,
  1965. chapterNumber: number,
  1966. output: WriteChapterOutput,
  1967. finalContent: string,
  1968. countingMode: Parameters<typeof countChapterLength>[1],
  1969. reducedControlInput?: {
  1970. chapterIntent: string;
  1971. contextPackage: ContextPackage;
  1972. ruleStack: RuleStack;
  1973. },
  1974. ): Promise<WriteChapterOutput> {
  1975. if (finalContent === output.content) {
  1976. return output;
  1977. }
  1978. const analyzer = new ChapterAnalyzerAgent(this.agentCtxFor("chapter-analyzer", bookId));
  1979. const analyzed = await analyzer.analyzeChapter({
  1980. book,
  1981. bookDir,
  1982. chapterNumber,
  1983. chapterContent: finalContent,
  1984. chapterTitle: output.title,
  1985. chapterIntent: reducedControlInput?.chapterIntent,
  1986. contextPackage: reducedControlInput?.contextPackage,
  1987. ruleStack: reducedControlInput?.ruleStack,
  1988. });
  1989. return {
  1990. ...analyzed,
  1991. content: finalContent,
  1992. wordCount: countChapterLength(finalContent, countingMode),
  1993. postWriteErrors: [],
  1994. postWriteWarnings: [],
  1995. hookHealthIssues: output.hookHealthIssues,
  1996. tokenUsage: output.tokenUsage,
  1997. };
  1998. }
  1999. private async assertNoPendingStateRepair(bookId: string): Promise<void> {
  2000. const existingIndex = await this.state.loadChapterIndex(bookId);
  2001. const latestChapter = [...existingIndex].sort((left, right) => right.number - left.number)[0];
  2002. if (latestChapter?.status !== "state-degraded") {
  2003. return;
  2004. }
  2005. throw new Error(
  2006. `Latest chapter ${latestChapter.number} is state-degraded. Repair state or rewrite that chapter before continuing.`,
  2007. );
  2008. }
  2009. // ---------------------------------------------------------------------------
  2010. // Helpers
  2011. // ---------------------------------------------------------------------------
  2012. private async prepareWriteInput(
  2013. book: BookConfig,
  2014. bookDir: string,
  2015. chapterNumber: number,
  2016. externalContext?: string,
  2017. ): Promise<Pick<WriteChapterInput, "externalContext" | "chapterIntent" | "contextPackage" | "ruleStack" | "trace">> {
  2018. if ((this.config.inputGovernanceMode ?? "v2") === "legacy") {
  2019. return { externalContext };
  2020. }
  2021. const { plan, composed } = await this.createGovernedArtifacts(
  2022. book,
  2023. bookDir,
  2024. chapterNumber,
  2025. externalContext,
  2026. { reuseExistingIntentWhenContextMissing: true },
  2027. );
  2028. return {
  2029. chapterIntent: plan.intentMarkdown,
  2030. contextPackage: composed.contextPackage,
  2031. ruleStack: composed.ruleStack,
  2032. trace: composed.trace,
  2033. };
  2034. }
  2035. private async resetImportReplayTruthFiles(
  2036. bookDir: string,
  2037. language: LengthLanguage,
  2038. ): Promise<void> {
  2039. const storyDir = join(bookDir, "story");
  2040. await Promise.all([
  2041. writeFile(
  2042. join(storyDir, "current_state.md"),
  2043. this.buildImportReplayStateSeed(language),
  2044. "utf-8",
  2045. ),
  2046. // NOTE: pending_hooks.md intentionally NOT reset here — hooks are
  2047. // chapter-content-specific and user may have invested significant
  2048. // effort in tuning them. The replay will incrementally add new hooks
  2049. // detected from the imported chapters without destroying existing ones.
  2050. rm(join(storyDir, "chapter_summaries.md"), { force: true }),
  2051. rm(join(storyDir, "subplot_board.md"), { force: true }),
  2052. rm(join(storyDir, "emotional_arcs.md"), { force: true }),
  2053. rm(join(storyDir, "character_matrix.md"), { force: true }),
  2054. rm(join(storyDir, "volume_summaries.md"), { force: true }),
  2055. rm(join(storyDir, "particle_ledger.md"), { force: true }),
  2056. rm(join(storyDir, "memory.db"), { force: true }),
  2057. rm(join(storyDir, "memory.db-shm"), { force: true }),
  2058. rm(join(storyDir, "memory.db-wal"), { force: true }),
  2059. rm(join(storyDir, "state"), { recursive: true, force: true }),
  2060. rm(join(storyDir, "snapshots"), { recursive: true, force: true }),
  2061. ]);
  2062. }
  2063. private buildImportReplayStateSeed(language: LengthLanguage): string {
  2064. if (language === "en") {
  2065. return [
  2066. "# Current State",
  2067. "",
  2068. "| Field | Value |",
  2069. "| --- | --- |",
  2070. "| Current Chapter | 0 |",
  2071. "| Current Location | (not set) |",
  2072. "| Protagonist State | (not set) |",
  2073. "| Current Goal | (not set) |",
  2074. "| Current Constraint | (not set) |",
  2075. "| Current Alliances | (not set) |",
  2076. "| Current Conflict | (not set) |",
  2077. "",
  2078. ].join("\n");
  2079. }
  2080. return [
  2081. "# 当前状态",
  2082. "",
  2083. "| 字段 | 值 |",
  2084. "| --- | --- |",
  2085. "| 当前章节 | 0 |",
  2086. "| 当前位置 | (未设定) |",
  2087. "| 主角状态 | (未设定) |",
  2088. "| 当前目标 | (未设定) |",
  2089. "| 当前限制 | (未设定) |",
  2090. "| 当前敌我 | (未设定) |",
  2091. "| 当前冲突 | (未设定) |",
  2092. "",
  2093. ].join("\n");
  2094. }
  2095. private buildImportReplayHooksSeed(language: LengthLanguage): string {
  2096. if (language === "en") {
  2097. return [
  2098. "# Pending Hooks",
  2099. "",
  2100. "| hook_id | start_chapter | type | status | last_advanced_chapter | expected_payoff | notes |",
  2101. "| --- | --- | --- | --- | --- | --- | --- |",
  2102. "",
  2103. ].join("\n");
  2104. }
  2105. return [
  2106. "# 伏笔池",
  2107. "",
  2108. "| hook_id | 起始章节 | 类型 | 状态 | 最近推进 | 预期回收 | 备注 |",
  2109. "| --- | --- | --- | --- | --- | --- | --- |",
  2110. "",
  2111. ].join("\n");
  2112. }
  2113. private async normalizeDraftLengthIfNeeded(params: {
  2114. bookId: string;
  2115. chapterNumber: number;
  2116. chapterContent: string;
  2117. lengthSpec: LengthSpec;
  2118. chapterIntent?: string;
  2119. }): Promise<{
  2120. content: string;
  2121. wordCount: number;
  2122. applied: boolean;
  2123. tokenUsage?: TokenUsageSummary;
  2124. }> {
  2125. const writerCount = countChapterLength(
  2126. params.chapterContent,
  2127. params.lengthSpec.countingMode,
  2128. );
  2129. if (!isOutsideSoftRange(writerCount, params.lengthSpec)) {
  2130. return {
  2131. content: params.chapterContent,
  2132. wordCount: writerCount,
  2133. applied: false,
  2134. };
  2135. }
  2136. const normalizer = new LengthNormalizerAgent(
  2137. this.agentCtxFor("length-normalizer", params.bookId),
  2138. );
  2139. const normalized = await normalizer.normalizeChapter({
  2140. chapterContent: params.chapterContent,
  2141. lengthSpec: params.lengthSpec,
  2142. chapterIntent: params.chapterIntent,
  2143. });
  2144. // Safety net: if normalizer output is less than 25% of original, it was too destructive.
  2145. // Reject and keep original content.
  2146. if (normalized.finalCount < writerCount * 0.25) {
  2147. this.logWarn(this.languageFromLengthSpec(params.lengthSpec), {
  2148. zh: `字数归一化被拒绝:第${params.chapterNumber}章 ${writerCount} -> ${normalized.finalCount}(砍了${Math.round((1 - normalized.finalCount / writerCount) * 100)}%,超过安全阈值)`,
  2149. en: `Length normalization rejected for chapter ${params.chapterNumber}: ${writerCount} -> ${normalized.finalCount} (cut ${Math.round((1 - normalized.finalCount / writerCount) * 100)}%, exceeds safety threshold)`,
  2150. });
  2151. return {
  2152. content: params.chapterContent,
  2153. wordCount: writerCount,
  2154. applied: false,
  2155. };
  2156. }
  2157. this.logInfo(this.languageFromLengthSpec(params.lengthSpec), {
  2158. zh: `审计前字数归一化:第${params.chapterNumber}章 ${writerCount} -> ${normalized.finalCount}`,
  2159. en: `Length normalization before audit for chapter ${params.chapterNumber}: ${writerCount} -> ${normalized.finalCount}`,
  2160. });
  2161. return {
  2162. content: normalized.normalizedContent,
  2163. wordCount: normalized.finalCount,
  2164. applied: normalized.applied,
  2165. tokenUsage: normalized.tokenUsage,
  2166. };
  2167. }
  2168. private assertChapterContentNotEmpty(content: string, chapterNumber: number, stage: string): void {
  2169. if (content.trim().length > 0) return;
  2170. throw new Error(`Chapter ${chapterNumber} has empty chapter content after ${stage}`);
  2171. }
  2172. private async syncCurrentStateFactHistory(bookId: string, uptoChapter: number): Promise<void> {
  2173. const bookDir = this.state.bookDir(bookId);
  2174. try {
  2175. await this.rebuildCurrentStateFactHistory(bookDir, uptoChapter);
  2176. } catch (error) {
  2177. if (this.isMemoryIndexUnavailableError(error)) {
  2178. if (this.canOpenMemoryIndex(bookDir)) {
  2179. try {
  2180. await this.rebuildCurrentStateFactHistory(bookDir, uptoChapter);
  2181. return;
  2182. } catch (retryError) {
  2183. error = retryError;
  2184. }
  2185. } else {
  2186. if (!this.memoryIndexFallbackWarned) {
  2187. this.memoryIndexFallbackWarned = true;
  2188. this.logWarn(await this.resolveBookLanguageById(bookId), {
  2189. zh: "当前 Node 运行时不支持 SQLite 记忆索引,继续使用 Markdown 回退方案。",
  2190. en: "SQLite memory index unavailable on this Node runtime; continuing with markdown fallback.",
  2191. });
  2192. await this.logMemoryIndexDebugInfo(bookId, error);
  2193. }
  2194. return;
  2195. }
  2196. }
  2197. this.logWarn(await this.resolveBookLanguageById(bookId), {
  2198. zh: `状态事实同步已跳过:${String(error)}`,
  2199. en: `State fact sync skipped: ${String(error)}`,
  2200. });
  2201. }
  2202. }
  2203. private async syncLegacyStructuredStateFromMarkdown(
  2204. bookDir: string,
  2205. chapterNumber: number,
  2206. output?: {
  2207. readonly runtimeStateDelta?: WriteChapterOutput["runtimeStateDelta"];
  2208. readonly runtimeStateSnapshot?: WriteChapterOutput["runtimeStateSnapshot"];
  2209. },
  2210. ): Promise<void> {
  2211. if (output?.runtimeStateDelta || output?.runtimeStateSnapshot) {
  2212. return;
  2213. }
  2214. await rewriteStructuredStateFromMarkdown({
  2215. bookDir,
  2216. fallbackChapter: chapterNumber,
  2217. });
  2218. }
  2219. private async syncNarrativeMemoryIndex(bookId: string): Promise<void> {
  2220. const bookDir = this.state.bookDir(bookId);
  2221. try {
  2222. await this.rebuildNarrativeMemoryIndex(bookDir);
  2223. } catch (error) {
  2224. if (this.isMemoryIndexUnavailableError(error)) {
  2225. if (this.canOpenMemoryIndex(bookDir)) {
  2226. try {
  2227. await this.rebuildNarrativeMemoryIndex(bookDir);
  2228. return;
  2229. } catch (retryError) {
  2230. error = retryError;
  2231. }
  2232. } else {
  2233. if (!this.memoryIndexFallbackWarned) {
  2234. this.memoryIndexFallbackWarned = true;
  2235. this.logWarn(await this.resolveBookLanguageById(bookId), {
  2236. zh: "当前 Node 运行时不支持 SQLite 记忆索引,继续使用 Markdown 回退方案。",
  2237. en: "SQLite memory index unavailable on this Node runtime; continuing with markdown fallback.",
  2238. });
  2239. await this.logMemoryIndexDebugInfo(bookId, error);
  2240. }
  2241. return;
  2242. }
  2243. }
  2244. this.logWarn(await this.resolveBookLanguageById(bookId), {
  2245. zh: `叙事记忆同步已跳过:${String(error)}`,
  2246. en: `Narrative memory sync skipped: ${String(error)}`,
  2247. });
  2248. }
  2249. }
  2250. private async rebuildCurrentStateFactHistory(bookDir: string, uptoChapter: number): Promise<void> {
  2251. const memoryDb = await this.withMemoryIndexRetry(async () => {
  2252. const db = new MemoryDB(bookDir);
  2253. try {
  2254. db.resetFacts();
  2255. const activeFacts = new Map<string, { id: number; object: string }>();
  2256. for (let chapter = 0; chapter <= uptoChapter; chapter++) {
  2257. const snapshotFacts = await loadSnapshotCurrentStateFacts(bookDir, chapter);
  2258. if (snapshotFacts.length === 0) continue;
  2259. const nextFacts = new Map<string, Omit<Fact, "id">>();
  2260. for (const fact of snapshotFacts) {
  2261. nextFacts.set(this.factKey(fact), {
  2262. subject: fact.subject,
  2263. predicate: fact.predicate,
  2264. object: fact.object,
  2265. validFromChapter: chapter,
  2266. validUntilChapter: null,
  2267. sourceChapter: chapter,
  2268. });
  2269. }
  2270. for (const [key, previous] of activeFacts.entries()) {
  2271. const next = nextFacts.get(key);
  2272. if (!next || next.object !== previous.object) {
  2273. db.invalidateFact(previous.id, chapter);
  2274. activeFacts.delete(key);
  2275. }
  2276. }
  2277. for (const [key, fact] of nextFacts.entries()) {
  2278. if (activeFacts.has(key)) continue;
  2279. const id = db.addFact(fact);
  2280. activeFacts.set(key, { id, object: fact.object });
  2281. }
  2282. }
  2283. return db;
  2284. } catch (error) {
  2285. db.close();
  2286. throw error;
  2287. }
  2288. });
  2289. try {
  2290. // No-op: keep the db open only for the duration of the rebuild.
  2291. } finally {
  2292. memoryDb.close();
  2293. }
  2294. }
  2295. private async rebuildNarrativeMemoryIndex(bookDir: string): Promise<void> {
  2296. const memorySeed = await loadNarrativeMemorySeed(bookDir);
  2297. const memoryDb = await this.withMemoryIndexRetry(() => {
  2298. const db = new MemoryDB(bookDir);
  2299. try {
  2300. db.replaceSummaries(memorySeed.summaries);
  2301. db.replaceHooks(memorySeed.hooks);
  2302. return db;
  2303. } catch (error) {
  2304. db.close();
  2305. throw error;
  2306. }
  2307. });
  2308. try {
  2309. // No-op: keep the db open only for the duration of the rebuild.
  2310. } finally {
  2311. memoryDb.close();
  2312. }
  2313. }
  2314. private canOpenMemoryIndex(bookDir: string): boolean {
  2315. let memoryDb: MemoryDB | null = null;
  2316. try {
  2317. memoryDb = new MemoryDB(bookDir);
  2318. return true;
  2319. } catch {
  2320. return false;
  2321. } finally {
  2322. memoryDb?.close();
  2323. }
  2324. }
  2325. private async logMemoryIndexDebugInfo(bookId: string, error: unknown): Promise<void> {
  2326. if (process.env.INKOS_DEBUG_SQLITE_MEMORY !== "1") {
  2327. return;
  2328. }
  2329. const code = typeof error === "object" && error !== null && "code" in error
  2330. ? String((error as { code?: unknown }).code ?? "")
  2331. : "";
  2332. const message = error instanceof Error
  2333. ? error.message
  2334. : String(error);
  2335. this.logWarn(await this.resolveBookLanguageById(bookId), {
  2336. zh: `SQLite 记忆索引调试:node=${process.version}; execArgv=${JSON.stringify(process.execArgv)}; code=${code || "(none)"}; message=${message}`,
  2337. en: `SQLite memory debug: node=${process.version}; execArgv=${JSON.stringify(process.execArgv)}; code=${code || "(none)"}; message=${message}`,
  2338. });
  2339. }
  2340. private async withMemoryIndexRetry<T>(operation: () => Promise<T> | T): Promise<T> {
  2341. const retryDelaysMs = [0, 25, 75];
  2342. let lastError: unknown;
  2343. for (let attempt = 0; attempt < retryDelaysMs.length; attempt += 1) {
  2344. try {
  2345. return await operation();
  2346. } catch (error) {
  2347. lastError = error;
  2348. if (!this.isMemoryIndexBusyError(error) || attempt === retryDelaysMs.length - 1) {
  2349. throw error;
  2350. }
  2351. await new Promise((resolve) => setTimeout(resolve, retryDelaysMs[attempt + 1]!));
  2352. }
  2353. }
  2354. throw lastError;
  2355. }
  2356. private isMemoryIndexUnavailableError(error: unknown): boolean {
  2357. if (!error) return false;
  2358. const code = typeof error === "object" && error !== null && "code" in error
  2359. ? String((error as { code?: unknown }).code ?? "")
  2360. : "";
  2361. const message = error instanceof Error
  2362. ? error.message
  2363. : String(error);
  2364. const normalizedMessage = message.trim();
  2365. return /^No such built-in module:\s*node:sqlite$/i.test(normalizedMessage)
  2366. || /^Cannot find module ['"]node:sqlite['"]$/i.test(normalizedMessage)
  2367. || (code === "ERR_UNKNOWN_BUILTIN_MODULE" && /\bnode:sqlite\b/i.test(normalizedMessage));
  2368. }
  2369. private isMemoryIndexBusyError(error: unknown): boolean {
  2370. if (!error) return false;
  2371. const code = typeof error === "object" && error !== null && "code" in error
  2372. ? String((error as { code?: unknown }).code ?? "")
  2373. : "";
  2374. const message = error instanceof Error
  2375. ? error.message
  2376. : String(error);
  2377. return code === "SQLITE_BUSY"
  2378. || code === "SQLITE_LOCKED"
  2379. || /\bSQLITE_BUSY\b/i.test(message)
  2380. || /\bSQLITE_LOCKED\b/i.test(message)
  2381. || /database is locked/i.test(message)
  2382. || /database is busy/i.test(message);
  2383. }
  2384. private factKey(fact: Pick<Fact, "subject" | "predicate">): string {
  2385. return `${fact.subject}::${fact.predicate}`;
  2386. }
  2387. private buildLengthWarnings(
  2388. chapterNumber: number,
  2389. finalCount: number,
  2390. lengthSpec: LengthSpec,
  2391. ): string[] {
  2392. if (!isOutsideHardRange(finalCount, lengthSpec)) {
  2393. return [];
  2394. }
  2395. return [
  2396. this.localize(this.languageFromLengthSpec(lengthSpec), {
  2397. zh: `第${chapterNumber}章经过一次字数归一化后仍超出硬区间(${lengthSpec.hardMin}-${lengthSpec.hardMax},实际 ${finalCount})。`,
  2398. en: `Chapter ${chapterNumber} remains outside hard range (${lengthSpec.hardMin}-${lengthSpec.hardMax}, actual ${finalCount}) after a single normalization pass.`,
  2399. }),
  2400. ];
  2401. }
  2402. private buildLengthTelemetry(params: {
  2403. lengthSpec: LengthSpec;
  2404. writerCount: number;
  2405. postWriterNormalizeCount: number;
  2406. postReviseCount: number;
  2407. finalCount: number;
  2408. normalizeApplied: boolean;
  2409. lengthWarning: boolean;
  2410. }): LengthTelemetry {
  2411. return {
  2412. target: params.lengthSpec.target,
  2413. softMin: params.lengthSpec.softMin,
  2414. softMax: params.lengthSpec.softMax,
  2415. hardMin: params.lengthSpec.hardMin,
  2416. hardMax: params.lengthSpec.hardMax,
  2417. countingMode: params.lengthSpec.countingMode,
  2418. writerCount: params.writerCount,
  2419. postWriterNormalizeCount: params.postWriterNormalizeCount,
  2420. postReviseCount: params.postReviseCount,
  2421. finalCount: params.finalCount,
  2422. normalizeApplied: params.normalizeApplied,
  2423. lengthWarning: params.lengthWarning,
  2424. };
  2425. }
  2426. private async persistAuditDriftGuidance(params: {
  2427. readonly bookDir: string;
  2428. readonly chapterNumber: number;
  2429. readonly issues: ReadonlyArray<AuditIssue>;
  2430. readonly language: LengthLanguage;
  2431. }): Promise<void> {
  2432. const storyDir = join(params.bookDir, "story");
  2433. const driftPath = join(storyDir, "audit_drift.md");
  2434. const statePath = join(storyDir, "current_state.md");
  2435. const currentState = await readFile(statePath, "utf-8").catch(() => "");
  2436. const sanitizedState = this.stripAuditDriftCorrectionBlock(currentState).trimEnd();
  2437. if (sanitizedState !== currentState) {
  2438. await writeFile(statePath, sanitizedState, "utf-8");
  2439. }
  2440. if (params.issues.length === 0) {
  2441. await rm(driftPath, { force: true }).catch(() => undefined);
  2442. return;
  2443. }
  2444. const block = [
  2445. this.localize(params.language, {
  2446. zh: "# 审计纠偏",
  2447. en: "# Audit Drift",
  2448. }),
  2449. "",
  2450. this.localize(params.language, {
  2451. zh: "## 审计纠偏(自动生成,下一章写作前参照)",
  2452. en: "## Audit Drift Correction",
  2453. }),
  2454. "",
  2455. this.localize(params.language, {
  2456. zh: `> 第${params.chapterNumber}章审计发现以下问题,下一章写作时必须避免:`,
  2457. en: `> Chapter ${params.chapterNumber} audit found the following issues to avoid in the next chapter:`,
  2458. }),
  2459. ...params.issues.map((issue) => `> - [${issue.severity}] ${issue.category}: ${issue.description}`),
  2460. "",
  2461. ].join("\n");
  2462. await writeFile(driftPath, block, "utf-8");
  2463. }
  2464. private stripAuditDriftCorrectionBlock(currentState: string): string {
  2465. const headers = [
  2466. "## 审计纠偏(自动生成,下一章写作前参照)",
  2467. "## Audit Drift Correction",
  2468. "# 审计纠偏",
  2469. "# Audit Drift",
  2470. ];
  2471. let cutIndex = -1;
  2472. for (const header of headers) {
  2473. const index = currentState.indexOf(header);
  2474. if (index >= 0 && (cutIndex < 0 || index < cutIndex)) {
  2475. cutIndex = index;
  2476. }
  2477. }
  2478. if (cutIndex < 0) {
  2479. return currentState;
  2480. }
  2481. return currentState.slice(0, cutIndex).trimEnd();
  2482. }
  2483. private logLengthWarnings(lengthWarnings: ReadonlyArray<string>): void {
  2484. for (const warning of lengthWarnings) {
  2485. this.config.logger?.warn(warning);
  2486. }
  2487. }
  2488. private restoreLostAuditIssues(previous: AuditResult, next: AuditResult): AuditResult {
  2489. if (next.passed || next.issues.length > 0 || previous.issues.length === 0) {
  2490. return next;
  2491. }
  2492. return {
  2493. ...next,
  2494. issues: previous.issues,
  2495. summary: next.summary || previous.summary,
  2496. };
  2497. }
  2498. private restoreActionableAuditIfLost(
  2499. previous: {
  2500. auditResult: AuditResult;
  2501. aiTellCount: number;
  2502. blockingCount: number;
  2503. criticalCount: number;
  2504. revisionBlockingIssues: ReadonlyArray<AuditIssue>;
  2505. },
  2506. next: {
  2507. auditResult: AuditResult;
  2508. aiTellCount: number;
  2509. blockingCount: number;
  2510. criticalCount: number;
  2511. revisionBlockingIssues: ReadonlyArray<AuditIssue>;
  2512. },
  2513. ): MergedAuditEvaluation {
  2514. const auditResult = this.restoreLostAuditIssues(previous.auditResult, next.auditResult);
  2515. if (auditResult === next.auditResult) {
  2516. return next;
  2517. }
  2518. return {
  2519. ...next,
  2520. auditResult,
  2521. revisionBlockingIssues: previous.revisionBlockingIssues,
  2522. blockingCount: previous.blockingCount,
  2523. criticalCount: previous.criticalCount,
  2524. };
  2525. }
  2526. private async evaluateMergedAudit(params: {
  2527. auditor: ContinuityAuditor;
  2528. book: BookConfig;
  2529. bookDir: string;
  2530. chapterContent: string;
  2531. chapterNumber: number;
  2532. language: LengthLanguage;
  2533. auditOptions?: {
  2534. temperature?: number;
  2535. chapterIntent?: string;
  2536. contextPackage?: ContextPackage;
  2537. ruleStack?: RuleStack;
  2538. truthFileOverrides?: {
  2539. currentState?: string;
  2540. ledger?: string;
  2541. hooks?: string;
  2542. };
  2543. };
  2544. }): Promise<MergedAuditEvaluation> {
  2545. const llmAudit = await params.auditor.auditChapter(
  2546. params.bookDir,
  2547. params.chapterContent,
  2548. params.chapterNumber,
  2549. params.book.genre,
  2550. params.auditOptions,
  2551. );
  2552. const aiTells = analyzeAITells(params.chapterContent, params.language);
  2553. const sensitiveResult = analyzeSensitiveWords(params.chapterContent, undefined, params.language);
  2554. const longSpanFatigue = await analyzeLongSpanFatigue({
  2555. bookDir: params.bookDir,
  2556. chapterNumber: params.chapterNumber,
  2557. chapterContent: params.chapterContent,
  2558. language: params.language,
  2559. });
  2560. const hasBlockedWords = sensitiveResult.found.some((f) => f.severity === "block");
  2561. const issues: ReadonlyArray<AuditIssue> = [
  2562. ...llmAudit.issues,
  2563. ...aiTells.issues,
  2564. ...sensitiveResult.issues,
  2565. ...longSpanFatigue.issues,
  2566. ];
  2567. // revisionBlockingIssues excludes long-span-fatigue issues by
  2568. // construction (not by category name) so that an LLM-reported issue
  2569. // sharing a category label with a long-span issue is still counted.
  2570. const revisionBlockingIssues: ReadonlyArray<AuditIssue> = [
  2571. ...llmAudit.issues,
  2572. ...aiTells.issues,
  2573. ...sensitiveResult.issues,
  2574. ];
  2575. return {
  2576. auditResult: {
  2577. passed: hasBlockedWords ? false : llmAudit.passed,
  2578. issues,
  2579. summary: llmAudit.summary,
  2580. tokenUsage: llmAudit.tokenUsage,
  2581. },
  2582. aiTellCount: aiTells.issues.length,
  2583. blockingCount: revisionBlockingIssues.filter((issue) => issue.severity === "warning" || issue.severity === "critical").length,
  2584. criticalCount: revisionBlockingIssues.filter((issue) => issue.severity === "critical").length,
  2585. revisionBlockingIssues,
  2586. };
  2587. }
  2588. private async markBookActiveIfNeeded(bookId: string): Promise<void> {
  2589. const book = await this.state.loadBookConfig(bookId);
  2590. if (book.status !== "outlining") return;
  2591. await this.state.saveBookConfig(bookId, {
  2592. ...book,
  2593. status: "active",
  2594. updatedAt: new Date().toISOString(),
  2595. });
  2596. }
  2597. private async createGovernedArtifacts(
  2598. book: BookConfig,
  2599. bookDir: string,
  2600. chapterNumber: number,
  2601. externalContext?: string,
  2602. options?: {
  2603. readonly reuseExistingIntentWhenContextMissing?: boolean;
  2604. },
  2605. ): Promise<{
  2606. plan: PlanChapterOutput;
  2607. composed: Awaited<ReturnType<ComposerAgent["composeChapter"]>>;
  2608. }> {
  2609. const plan = await this.resolveGovernedPlan(book, bookDir, chapterNumber, externalContext, options);
  2610. const composer = new ComposerAgent(this.agentCtxFor("composer", book.id));
  2611. const composed = await composer.composeChapter({
  2612. book,
  2613. bookDir,
  2614. chapterNumber,
  2615. plan,
  2616. });
  2617. return { plan, composed };
  2618. }
  2619. private async resolveGovernedPlan(
  2620. book: BookConfig,
  2621. bookDir: string,
  2622. chapterNumber: number,
  2623. externalContext?: string,
  2624. options?: {
  2625. readonly reuseExistingIntentWhenContextMissing?: boolean;
  2626. },
  2627. ): Promise<PlanChapterOutput> {
  2628. if (
  2629. options?.reuseExistingIntentWhenContextMissing &&
  2630. (!externalContext || externalContext.trim().length === 0)
  2631. ) {
  2632. const persisted = await loadPersistedPlan(bookDir, chapterNumber);
  2633. if (persisted) return persisted;
  2634. }
  2635. const planner = new PlannerAgent(this.agentCtxFor("planner", book.id));
  2636. return planner.planChapter({
  2637. book,
  2638. bookDir,
  2639. chapterNumber,
  2640. externalContext,
  2641. });
  2642. }
  2643. private async emitWebhook(
  2644. event: WebhookEvent,
  2645. bookId: string,
  2646. chapterNumber?: number,
  2647. data?: Record<string, unknown>,
  2648. ): Promise<void> {
  2649. if (!this.config.notifyChannels || this.config.notifyChannels.length === 0) return;
  2650. await dispatchWebhookEvent(this.config.notifyChannels, {
  2651. event,
  2652. bookId,
  2653. chapterNumber,
  2654. timestamp: new Date().toISOString(),
  2655. data,
  2656. });
  2657. }
  2658. private async readChapterContent(bookDir: string, chapterNumber: number): Promise<string> {
  2659. const chaptersDir = join(bookDir, "chapters");
  2660. const files = await readdir(chaptersDir);
  2661. const paddedNum = String(chapterNumber).padStart(4, "0");
  2662. const chapterFile = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  2663. if (!chapterFile) {
  2664. throw new Error(`Chapter ${chapterNumber} file not found in ${chaptersDir}`);
  2665. }
  2666. const raw = await readFile(join(chaptersDir, chapterFile), "utf-8");
  2667. // Strip the title line
  2668. const lines = raw.split("\n");
  2669. const contentStart = lines.findIndex((l, i) => i > 0 && l.trim().length > 0);
  2670. return contentStart >= 0 ? lines.slice(contentStart).join("\n") : raw;
  2671. }
  2672. }