runner.ts 102 KB

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