pipeline-runner.test.ts 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import { createRequire } from "node:module";
  3. import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { PipelineRunner } from "../pipeline/runner.js";
  7. import { StateManager } from "../state/manager.js";
  8. import { ArchitectAgent } from "../agents/architect.js";
  9. import { PlannerAgent } from "../agents/planner.js";
  10. import { ComposerAgent } from "../agents/composer.js";
  11. import { WriterAgent, type WriteChapterOutput } from "../agents/writer.js";
  12. import { LengthNormalizerAgent } from "../agents/length-normalizer.js";
  13. import { ContinuityAuditor, type AuditIssue, type AuditResult } from "../agents/continuity.js";
  14. import { ReviserAgent, type ReviseOutput } from "../agents/reviser.js";
  15. import { ChapterAnalyzerAgent } from "../agents/chapter-analyzer.js";
  16. import type { BookConfig } from "../models/book.js";
  17. import type { ChapterMeta } from "../models/chapter.js";
  18. import { MemoryDB } from "../state/memory-db.js";
  19. import * as memoryDbModule from "../state/memory-db.js";
  20. import { countChapterLength } from "../utils/length-metrics.js";
  21. const require = createRequire(import.meta.url);
  22. const hasNodeSqlite = (() => {
  23. try {
  24. require("node:sqlite");
  25. return true;
  26. } catch {
  27. return false;
  28. }
  29. })();
  30. const sqliteIt = hasNodeSqlite ? it : it.skip;
  31. const ZERO_USAGE = {
  32. promptTokens: 0,
  33. completionTokens: 0,
  34. totalTokens: 0,
  35. } as const;
  36. const CRITICAL_ISSUE: AuditIssue = {
  37. severity: "critical",
  38. category: "continuity",
  39. description: "Fix the chapter state",
  40. suggestion: "Repair the contradiction",
  41. };
  42. function createAuditResult(overrides: Partial<AuditResult>): AuditResult {
  43. return {
  44. passed: true,
  45. issues: [],
  46. summary: "ok",
  47. tokenUsage: ZERO_USAGE,
  48. ...overrides,
  49. };
  50. }
  51. function createWriterOutput(overrides: Partial<WriteChapterOutput> = {}): WriteChapterOutput {
  52. return {
  53. chapterNumber: 1,
  54. title: "Test Chapter",
  55. content: "Original chapter body.",
  56. wordCount: "Original chapter body.".length,
  57. preWriteCheck: "check",
  58. postSettlement: "settled",
  59. updatedState: "writer state",
  60. updatedLedger: "writer ledger",
  61. updatedHooks: "writer hooks",
  62. chapterSummary: "| 1 | Original summary |",
  63. updatedSubplots: "writer subplots",
  64. updatedEmotionalArcs: "writer emotions",
  65. updatedCharacterMatrix: "writer matrix",
  66. postWriteErrors: [],
  67. postWriteWarnings: [],
  68. tokenUsage: ZERO_USAGE,
  69. ...overrides,
  70. };
  71. }
  72. function createReviseOutput(overrides: Partial<ReviseOutput> = {}): ReviseOutput {
  73. return {
  74. revisedContent: "Revised chapter body.",
  75. wordCount: "Revised chapter body.".length,
  76. fixedIssues: ["fixed"],
  77. updatedState: "revised state",
  78. updatedLedger: "revised ledger",
  79. updatedHooks: "revised hooks",
  80. tokenUsage: ZERO_USAGE,
  81. ...overrides,
  82. };
  83. }
  84. function createAnalyzedOutput(overrides: Partial<WriteChapterOutput> = {}): WriteChapterOutput {
  85. return createWriterOutput({
  86. content: "Analyzed final chapter body.",
  87. wordCount: "Analyzed final chapter body.".length,
  88. updatedState: "analyzed state",
  89. updatedLedger: "analyzed ledger",
  90. updatedHooks: "analyzed hooks",
  91. chapterSummary: "| 1 | Revised summary |",
  92. updatedSubplots: "analyzed subplots",
  93. updatedEmotionalArcs: "analyzed emotions",
  94. updatedCharacterMatrix: "analyzed matrix",
  95. ...overrides,
  96. });
  97. }
  98. function createStateCard(params: {
  99. readonly chapter: number;
  100. readonly location: string;
  101. readonly protagonistState: string;
  102. readonly goal: string;
  103. readonly conflict: string;
  104. }): string {
  105. return [
  106. "# Current State",
  107. "",
  108. "| Field | Value |",
  109. "| --- | --- |",
  110. `| Current Chapter | ${params.chapter} |`,
  111. `| Current Location | ${params.location} |`,
  112. `| Protagonist State | ${params.protagonistState} |`,
  113. `| Current Goal | ${params.goal} |`,
  114. "| Current Constraint | The city gates are watched. |",
  115. "| Current Alliances | Mentor allies are scattered. |",
  116. `| Current Conflict | ${params.conflict} |`,
  117. "",
  118. ].join("\n");
  119. }
  120. function createCaptureLogger() {
  121. const infos: string[] = [];
  122. const warnings: string[] = [];
  123. const logger = {
  124. debug() {},
  125. info(message: string) {
  126. infos.push(message);
  127. },
  128. warn(message: string) {
  129. warnings.push(message);
  130. },
  131. error() {},
  132. child() {
  133. return logger;
  134. },
  135. };
  136. return { logger, infos, warnings };
  137. }
  138. async function createRunnerFixture(
  139. configOverrides: Partial<ConstructorParameters<typeof PipelineRunner>[0]> = {},
  140. ): Promise<{
  141. root: string;
  142. runner: PipelineRunner;
  143. state: StateManager;
  144. bookId: string;
  145. }> {
  146. const root = await mkdtemp(join(tmpdir(), "inkos-runner-test-"));
  147. const state = new StateManager(root);
  148. const bookId = "test-book";
  149. const now = "2026-03-19T00:00:00.000Z";
  150. const book: BookConfig = {
  151. id: bookId,
  152. title: "Test Book",
  153. platform: "tomato",
  154. genre: "xuanhuan",
  155. status: "active",
  156. targetChapters: 10,
  157. chapterWordCount: 3000,
  158. createdAt: now,
  159. updatedAt: now,
  160. };
  161. await state.saveBookConfig(bookId, book);
  162. await mkdir(join(state.bookDir(bookId), "story"), { recursive: true });
  163. await mkdir(join(state.bookDir(bookId), "chapters"), { recursive: true });
  164. const runner = new PipelineRunner({
  165. client: {
  166. provider: "openai",
  167. apiFormat: "chat",
  168. stream: false,
  169. defaults: {
  170. temperature: 0.7,
  171. maxTokens: 4096,
  172. thinkingBudget: 0, maxTokensCap: null,
  173. },
  174. } as ConstructorParameters<typeof PipelineRunner>[0]["client"],
  175. model: "test-model",
  176. projectRoot: root,
  177. ...configOverrides,
  178. });
  179. return { root, runner, state, bookId };
  180. }
  181. describe("PipelineRunner", () => {
  182. beforeEach(() => {
  183. vi.spyOn(LengthNormalizerAgent.prototype, "normalizeChapter").mockImplementation(
  184. async ({ chapterContent, lengthSpec }) => ({
  185. normalizedContent: chapterContent,
  186. finalCount: countChapterLength(chapterContent, lengthSpec.countingMode),
  187. applied: false,
  188. mode: "none",
  189. tokenUsage: ZERO_USAGE,
  190. }),
  191. );
  192. });
  193. afterEach(() => {
  194. vi.restoreAllMocks();
  195. });
  196. it("does not reuse override clients when credential sources differ", () => {
  197. const previousKeyA = process.env.TEST_KEY_A;
  198. const previousKeyB = process.env.TEST_KEY_B;
  199. process.env.TEST_KEY_A = "key-a";
  200. process.env.TEST_KEY_B = "key-b";
  201. try {
  202. const runner = new PipelineRunner({
  203. client: {
  204. provider: "openai",
  205. apiFormat: "chat",
  206. stream: false,
  207. defaults: {
  208. temperature: 0.7,
  209. maxTokens: 4096,
  210. thinkingBudget: 0, maxTokensCap: null,
  211. },
  212. } as ConstructorParameters<typeof PipelineRunner>[0]["client"],
  213. model: "base-model",
  214. projectRoot: process.cwd(),
  215. defaultLLMConfig: {
  216. provider: "custom",
  217. baseUrl: "https://base.example/v1",
  218. apiKey: "base-key",
  219. model: "base-model",
  220. temperature: 0.7,
  221. maxTokens: 4096,
  222. thinkingBudget: 0,
  223. apiFormat: "chat",
  224. stream: false,
  225. },
  226. modelOverrides: {
  227. writer: {
  228. model: "writer-model",
  229. provider: "custom",
  230. baseUrl: "https://shared.example/v1",
  231. apiKeyEnv: "TEST_KEY_A",
  232. },
  233. auditor: {
  234. model: "auditor-model",
  235. provider: "custom",
  236. baseUrl: "https://shared.example/v1",
  237. apiKeyEnv: "TEST_KEY_B",
  238. },
  239. },
  240. });
  241. const resolveOverride = (
  242. runner as unknown as {
  243. resolveOverride: (agent: string) => { model: string; client: unknown };
  244. }
  245. ).resolveOverride.bind(runner);
  246. const writerOverride = resolveOverride("writer");
  247. const auditorOverride = resolveOverride("auditor");
  248. expect(writerOverride.client).not.toBe(auditorOverride.client);
  249. } finally {
  250. if (previousKeyA === undefined) delete process.env.TEST_KEY_A;
  251. else process.env.TEST_KEY_A = previousKeyA;
  252. if (previousKeyB === undefined) delete process.env.TEST_KEY_B;
  253. else process.env.TEST_KEY_B = previousKeyB;
  254. }
  255. });
  256. it("initializes control documents during book creation", async () => {
  257. const root = await mkdtemp(join(tmpdir(), "inkos-init-book-test-"));
  258. const bookId = "bootstrap-book";
  259. const brief = "# Author Intent\n\nKeep the narrative centered on mentor conflict.\n";
  260. const now = "2026-03-22T00:00:00.000Z";
  261. const book: BookConfig = {
  262. id: bookId,
  263. title: "Bootstrap Book",
  264. platform: "tomato",
  265. genre: "xuanhuan",
  266. status: "outlining",
  267. targetChapters: 10,
  268. chapterWordCount: 3000,
  269. createdAt: now,
  270. updatedAt: now,
  271. };
  272. const runner = new PipelineRunner({
  273. client: {
  274. provider: "openai",
  275. apiFormat: "chat",
  276. stream: false,
  277. defaults: {
  278. temperature: 0.7,
  279. maxTokens: 4096,
  280. thinkingBudget: 0, maxTokensCap: null,
  281. },
  282. } as ConstructorParameters<typeof PipelineRunner>[0]["client"],
  283. model: "test-model",
  284. projectRoot: root,
  285. externalContext: brief,
  286. });
  287. vi.spyOn(ArchitectAgent.prototype, "generateFoundation").mockResolvedValue({
  288. storyBible: "# Story Bible\n",
  289. volumeOutline: "# Volume Outline\n",
  290. bookRules: "---\nversion: \"1.0\"\n---\n\n# Book Rules\n",
  291. currentState: "# Current State\n",
  292. pendingHooks: "# Pending Hooks\n",
  293. });
  294. try {
  295. await runner.initBook(book);
  296. const storyDir = join(root, "books", bookId, "story");
  297. const authorIntent = await readFile(join(storyDir, "author_intent.md"), "utf-8");
  298. const currentFocus = await readFile(join(storyDir, "current_focus.md"), "utf-8");
  299. const runtimeDir = await stat(join(storyDir, "runtime"));
  300. expect(authorIntent).toContain("mentor conflict");
  301. expect(currentFocus).toContain("Current Focus");
  302. expect(runtimeDir.isDirectory()).toBe(true);
  303. } finally {
  304. await rm(root, { recursive: true, force: true });
  305. }
  306. });
  307. it("bootstraps missing control documents for legacy books before writing", async () => {
  308. const { root, runner, bookId } = await createRunnerFixture();
  309. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  310. createWriterOutput({
  311. chapterNumber: 1,
  312. content: "Legacy chapter body.",
  313. wordCount: "Legacy chapter body.".length,
  314. }),
  315. );
  316. try {
  317. await runner.writeDraft(bookId);
  318. const storyDir = join(root, "books", bookId, "story");
  319. const authorIntent = await readFile(join(storyDir, "author_intent.md"), "utf-8");
  320. const currentFocus = await readFile(join(storyDir, "current_focus.md"), "utf-8");
  321. const runtimeDir = await stat(join(storyDir, "runtime"));
  322. expect(authorIntent).toContain("Author Intent");
  323. expect(currentFocus).toContain("Current Focus");
  324. expect(runtimeDir.isDirectory()).toBe(true);
  325. } finally {
  326. await rm(root, { recursive: true, force: true });
  327. }
  328. });
  329. it("routes writeDraft through planner and composer in v2 mode", async () => {
  330. const { root, runner, state, bookId } = await createRunnerFixture({
  331. inputGovernanceMode: "v2",
  332. });
  333. await Promise.all([
  334. writeFile(join(state.bookDir(bookId), "story", "current_focus.md"), "# Current Focus\n\nBring focus back to the mentor conflict.\n", "utf-8"),
  335. writeFile(join(state.bookDir(bookId), "story", "volume_outline.md"), "# Volume Outline\n\n## Chapter 1\nTrack the merchant guild trail.\n", "utf-8"),
  336. writeFile(join(state.bookDir(bookId), "story", "current_state.md"), "# Current State\n\n- Lin Yue still hides the broken oath token.\n", "utf-8"),
  337. writeFile(join(state.bookDir(bookId), "story", "story_bible.md"), "# Story Bible\n\n- The jade seal cannot be destroyed.\n", "utf-8"),
  338. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n\n- Why the mentor vanished after the trial.\n", "utf-8"),
  339. ]);
  340. const planChapter = vi.spyOn(PlannerAgent.prototype, "planChapter");
  341. const composeChapter = vi.spyOn(ComposerAgent.prototype, "composeChapter");
  342. const writeChapter = vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  343. createWriterOutput({
  344. chapterNumber: 1,
  345. content: "Governed draft body.",
  346. wordCount: "Governed draft body.".length,
  347. }),
  348. );
  349. try {
  350. await runner.writeDraft(bookId, "Ignore the guild chase and bring focus back to mentor conflict.");
  351. expect(planChapter).toHaveBeenCalledTimes(1);
  352. expect(composeChapter).toHaveBeenCalledTimes(1);
  353. const writeInput = writeChapter.mock.calls[0]?.[0];
  354. expect(writeInput?.externalContext).toBeUndefined();
  355. expect(writeInput?.chapterIntent).toContain("# Chapter Intent");
  356. expect(writeInput?.contextPackage?.selectedContext.length).toBeGreaterThan(0);
  357. expect(writeInput?.ruleStack?.activeOverrides).toHaveLength(1);
  358. const runtimeDir = join(state.bookDir(bookId), "story", "runtime");
  359. await expect(stat(join(runtimeDir, "chapter-0001.intent.md"))).resolves.toBeTruthy();
  360. await expect(stat(join(runtimeDir, "chapter-0001.context.json"))).resolves.toBeTruthy();
  361. await expect(stat(join(runtimeDir, "chapter-0001.rule-stack.yaml"))).resolves.toBeTruthy();
  362. await expect(stat(join(runtimeDir, "chapter-0001.trace.json"))).resolves.toBeTruthy();
  363. } finally {
  364. await rm(root, { recursive: true, force: true });
  365. }
  366. });
  367. it("reuses an existing planned intent for draft when no new context is provided in v2 mode", async () => {
  368. const { root, runner, state, bookId } = await createRunnerFixture({
  369. inputGovernanceMode: "v2",
  370. });
  371. await Promise.all([
  372. mkdir(join(state.bookDir(bookId), "story", "runtime"), { recursive: true }),
  373. writeFile(join(state.bookDir(bookId), "story", "current_focus.md"), "# Current Focus\n\nTrack the merchant guild trail.\n", "utf-8"),
  374. writeFile(join(state.bookDir(bookId), "story", "volume_outline.md"), "# Volume Outline\n\n## Chapter 1\nTrack the merchant guild trail.\n", "utf-8"),
  375. writeFile(join(state.bookDir(bookId), "story", "current_state.md"), "# Current State\n\n- Lin Yue still hides the broken oath token.\n", "utf-8"),
  376. writeFile(join(state.bookDir(bookId), "story", "story_bible.md"), "# Story Bible\n\n- The jade seal cannot be destroyed.\n", "utf-8"),
  377. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n\n- Why the mentor vanished after the trial.\n", "utf-8"),
  378. writeFile(
  379. join(state.bookDir(bookId), "story", "runtime", "chapter-0001.intent.md"),
  380. [
  381. "# Chapter Intent",
  382. "",
  383. "## Goal",
  384. "Bring the focus back to the mentor conflict.",
  385. "",
  386. "## Outline Node",
  387. "Track the merchant guild trail.",
  388. "",
  389. "## Must Keep",
  390. "- Lin Yue still hides the broken oath token.",
  391. "",
  392. "## Must Avoid",
  393. "- Do not reveal the mastermind",
  394. "",
  395. "## Style Emphasis",
  396. "- Keep the narrative emotionally close to the mentor conflict.",
  397. "",
  398. "## Conflicts",
  399. "- outline_vs_request: allow local outline deferral",
  400. "",
  401. "## Pending Hooks Snapshot",
  402. "- none",
  403. "",
  404. "## Chapter Summaries Snapshot",
  405. "- none",
  406. "",
  407. ].join("\n"),
  408. "utf-8",
  409. ),
  410. ]);
  411. const planChapter = vi.spyOn(PlannerAgent.prototype, "planChapter");
  412. const writeChapter = vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  413. createWriterOutput({
  414. chapterNumber: 1,
  415. content: "Governed draft body.",
  416. wordCount: "Governed draft body.".length,
  417. }),
  418. );
  419. try {
  420. await runner.writeDraft(bookId);
  421. expect(planChapter).not.toHaveBeenCalled();
  422. const writeInput = writeChapter.mock.calls[0]?.[0];
  423. expect(writeInput?.chapterIntent).toContain("Bring the focus back to the mentor conflict.");
  424. expect(writeInput?.ruleStack?.activeOverrides).toHaveLength(1);
  425. } finally {
  426. await rm(root, { recursive: true, force: true });
  427. }
  428. });
  429. sqliteIt("syncs current-state facts into memory.db after drafting a chapter", async () => {
  430. const { root, runner, state, bookId } = await createRunnerFixture();
  431. const chapterOneState = createStateCard({
  432. chapter: 1,
  433. location: "Ashen ferry crossing",
  434. protagonistState: "Lin Yue hides the broken oath token.",
  435. goal: "Find the vanished mentor before dawn.",
  436. conflict: "Mentor debt blocks every choice.",
  437. });
  438. await Promise.all([
  439. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  440. writeFile(
  441. join(state.bookDir(bookId), "story", "current_state.md"),
  442. createStateCard({
  443. chapter: 0,
  444. location: "Shrine outskirts",
  445. protagonistState: "Lin Yue begins with the oath token hidden.",
  446. goal: "Reach the trial city.",
  447. conflict: "The trial deadline is closing in.",
  448. }),
  449. "utf-8",
  450. ),
  451. ]);
  452. await state.snapshotState(bookId, 0);
  453. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  454. createWriterOutput({
  455. chapterNumber: 1,
  456. content: "Draft body.",
  457. wordCount: "Draft body.".length,
  458. updatedState: chapterOneState,
  459. updatedHooks: [
  460. "# Pending Hooks",
  461. "",
  462. "| hook_id | start_chapter | type | status | last_advanced_chapter | expected_payoff | notes |",
  463. "| --- | --- | --- | --- | --- | --- | --- |",
  464. "| mentor-debt | 1 | relationship | open | 1 | 6 | The mentor debt remains unresolved |",
  465. "",
  466. ].join("\n"),
  467. chapterSummary: [
  468. "| 1 | Ferry Debt | Lin Yue | Lin Yue crosses the ferry and recommits to the mentor trail | The debt hardens into the core conflict | mentor-debt advanced | tense | mainline |",
  469. ].join("\n"),
  470. }),
  471. );
  472. try {
  473. await runner.writeDraft(bookId);
  474. const memoryDb = new MemoryDB(state.bookDir(bookId));
  475. try {
  476. expect(memoryDb.getCurrentFacts()).toEqual(
  477. expect.arrayContaining([
  478. expect.objectContaining({
  479. predicate: "Current Conflict",
  480. object: "Mentor debt blocks every choice.",
  481. validFromChapter: 1,
  482. sourceChapter: 1,
  483. }),
  484. ]),
  485. );
  486. expect(memoryDb.getChapterCount()).toBe(1);
  487. expect(memoryDb.getActiveHooks()).toEqual(
  488. expect.arrayContaining([
  489. expect.objectContaining({
  490. hookId: "mentor-debt",
  491. status: "open",
  492. }),
  493. ]),
  494. );
  495. } finally {
  496. memoryDb.close();
  497. }
  498. } finally {
  499. await rm(root, { recursive: true, force: true });
  500. }
  501. });
  502. sqliteIt("syncs narrative memory from structured runtime state instead of stale markdown projections", async () => {
  503. const { root, runner, state, bookId } = await createRunnerFixture();
  504. const storyDir = join(state.bookDir(bookId), "story");
  505. const stateDir = join(storyDir, "state");
  506. await mkdir(stateDir, { recursive: true });
  507. await Promise.all([
  508. writeFile(
  509. join(storyDir, "chapter_summaries.md"),
  510. [
  511. "| chapter | title | characters | events | stateChanges | hookActivity | mood | chapterType |",
  512. "| --- | --- | --- | --- | --- | --- | --- | --- |",
  513. "| 1 | Markdown Summary | Lin Yue | Old markdown event | Old markdown state | markdown-hook advanced | tense | fallback |",
  514. "",
  515. ].join("\n"),
  516. "utf-8",
  517. ),
  518. writeFile(
  519. join(storyDir, "pending_hooks.md"),
  520. [
  521. "| hook_id | start_chapter | type | status | last_advanced | expected_payoff | notes |",
  522. "| --- | --- | --- | --- | --- | --- | --- |",
  523. "| markdown-hook | 1 | mystery | open | 1 | 4 | Old markdown hook |",
  524. "",
  525. ].join("\n"),
  526. "utf-8",
  527. ),
  528. writeFile(join(stateDir, "manifest.json"), JSON.stringify({
  529. schemaVersion: 2,
  530. language: "en",
  531. lastAppliedChapter: 3,
  532. projectionVersion: 1,
  533. migrationWarnings: [],
  534. }, null, 2), "utf-8"),
  535. writeFile(join(stateDir, "current_state.json"), JSON.stringify({
  536. chapter: 3,
  537. facts: [],
  538. }, null, 2), "utf-8"),
  539. writeFile(join(stateDir, "hooks.json"), JSON.stringify({
  540. hooks: [
  541. {
  542. hookId: "structured-hook",
  543. startChapter: 2,
  544. type: "relationship",
  545. status: "progressing",
  546. lastAdvancedChapter: 3,
  547. expectedPayoff: "Reveal the mentor ledger.",
  548. notes: "Structured hook should win.",
  549. },
  550. ],
  551. }, null, 2), "utf-8"),
  552. writeFile(join(stateDir, "chapter_summaries.json"), JSON.stringify({
  553. rows: [
  554. {
  555. chapter: 3,
  556. title: "Structured Summary",
  557. characters: "Lin Yue",
  558. events: "Structured runtime state event.",
  559. stateChanges: "Structured runtime state shift.",
  560. hookActivity: "structured-hook advanced",
  561. mood: "grim",
  562. chapterType: "mainline",
  563. },
  564. ],
  565. }, null, 2), "utf-8"),
  566. ]);
  567. try {
  568. await (runner as unknown as {
  569. syncNarrativeMemoryIndex: (targetBookId: string) => Promise<void>;
  570. }).syncNarrativeMemoryIndex(bookId);
  571. const memoryDb = new MemoryDB(state.bookDir(bookId));
  572. try {
  573. expect(memoryDb.getSummaries(1, 10)).toEqual([
  574. expect.objectContaining({
  575. chapter: 3,
  576. title: "Structured Summary",
  577. events: "Structured runtime state event.",
  578. }),
  579. ]);
  580. expect(memoryDb.getActiveHooks()).toEqual([
  581. expect.objectContaining({
  582. hookId: "structured-hook",
  583. status: "progressing",
  584. }),
  585. ]);
  586. } finally {
  587. memoryDb.close();
  588. }
  589. } finally {
  590. await rm(root, { recursive: true, force: true });
  591. }
  592. });
  593. it("uses a friendly fallback warning when sqlite memory indexing is unavailable", async () => {
  594. const { logger, warnings } = createCaptureLogger();
  595. const { root, runner, state, bookId } = await createRunnerFixture({
  596. logger,
  597. });
  598. await Promise.all([
  599. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  600. writeFile(
  601. join(state.bookDir(bookId), "story", "current_state.md"),
  602. createStateCard({
  603. chapter: 0,
  604. location: "Shrine outskirts",
  605. protagonistState: "Lin Yue begins with the oath token hidden.",
  606. goal: "Reach the trial city.",
  607. conflict: "The trial deadline is closing in.",
  608. }),
  609. "utf-8",
  610. ),
  611. ]);
  612. vi.spyOn(memoryDbModule, "MemoryDB").mockImplementation(() => {
  613. const error = new Error("No such built-in module: node:sqlite");
  614. (error as Error & { code?: string }).code = "ERR_UNKNOWN_BUILTIN_MODULE";
  615. throw error;
  616. });
  617. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  618. createWriterOutput({
  619. chapterNumber: 1,
  620. content: "Draft body.",
  621. wordCount: "Draft body.".length,
  622. }),
  623. );
  624. try {
  625. const result = await runner.writeDraft(bookId);
  626. expect(result.chapterNumber).toBe(1);
  627. expect(warnings).toContain(
  628. "当前 Node 运行时不支持 SQLite 记忆索引,继续使用 Markdown 回退方案。",
  629. );
  630. expect(warnings.join("\n")).not.toContain("node:sqlite");
  631. expect(warnings.join("\n")).not.toContain("ERR_UNKNOWN_BUILTIN_MODULE");
  632. expect(warnings.join("\n")).not.toContain("状态事实同步已跳过:");
  633. } finally {
  634. await rm(root, { recursive: true, force: true });
  635. }
  636. });
  637. it("does not misclassify generic runtime errors as sqlite-unavailable fallback", async () => {
  638. const { logger, warnings } = createCaptureLogger();
  639. const { root, runner, state, bookId } = await createRunnerFixture({
  640. logger,
  641. });
  642. await Promise.all([
  643. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  644. writeFile(
  645. join(state.bookDir(bookId), "story", "current_state.md"),
  646. createStateCard({
  647. chapter: 0,
  648. location: "Shrine outskirts",
  649. protagonistState: "Lin Yue begins with the oath token hidden.",
  650. goal: "Reach the trial city.",
  651. conflict: "The trial deadline is closing in.",
  652. }),
  653. "utf-8",
  654. ),
  655. ]);
  656. vi.spyOn(memoryDbModule, "MemoryDB").mockImplementation(() => {
  657. throw new Error("sync failed while handling cached node:sqlite telemetry text");
  658. });
  659. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  660. createWriterOutput({
  661. chapterNumber: 1,
  662. content: "Draft body.",
  663. wordCount: "Draft body.".length,
  664. }),
  665. );
  666. try {
  667. const result = await runner.writeDraft(bookId);
  668. expect(result.chapterNumber).toBe(1);
  669. expect(warnings.join("\n")).toContain("叙事记忆同步已跳过:");
  670. expect(warnings.join("\n")).not.toContain("当前 Node 运行时不支持 SQLite 记忆索引");
  671. } finally {
  672. await rm(root, { recursive: true, force: true });
  673. }
  674. });
  675. sqliteIt("recovers when sqlite-unavailable signature is transient and probe succeeds", async () => {
  676. const { logger, warnings } = createCaptureLogger();
  677. const { root, runner, state, bookId } = await createRunnerFixture({
  678. logger,
  679. inputGovernanceMode: "legacy",
  680. });
  681. await Promise.all([
  682. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  683. writeFile(
  684. join(state.bookDir(bookId), "story", "current_state.md"),
  685. createStateCard({
  686. chapter: 0,
  687. location: "Shrine outskirts",
  688. protagonistState: "Lin Yue begins with the oath token hidden.",
  689. goal: "Reach the trial city.",
  690. conflict: "The trial deadline is closing in.",
  691. }),
  692. "utf-8",
  693. ),
  694. ]);
  695. const RealMemoryDB = memoryDbModule.MemoryDB;
  696. let constructorCalls = 0;
  697. vi.spyOn(memoryDbModule, "MemoryDB").mockImplementation((...args: ConstructorParameters<typeof memoryDbModule.MemoryDB>) => {
  698. if (constructorCalls === 0) {
  699. constructorCalls += 1;
  700. const error = new Error("No such built-in module: node:sqlite");
  701. (error as Error & { code?: string }).code = "ERR_UNKNOWN_BUILTIN_MODULE";
  702. throw error;
  703. }
  704. constructorCalls += 1;
  705. return new RealMemoryDB(...args);
  706. });
  707. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  708. createWriterOutput({
  709. chapterNumber: 1,
  710. content: "Draft body.",
  711. wordCount: "Draft body.".length,
  712. chapterSummary: "| 1 | Draft summary | Lin Yue | Draft event | Draft shift | hook advanced | tense | transition |",
  713. updatedHooks: [
  714. "# Pending Hooks",
  715. "",
  716. "| hook_id | 起始章节 | 类型 | 状态 | 最近推进 | 预期回收 | 备注 |",
  717. "| --- | --- | --- | --- | --- | --- | --- |",
  718. "| mentor-debt | 1 | relationship | open | 1 | 3 | Draft hook |",
  719. ].join("\n"),
  720. }),
  721. );
  722. try {
  723. const result = await runner.writeDraft(bookId);
  724. expect(result.chapterNumber).toBe(1);
  725. expect(warnings.join("\n")).not.toContain("当前 Node 运行时不支持 SQLite 记忆索引");
  726. expect(warnings.join("\n")).not.toContain("叙事记忆同步已跳过");
  727. const memoryDb = new MemoryDB(state.bookDir(bookId));
  728. try {
  729. expect(memoryDb.getChapterCount()).toBe(1);
  730. expect(memoryDb.getActiveHooks()).toEqual(
  731. expect.arrayContaining([
  732. expect.objectContaining({
  733. hookId: "mentor-debt",
  734. status: "open",
  735. }),
  736. ]),
  737. );
  738. } finally {
  739. memoryDb.close();
  740. }
  741. } finally {
  742. await rm(root, { recursive: true, force: true });
  743. }
  744. });
  745. sqliteIt("retries transient sqlite busy errors during narrative memory sync", async () => {
  746. const { logger, warnings } = createCaptureLogger();
  747. const { root, runner, state, bookId } = await createRunnerFixture({
  748. logger,
  749. inputGovernanceMode: "legacy",
  750. });
  751. await Promise.all([
  752. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  753. writeFile(
  754. join(state.bookDir(bookId), "story", "current_state.md"),
  755. createStateCard({
  756. chapter: 0,
  757. location: "Shrine outskirts",
  758. protagonistState: "Lin Yue begins with the oath token hidden.",
  759. goal: "Reach the trial city.",
  760. conflict: "The trial deadline is closing in.",
  761. }),
  762. "utf-8",
  763. ),
  764. ]);
  765. const RealMemoryDB = memoryDbModule.MemoryDB;
  766. let constructorCalls = 0;
  767. vi.spyOn(memoryDbModule, "MemoryDB").mockImplementation((...args: ConstructorParameters<typeof memoryDbModule.MemoryDB>) => {
  768. if (constructorCalls === 0) {
  769. constructorCalls += 1;
  770. const error = new Error("database is locked");
  771. (error as Error & { code?: string }).code = "SQLITE_BUSY";
  772. throw error;
  773. }
  774. constructorCalls += 1;
  775. return new RealMemoryDB(...args);
  776. });
  777. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  778. createWriterOutput({
  779. chapterNumber: 1,
  780. content: "Draft body.",
  781. wordCount: "Draft body.".length,
  782. chapterSummary: "| 1 | Draft summary | Lin Yue | Draft event | Draft shift | hook advanced | tense | transition |",
  783. updatedHooks: [
  784. "# Pending Hooks",
  785. "",
  786. "| hook_id | 起始章节 | 类型 | 状态 | 最近推进 | 预期回收 | 备注 |",
  787. "| --- | --- | --- | --- | --- | --- | --- |",
  788. "| mentor-debt | 1 | relationship | open | 1 | 3 | Draft hook |",
  789. ].join("\n"),
  790. }),
  791. );
  792. try {
  793. const result = await runner.writeDraft(bookId);
  794. expect(result.chapterNumber).toBe(1);
  795. expect(warnings.join("\n")).not.toContain("当前 Node 运行时不支持 SQLite 记忆索引");
  796. expect(warnings.join("\n")).not.toContain("叙事记忆同步已跳过");
  797. const memoryDb = new MemoryDB(state.bookDir(bookId));
  798. try {
  799. expect(memoryDb.getChapterCount()).toBe(1);
  800. expect(memoryDb.getActiveHooks()).toEqual(
  801. expect.arrayContaining([
  802. expect.objectContaining({
  803. hookId: "mentor-debt",
  804. status: "open",
  805. }),
  806. ]),
  807. );
  808. } finally {
  809. memoryDb.close();
  810. }
  811. } finally {
  812. await rm(root, { recursive: true, force: true });
  813. }
  814. });
  815. it("logs explicit stage messages during book initialization", async () => {
  816. const { logger, infos } = createCaptureLogger();
  817. const { root, runner, state, bookId } = await createRunnerFixture({ logger });
  818. const book = await state.loadBookConfig(bookId);
  819. vi.spyOn(ArchitectAgent.prototype, "generateFoundation").mockResolvedValue({
  820. storyBible: "# Story Bible\n",
  821. volumeOutline: "# Volume Outline\n",
  822. bookRules: "---\nversion: \"1.0\"\n---\n\n# Book Rules\n",
  823. currentState: createStateCard({
  824. chapter: 0,
  825. location: "Ashen ferry crossing",
  826. protagonistState: "Lin Yue still hides the oath token.",
  827. goal: "Find the vanished mentor.",
  828. conflict: "The mentor debt is still personal.",
  829. }),
  830. pendingHooks: "# Pending Hooks\n",
  831. });
  832. try {
  833. await runner.initBook(book);
  834. expect(infos).toEqual(expect.arrayContaining([
  835. "阶段:保存书籍配置",
  836. "阶段:生成基础设定",
  837. "阶段:写入基础设定文件",
  838. "阶段:初始化控制文档",
  839. "阶段:创建初始快照",
  840. ]));
  841. } finally {
  842. await rm(root, { recursive: true, force: true });
  843. }
  844. });
  845. it("marks an outlining book as active after drafting the first chapter", async () => {
  846. const { root, runner, state, bookId } = await createRunnerFixture();
  847. const book = await state.loadBookConfig(bookId);
  848. await state.saveBookConfig(bookId, { ...book, status: "outlining" });
  849. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  850. createWriterOutput({
  851. chapterNumber: 1,
  852. content: "Draft body.",
  853. wordCount: "Draft body.".length,
  854. }),
  855. );
  856. try {
  857. await runner.writeDraft(bookId);
  858. const book = await state.loadBookConfig(bookId);
  859. expect(book.status).toBe("active");
  860. } finally {
  861. await rm(root, { recursive: true, force: true });
  862. }
  863. });
  864. it("routes writeNextChapter through planner and composer in v2 mode", async () => {
  865. const { root, runner, state, bookId } = await createRunnerFixture({
  866. inputGovernanceMode: "v2",
  867. });
  868. await Promise.all([
  869. writeFile(join(state.bookDir(bookId), "story", "current_focus.md"), "# Current Focus\n\nBring focus back to the mentor conflict.\n", "utf-8"),
  870. writeFile(join(state.bookDir(bookId), "story", "volume_outline.md"), "# Volume Outline\n\n## Chapter 1\nTrack the merchant guild trail.\n", "utf-8"),
  871. writeFile(join(state.bookDir(bookId), "story", "current_state.md"), "# Current State\n\n- Lin Yue still hides the broken oath token.\n", "utf-8"),
  872. writeFile(join(state.bookDir(bookId), "story", "story_bible.md"), "# Story Bible\n\n- The jade seal cannot be destroyed.\n", "utf-8"),
  873. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n\n- Why the mentor vanished after the trial.\n", "utf-8"),
  874. ]);
  875. const planChapter = vi.spyOn(PlannerAgent.prototype, "planChapter");
  876. const composeChapter = vi.spyOn(ComposerAgent.prototype, "composeChapter");
  877. const writeChapter = vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  878. createWriterOutput({
  879. chapterNumber: 1,
  880. content: "Governed pipeline draft.",
  881. wordCount: "Governed pipeline draft.".length,
  882. }),
  883. );
  884. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  885. createAuditResult({
  886. passed: true,
  887. issues: [],
  888. summary: "clean",
  889. }),
  890. );
  891. try {
  892. await runner.writeNextChapter(bookId, 220);
  893. expect(planChapter).toHaveBeenCalledTimes(1);
  894. expect(composeChapter).toHaveBeenCalledTimes(1);
  895. const writeInput = writeChapter.mock.calls[0]?.[0];
  896. expect(writeInput?.chapterIntent).toContain("# Chapter Intent");
  897. expect(writeInput?.contextPackage?.selectedContext.length).toBeGreaterThan(0);
  898. } finally {
  899. await rm(root, { recursive: true, force: true });
  900. }
  901. });
  902. it("re-plans instead of reusing a persisted invalid intent artifact in v2 mode", async () => {
  903. const { root, runner, state, bookId } = await createRunnerFixture({
  904. inputGovernanceMode: "v2",
  905. });
  906. const storyDir = join(state.bookDir(bookId), "story");
  907. const runtimeDir = join(storyDir, "runtime");
  908. await mkdir(runtimeDir, { recursive: true });
  909. await Promise.all([
  910. writeFile(join(storyDir, "current_focus.md"), "# Current Focus\n\nBring focus back to the mentor conflict.\n", "utf-8"),
  911. writeFile(
  912. join(storyDir, "volume_outline.md"),
  913. [
  914. "# Volume Outline",
  915. "",
  916. "### Golden First Three Chapters Rule",
  917. "",
  918. "**Chapter 1:**",
  919. "Track the merchant guild trail.",
  920. "",
  921. ].join("\n"),
  922. "utf-8",
  923. ),
  924. writeFile(join(storyDir, "current_state.md"), "# Current State\n\n- Lin Yue still hides the broken oath token.\n", "utf-8"),
  925. writeFile(join(storyDir, "story_bible.md"), "# Story Bible\n\n- The jade seal cannot be destroyed.\n", "utf-8"),
  926. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n\n- Why the mentor vanished after the trial.\n", "utf-8"),
  927. writeFile(
  928. join(runtimeDir, "chapter-0001.intent.md"),
  929. [
  930. "# Chapter Intent",
  931. "",
  932. "## Goal",
  933. "**",
  934. "",
  935. "## Outline Node",
  936. "**",
  937. "",
  938. "## Must Keep",
  939. "- none",
  940. "",
  941. "## Must Avoid",
  942. "- none",
  943. "",
  944. "## Style Emphasis",
  945. "- none",
  946. "",
  947. "## Conflicts",
  948. "- none",
  949. "",
  950. ].join("\n"),
  951. "utf-8",
  952. ),
  953. ]);
  954. const planChapter = vi.spyOn(PlannerAgent.prototype, "planChapter");
  955. const writeChapter = vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  956. createWriterOutput({
  957. chapterNumber: 1,
  958. content: "Governed pipeline draft.",
  959. wordCount: "Governed pipeline draft.".length,
  960. }),
  961. );
  962. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  963. createAuditResult({
  964. passed: true,
  965. issues: [],
  966. summary: "clean",
  967. }),
  968. );
  969. try {
  970. await runner.writeNextChapter(bookId, 220);
  971. expect(planChapter).toHaveBeenCalledTimes(1);
  972. const writeInput = writeChapter.mock.calls[0]?.[0];
  973. expect(writeInput?.chapterIntent).toContain("Track the merchant guild trail.");
  974. expect(writeInput?.chapterIntent).not.toContain("\n**\n");
  975. } finally {
  976. await rm(root, { recursive: true, force: true });
  977. }
  978. });
  979. it("logs explicit stage messages during writeNextChapter", async () => {
  980. const { logger, infos } = createCaptureLogger();
  981. const { root, runner, state, bookId } = await createRunnerFixture({
  982. inputGovernanceMode: "v2",
  983. logger,
  984. });
  985. await Promise.all([
  986. writeFile(join(state.bookDir(bookId), "story", "current_focus.md"), "# Current Focus\n\nBring focus back to the mentor conflict.\n", "utf-8"),
  987. writeFile(join(state.bookDir(bookId), "story", "volume_outline.md"), "# Volume Outline\n\n## Chapter 1\nTrack the merchant guild trail.\n", "utf-8"),
  988. writeFile(join(state.bookDir(bookId), "story", "current_state.md"), "# Current State\n\n- Lin Yue still hides the broken oath token.\n", "utf-8"),
  989. writeFile(join(state.bookDir(bookId), "story", "story_bible.md"), "# Story Bible\n\n- The jade seal cannot be destroyed.\n", "utf-8"),
  990. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n\n- Why the mentor vanished after the trial.\n", "utf-8"),
  991. ]);
  992. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  993. createWriterOutput({
  994. chapterNumber: 1,
  995. content: "Governed pipeline draft.",
  996. wordCount: "Governed pipeline draft.".length,
  997. }),
  998. );
  999. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1000. createAuditResult({
  1001. passed: true,
  1002. issues: [],
  1003. summary: "clean",
  1004. }),
  1005. );
  1006. try {
  1007. await runner.writeNextChapter(bookId, 220);
  1008. expect(infos).toEqual(expect.arrayContaining([
  1009. "阶段:准备章节输入",
  1010. "阶段:撰写章节草稿",
  1011. "阶段:审计草稿",
  1012. "阶段:落盘最终章节",
  1013. "阶段:生成最终真相文件",
  1014. "阶段:校验真相文件变更",
  1015. "阶段:同步记忆索引",
  1016. "阶段:更新章节索引与快照",
  1017. ]));
  1018. } finally {
  1019. await rm(root, { recursive: true, force: true });
  1020. }
  1021. });
  1022. it("logs English stage messages during writeNextChapter for English books", async () => {
  1023. const { logger, infos } = createCaptureLogger();
  1024. const { root, runner, state, bookId } = await createRunnerFixture({
  1025. inputGovernanceMode: "v2",
  1026. logger,
  1027. });
  1028. const englishBook = {
  1029. ...(await state.loadBookConfig(bookId)),
  1030. genre: "other",
  1031. language: "en" as const,
  1032. chapterWordCount: 220,
  1033. };
  1034. await state.saveBookConfig(bookId, englishBook);
  1035. await Promise.all([
  1036. writeFile(join(state.bookDir(bookId), "story", "current_focus.md"), "# Current Focus\n\nBring focus back to the mentor conflict.\n", "utf-8"),
  1037. writeFile(join(state.bookDir(bookId), "story", "volume_outline.md"), "# Volume Outline\n\n## Chapter 1\nTrack the merchant guild trail.\n", "utf-8"),
  1038. writeFile(join(state.bookDir(bookId), "story", "current_state.md"), "# Current State\n\n- Lin Yue still hides the broken oath token.\n", "utf-8"),
  1039. writeFile(join(state.bookDir(bookId), "story", "story_bible.md"), "# Story Bible\n\n- The jade seal cannot be destroyed.\n", "utf-8"),
  1040. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n\n- Why the mentor vanished after the trial.\n", "utf-8"),
  1041. ]);
  1042. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1043. createWriterOutput({
  1044. chapterNumber: 1,
  1045. content: "Governed pipeline draft.",
  1046. wordCount: countChapterLength("Governed pipeline draft.", "en_words"),
  1047. }),
  1048. );
  1049. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1050. createAuditResult({
  1051. passed: true,
  1052. issues: [],
  1053. summary: "clean",
  1054. }),
  1055. );
  1056. try {
  1057. await runner.writeNextChapter(bookId, 220);
  1058. expect(infos).toEqual(expect.arrayContaining([
  1059. "Stage: preparing chapter inputs",
  1060. "Stage: writing chapter draft",
  1061. "Stage: auditing draft",
  1062. "Stage: persisting final chapter",
  1063. "Stage: rebuilding final truth files",
  1064. "Stage: validating truth file updates",
  1065. "Stage: syncing memory indexes",
  1066. "Stage: updating chapter index and snapshots",
  1067. ]));
  1068. expect(infos.join("\n")).not.toContain("阶段:");
  1069. } finally {
  1070. await rm(root, { recursive: true, force: true });
  1071. }
  1072. });
  1073. it("writes English audit drift correction blocks for English books", async () => {
  1074. const { root, runner, state, bookId } = await createRunnerFixture();
  1075. const englishBook = {
  1076. ...(await state.loadBookConfig(bookId)),
  1077. genre: "other",
  1078. language: "en" as const,
  1079. chapterWordCount: 220,
  1080. };
  1081. await state.saveBookConfig(bookId, englishBook);
  1082. await Promise.all([
  1083. writeFile(join(state.bookDir(bookId), "story", "current_focus.md"), "# Current Focus\n\nKeep the pressure on the harbor debt.\n", "utf-8"),
  1084. writeFile(join(state.bookDir(bookId), "story", "current_state.md"), createStateCard({
  1085. chapter: 0,
  1086. location: "Harbor gate",
  1087. protagonistState: "Lin Yue is tracking the vanished mentor.",
  1088. goal: "Reach the sealed berth.",
  1089. conflict: "The harbor debt keeps pulling him sideways.",
  1090. }), "utf-8"),
  1091. writeFile(join(state.bookDir(bookId), "story", "story_bible.md"), "# Story Bible\n\n- The harbor seal cannot be forged.\n", "utf-8"),
  1092. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n\n- The vanished mentor still owes a debt.\n", "utf-8"),
  1093. ]);
  1094. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1095. createWriterOutput({
  1096. chapterNumber: 1,
  1097. content: "Lin Yue reached the sealed berth before dawn.",
  1098. wordCount: countChapterLength("Lin Yue reached the sealed berth before dawn.", "en_words"),
  1099. updatedState: createStateCard({
  1100. chapter: 1,
  1101. location: "Sealed berth",
  1102. protagonistState: "Lin Yue is winded but focused.",
  1103. goal: "Inspect the berth before the guild arrives.",
  1104. conflict: "The harbor debt is still active.",
  1105. }),
  1106. updatedHooks: "# Pending Hooks\n\n- The vanished mentor still owes a debt.\n",
  1107. }),
  1108. );
  1109. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1110. createAuditResult({
  1111. passed: true,
  1112. issues: [{
  1113. severity: "warning",
  1114. category: "continuity",
  1115. description: "Keep the berth timing precise in the next chapter.",
  1116. suggestion: "Avoid skipping the dawn transition.",
  1117. }],
  1118. summary: "warning only",
  1119. }),
  1120. );
  1121. try {
  1122. await runner.writeNextChapter(bookId, 220);
  1123. const currentState = await readFile(join(state.bookDir(bookId), "story", "current_state.md"), "utf-8");
  1124. expect(currentState).toContain("## Audit Drift Correction");
  1125. expect(currentState).toContain("> Chapter 1 audit found the following issues");
  1126. expect(currentState).not.toContain("## 审计纠偏");
  1127. expect(currentState).not.toContain("下一章写作前参照");
  1128. } finally {
  1129. await rm(root, { recursive: true, force: true });
  1130. }
  1131. });
  1132. it("passes reduced control inputs into auditor and reviser in v2 mode", async () => {
  1133. const { root, runner, state, bookId } = await createRunnerFixture({
  1134. inputGovernanceMode: "v2",
  1135. });
  1136. await Promise.all([
  1137. writeFile(join(state.bookDir(bookId), "story", "current_focus.md"), "# Current Focus\n\nBring focus back to the mentor conflict.\n", "utf-8"),
  1138. writeFile(join(state.bookDir(bookId), "story", "volume_outline.md"), "# Volume Outline\n\n## Chapter 1\nTrack the merchant guild trail.\n", "utf-8"),
  1139. writeFile(join(state.bookDir(bookId), "story", "current_state.md"), "# Current State\n\n- Lin Yue still hides the broken oath token.\n", "utf-8"),
  1140. writeFile(join(state.bookDir(bookId), "story", "story_bible.md"), "# Story Bible\n\n- The jade seal cannot be destroyed.\n", "utf-8"),
  1141. writeFile(join(state.bookDir(bookId), "story", "pending_hooks.md"), "# Pending Hooks\n\n- Why the mentor vanished after the trial.\n", "utf-8"),
  1142. ]);
  1143. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1144. createWriterOutput({
  1145. chapterNumber: 1,
  1146. content: "Needs governed revision.",
  1147. wordCount: "Needs governed revision.".length,
  1148. }),
  1149. );
  1150. const auditChapter = vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1151. createAuditResult({
  1152. passed: false,
  1153. issues: [CRITICAL_ISSUE],
  1154. summary: "needs revision",
  1155. }),
  1156. );
  1157. const reviseChapter = vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  1158. createReviseOutput({
  1159. revisedContent: "Governed revised content.",
  1160. wordCount: "Governed revised content.".length,
  1161. }),
  1162. );
  1163. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  1164. createAnalyzedOutput({
  1165. content: "Governed revised content.",
  1166. wordCount: "Governed revised content.".length,
  1167. }),
  1168. );
  1169. try {
  1170. await runner.writeNextChapter(bookId, 220);
  1171. expect(auditChapter.mock.calls[0]?.[4]).toMatchObject({
  1172. chapterIntent: expect.stringContaining("# Chapter Intent"),
  1173. contextPackage: expect.objectContaining({
  1174. selectedContext: expect.any(Array),
  1175. }),
  1176. ruleStack: expect.objectContaining({
  1177. activeOverrides: expect.any(Array),
  1178. }),
  1179. });
  1180. expect(reviseChapter.mock.calls[0]?.[6]).toMatchObject({
  1181. chapterIntent: expect.stringContaining("# Chapter Intent"),
  1182. contextPackage: expect.objectContaining({
  1183. selectedContext: expect.any(Array),
  1184. }),
  1185. ruleStack: expect.objectContaining({
  1186. activeOverrides: expect.any(Array),
  1187. }),
  1188. lengthSpec: expect.objectContaining({
  1189. target: 220,
  1190. softMin: 190,
  1191. softMax: 250,
  1192. }),
  1193. });
  1194. } finally {
  1195. await rm(root, { recursive: true, force: true });
  1196. }
  1197. });
  1198. it("normalizes revised output once before re-audit when it leaves the target band", async () => {
  1199. const { root, runner, bookId } = await createRunnerFixture();
  1200. const writerDraft = "中段正文。".repeat(40);
  1201. const overlongRevision = "修订后正文。".repeat(60);
  1202. const normalizedRevision = "归一正文。".repeat(40);
  1203. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1204. createWriterOutput({
  1205. content: writerDraft,
  1206. wordCount: writerDraft.length,
  1207. }),
  1208. );
  1209. const auditChapter = vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  1210. .mockResolvedValueOnce(
  1211. createAuditResult({
  1212. passed: false,
  1213. issues: [CRITICAL_ISSUE],
  1214. summary: "needs revision",
  1215. }),
  1216. )
  1217. .mockResolvedValueOnce(
  1218. createAuditResult({
  1219. passed: true,
  1220. issues: [],
  1221. summary: "clean",
  1222. }),
  1223. );
  1224. const reviseChapter = vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  1225. createReviseOutput({
  1226. revisedContent: overlongRevision,
  1227. wordCount: overlongRevision.length,
  1228. }),
  1229. );
  1230. const normalizeChapter = vi.mocked(
  1231. LengthNormalizerAgent.prototype.normalizeChapter,
  1232. ).mockResolvedValue({
  1233. normalizedContent: normalizedRevision,
  1234. finalCount: normalizedRevision.length,
  1235. applied: true,
  1236. mode: "compress",
  1237. tokenUsage: ZERO_USAGE,
  1238. });
  1239. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  1240. createAnalyzedOutput({
  1241. content: normalizedRevision,
  1242. wordCount: normalizedRevision.length,
  1243. }),
  1244. );
  1245. try {
  1246. await runner.writeNextChapter(bookId, 220);
  1247. expect(reviseChapter.mock.calls[0]?.[6]).toMatchObject({
  1248. lengthSpec: expect.objectContaining({
  1249. target: 220,
  1250. softMin: 190,
  1251. softMax: 250,
  1252. }),
  1253. });
  1254. expect(normalizeChapter).toHaveBeenCalledTimes(1);
  1255. expect(normalizeChapter.mock.calls[0]?.[0]).toMatchObject({
  1256. chapterContent: overlongRevision,
  1257. lengthSpec: expect.objectContaining({
  1258. target: 220,
  1259. }),
  1260. });
  1261. expect(auditChapter.mock.calls[1]?.[1]).toBe(normalizedRevision);
  1262. } finally {
  1263. await rm(root, { recursive: true, force: true });
  1264. }
  1265. });
  1266. it("normalizes overlong writer output once before audit", async () => {
  1267. const { root, runner, bookId } = await createRunnerFixture();
  1268. const overlongDraft = "冗余句子。".repeat(60);
  1269. const normalizedDraft = "压缩后的正文。".repeat(12);
  1270. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1271. createWriterOutput({
  1272. chapterNumber: 1,
  1273. content: overlongDraft,
  1274. wordCount: overlongDraft.length,
  1275. }),
  1276. );
  1277. const normalizeChapter = vi.mocked(
  1278. LengthNormalizerAgent.prototype.normalizeChapter,
  1279. ).mockResolvedValue({
  1280. normalizedContent: normalizedDraft,
  1281. finalCount: normalizedDraft.length,
  1282. applied: true,
  1283. mode: "compress",
  1284. tokenUsage: ZERO_USAGE,
  1285. });
  1286. const auditChapter = vi.spyOn(
  1287. ContinuityAuditor.prototype,
  1288. "auditChapter",
  1289. ).mockResolvedValue(
  1290. createAuditResult({
  1291. passed: true,
  1292. issues: [],
  1293. summary: "clean",
  1294. }),
  1295. );
  1296. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  1297. createAnalyzedOutput({
  1298. content: normalizedDraft,
  1299. wordCount: normalizedDraft.length,
  1300. }),
  1301. );
  1302. try {
  1303. await runner.writeNextChapter(bookId, 220);
  1304. expect(normalizeChapter).toHaveBeenCalledTimes(1);
  1305. expect(auditChapter.mock.calls[0]?.[1]).toBe(normalizedDraft);
  1306. } finally {
  1307. await rm(root, { recursive: true, force: true });
  1308. }
  1309. });
  1310. it("normalizes short writer output once before audit", async () => {
  1311. const { root, runner, bookId } = await createRunnerFixture();
  1312. const shortDraft = "短句。".repeat(20);
  1313. const normalizedDraft = "补足后的正文。".repeat(15);
  1314. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1315. createWriterOutput({
  1316. chapterNumber: 1,
  1317. content: shortDraft,
  1318. wordCount: shortDraft.length,
  1319. }),
  1320. );
  1321. const normalizeChapter = vi.mocked(
  1322. LengthNormalizerAgent.prototype.normalizeChapter,
  1323. ).mockResolvedValue({
  1324. normalizedContent: normalizedDraft,
  1325. finalCount: normalizedDraft.length,
  1326. applied: true,
  1327. mode: "expand",
  1328. tokenUsage: ZERO_USAGE,
  1329. });
  1330. const auditChapter = vi.spyOn(
  1331. ContinuityAuditor.prototype,
  1332. "auditChapter",
  1333. ).mockResolvedValue(
  1334. createAuditResult({
  1335. passed: true,
  1336. issues: [],
  1337. summary: "clean",
  1338. }),
  1339. );
  1340. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  1341. createAnalyzedOutput({
  1342. content: normalizedDraft,
  1343. wordCount: normalizedDraft.length,
  1344. }),
  1345. );
  1346. try {
  1347. await runner.writeNextChapter(bookId, 220);
  1348. expect(normalizeChapter).toHaveBeenCalledTimes(1);
  1349. expect(normalizeChapter.mock.calls[0]?.[0]).toMatchObject({
  1350. chapterContent: shortDraft,
  1351. lengthSpec: expect.objectContaining({
  1352. target: 220,
  1353. softMin: 190,
  1354. softMax: 250,
  1355. }),
  1356. });
  1357. expect(auditChapter.mock.calls[0]?.[1]).toBe(normalizedDraft);
  1358. } finally {
  1359. await rm(root, { recursive: true, force: true });
  1360. }
  1361. });
  1362. it("records a length warning when a single normalize pass still misses the hard range", async () => {
  1363. const { root, runner, state, bookId } = await createRunnerFixture();
  1364. const overlongDraft = "冗余句子。".repeat(60);
  1365. const stillOverHard = "仍然过长。".repeat(70);
  1366. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1367. createWriterOutput({
  1368. chapterNumber: 1,
  1369. content: overlongDraft,
  1370. wordCount: overlongDraft.length,
  1371. }),
  1372. );
  1373. const normalizeChapter = vi.mocked(
  1374. LengthNormalizerAgent.prototype.normalizeChapter,
  1375. ).mockResolvedValue({
  1376. normalizedContent: stillOverHard,
  1377. finalCount: stillOverHard.length,
  1378. applied: true,
  1379. mode: "compress",
  1380. tokenUsage: ZERO_USAGE,
  1381. });
  1382. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1383. createAuditResult({
  1384. passed: true,
  1385. issues: [],
  1386. summary: "clean",
  1387. }),
  1388. );
  1389. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  1390. createAnalyzedOutput({
  1391. content: stillOverHard,
  1392. wordCount: stillOverHard.length,
  1393. }),
  1394. );
  1395. try {
  1396. const result = await runner.writeNextChapter(bookId, 220);
  1397. const chapterIndex = await state.loadChapterIndex(bookId);
  1398. const chapterMeta = chapterIndex.find((entry) => entry.number === 1);
  1399. expect(normalizeChapter).toHaveBeenCalledTimes(1);
  1400. expect((result as { lengthWarnings?: ReadonlyArray<string> }).lengthWarnings?.[0]).toContain(
  1401. "超出硬区间",
  1402. );
  1403. expect((result as { lengthTelemetry?: { finalCount: number } }).lengthTelemetry?.finalCount).toBe(
  1404. stillOverHard.length,
  1405. );
  1406. expect(chapterMeta?.lengthWarnings?.[0]).toContain("超出硬区间");
  1407. expect(chapterMeta?.lengthTelemetry?.lengthWarning).toBe(true);
  1408. } finally {
  1409. await rm(root, { recursive: true, force: true });
  1410. }
  1411. });
  1412. it("keeps the last actionable audit issues when re-audit returns failed with no issues", async () => {
  1413. const { root, runner, state, bookId } = await createRunnerFixture({
  1414. inputGovernanceMode: "legacy",
  1415. });
  1416. const storyDir = join(state.bookDir(bookId), "story");
  1417. const draftBody = "甲".repeat(210);
  1418. const revisedBody = "乙".repeat(215);
  1419. await Promise.all([
  1420. writeFile(join(storyDir, "current_state.md"), createStateCard({
  1421. chapter: 0,
  1422. location: "Ashen ferry crossing",
  1423. protagonistState: "Lin Yue still hides the oath token.",
  1424. goal: "Find the vanished mentor.",
  1425. conflict: "The mentor debt is still personal.",
  1426. }), "utf-8"),
  1427. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  1428. ]);
  1429. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1430. createWriterOutput({
  1431. content: draftBody,
  1432. wordCount: draftBody.length,
  1433. }),
  1434. );
  1435. vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  1436. .mockResolvedValueOnce(
  1437. createAuditResult({
  1438. passed: false,
  1439. issues: [CRITICAL_ISSUE],
  1440. summary: "needs revision",
  1441. }),
  1442. )
  1443. .mockResolvedValueOnce(
  1444. createAuditResult({
  1445. passed: false,
  1446. issues: [],
  1447. summary: "",
  1448. }),
  1449. );
  1450. vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  1451. createReviseOutput({
  1452. revisedContent: revisedBody,
  1453. wordCount: revisedBody.length,
  1454. fixedIssues: ["- tightened continuity."],
  1455. }),
  1456. );
  1457. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  1458. createAnalyzedOutput({
  1459. content: revisedBody,
  1460. wordCount: revisedBody.length,
  1461. }),
  1462. );
  1463. try {
  1464. const result = await runner.writeNextChapter(bookId, 220);
  1465. const savedIndex = await state.loadChapterIndex(bookId);
  1466. expect(result.status).toBe("audit-failed");
  1467. expect(result.auditResult.summary).toBe("needs revision");
  1468. expect(result.auditResult.issues).toEqual([CRITICAL_ISSUE]);
  1469. expect(savedIndex[0]?.auditIssues).toEqual([
  1470. `[critical] ${CRITICAL_ISSUE.description}`,
  1471. ]);
  1472. } finally {
  1473. await rm(root, { recursive: true, force: true });
  1474. }
  1475. });
  1476. it("preserves the legacy fallback when input governance mode is legacy", async () => {
  1477. const { root, runner, bookId } = await createRunnerFixture({
  1478. inputGovernanceMode: "legacy",
  1479. externalContext: "Legacy focus only.",
  1480. });
  1481. const planChapter = vi.spyOn(PlannerAgent.prototype, "planChapter");
  1482. const composeChapter = vi.spyOn(ComposerAgent.prototype, "composeChapter");
  1483. const writeChapter = vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1484. createWriterOutput({
  1485. chapterNumber: 1,
  1486. content: "Legacy draft body.",
  1487. wordCount: "Legacy draft body.".length,
  1488. }),
  1489. );
  1490. try {
  1491. await runner.writeDraft(bookId);
  1492. expect(planChapter).not.toHaveBeenCalled();
  1493. expect(composeChapter).not.toHaveBeenCalled();
  1494. const writeInput = writeChapter.mock.calls[0]?.[0];
  1495. expect(writeInput?.externalContext).toBe("Legacy focus only.");
  1496. expect(writeInput?.chapterIntent).toBeUndefined();
  1497. expect(writeInput?.contextPackage).toBeUndefined();
  1498. expect(writeInput?.ruleStack).toBeUndefined();
  1499. } finally {
  1500. await rm(root, { recursive: true, force: true });
  1501. }
  1502. });
  1503. it("uses the latest revised content as the input for follow-up spot-fix revisions", async () => {
  1504. const { root, runner, bookId } = await createRunnerFixture();
  1505. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1506. createWriterOutput({
  1507. content: "Original draft body.",
  1508. wordCount: "Original draft body.".length,
  1509. postWriteErrors: [
  1510. {
  1511. severity: "error",
  1512. rule: "post-write",
  1513. description: "Needs a deterministic fix",
  1514. suggestion: "Repair the line",
  1515. },
  1516. ],
  1517. }),
  1518. );
  1519. vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  1520. .mockResolvedValueOnce(createAuditResult({
  1521. passed: false,
  1522. issues: [CRITICAL_ISSUE],
  1523. summary: "needs another revision",
  1524. }))
  1525. .mockResolvedValueOnce(createAuditResult({
  1526. passed: true,
  1527. issues: [],
  1528. summary: "clean",
  1529. }));
  1530. const reviseChapter = vi.spyOn(ReviserAgent.prototype, "reviseChapter")
  1531. .mockResolvedValueOnce(createReviseOutput({
  1532. revisedContent: "After first fix.",
  1533. wordCount: "After first fix.".length,
  1534. }))
  1535. .mockResolvedValueOnce(createReviseOutput({
  1536. revisedContent: "After second fix.",
  1537. wordCount: "After second fix.".length,
  1538. }));
  1539. vi.spyOn(WriterAgent.prototype, "saveChapter").mockResolvedValue(undefined);
  1540. vi.spyOn(WriterAgent.prototype, "saveNewTruthFiles").mockResolvedValue(undefined);
  1541. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  1542. createAnalyzedOutput({
  1543. content: "After second fix.",
  1544. wordCount: "After second fix.".length,
  1545. }),
  1546. );
  1547. await runner.writeNextChapter(bookId);
  1548. expect(reviseChapter).toHaveBeenCalledTimes(2);
  1549. expect(reviseChapter.mock.calls[1]?.[1]).toBe("After first fix.");
  1550. await rm(root, { recursive: true, force: true });
  1551. });
  1552. it("persists truth files derived from the final revised chapter", async () => {
  1553. const { root, runner, state, bookId } = await createRunnerFixture();
  1554. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1555. createWriterOutput({
  1556. content: "Original draft body.",
  1557. wordCount: "Original draft body.".length,
  1558. updatedState: "original state",
  1559. updatedLedger: "original ledger",
  1560. updatedHooks: "original hooks",
  1561. chapterSummary: "| 1 | Original summary |",
  1562. updatedSubplots: "original subplots",
  1563. updatedEmotionalArcs: "original emotions",
  1564. updatedCharacterMatrix: "original matrix",
  1565. postWriteErrors: [
  1566. {
  1567. severity: "error",
  1568. rule: "post-write",
  1569. description: "Needs a deterministic fix",
  1570. suggestion: "Repair the line",
  1571. },
  1572. ],
  1573. }),
  1574. );
  1575. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1576. createAuditResult({
  1577. passed: true,
  1578. issues: [],
  1579. summary: "clean",
  1580. }),
  1581. );
  1582. vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  1583. createReviseOutput({
  1584. revisedContent: "Final revised body.",
  1585. wordCount: "Final revised body.".length,
  1586. }),
  1587. );
  1588. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  1589. createAnalyzedOutput({
  1590. content: "Final revised body.",
  1591. wordCount: "Final revised body.".length,
  1592. updatedState: "final analyzed state",
  1593. updatedLedger: "final analyzed ledger",
  1594. updatedHooks: "final analyzed hooks",
  1595. chapterSummary: "| 1 | Final analyzed summary |",
  1596. updatedSubplots: "final analyzed subplots",
  1597. updatedEmotionalArcs: "final analyzed emotions",
  1598. updatedCharacterMatrix: "final analyzed matrix",
  1599. }),
  1600. );
  1601. await runner.writeNextChapter(bookId);
  1602. const storyDir = join(state.bookDir(bookId), "story");
  1603. await expect(readFile(join(storyDir, "current_state.md"), "utf-8"))
  1604. .resolves.toContain("final analyzed state");
  1605. await expect(readFile(join(storyDir, "pending_hooks.md"), "utf-8"))
  1606. .resolves.toContain("final analyzed hooks");
  1607. await expect(readFile(join(storyDir, "particle_ledger.md"), "utf-8"))
  1608. .resolves.toContain("final analyzed ledger");
  1609. await expect(readFile(join(storyDir, "chapter_summaries.md"), "utf-8"))
  1610. .resolves.toContain("Final analyzed summary");
  1611. await expect(readFile(join(storyDir, "subplot_board.md"), "utf-8"))
  1612. .resolves.toContain("final analyzed subplots");
  1613. await expect(readFile(join(storyDir, "emotional_arcs.md"), "utf-8"))
  1614. .resolves.toContain("final analyzed emotions");
  1615. await expect(readFile(join(storyDir, "character_matrix.md"), "utf-8"))
  1616. .resolves.toContain("final analyzed matrix");
  1617. await rm(root, { recursive: true, force: true });
  1618. });
  1619. it("persists structured runtime state and rendered projections from writer delta output", async () => {
  1620. const { root, runner, state, bookId } = await createRunnerFixture({
  1621. inputGovernanceMode: "legacy",
  1622. });
  1623. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1624. createWriterOutput({
  1625. content: "Lin Yue follows the debt into the river-port ledger.",
  1626. wordCount: countChapterLength("Lin Yue follows the debt into the river-port ledger.", "en_words"),
  1627. postWriteErrors: [],
  1628. postWriteWarnings: [],
  1629. runtimeStateDelta: {
  1630. chapter: 1,
  1631. currentStatePatch: {
  1632. currentGoal: "Follow the debt through the river-port ledger.",
  1633. currentConflict: "Guild pressure keeps pulling against the debt trail.",
  1634. },
  1635. hookOps: {
  1636. upsert: [
  1637. {
  1638. hookId: "mentor-debt",
  1639. startChapter: 1,
  1640. type: "relationship",
  1641. status: "open",
  1642. lastAdvancedChapter: 1,
  1643. expectedPayoff: "Reveal why the mentor vanished.",
  1644. notes: "The river-port ledger sharpens the debt line.",
  1645. },
  1646. ],
  1647. resolve: [],
  1648. defer: [],
  1649. },
  1650. chapterSummary: {
  1651. chapter: 1,
  1652. title: "River Ledger",
  1653. characters: "Lin Yue",
  1654. events: "Lin Yue follows the debt into the river-port ledger.",
  1655. stateChanges: "The debt line sharpens.",
  1656. hookActivity: "mentor-debt advanced",
  1657. mood: "tense",
  1658. chapterType: "investigation",
  1659. },
  1660. subplotOps: [],
  1661. emotionalArcOps: [],
  1662. characterMatrixOps: [],
  1663. notes: [],
  1664. },
  1665. }),
  1666. );
  1667. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1668. createAuditResult({
  1669. passed: true,
  1670. issues: [],
  1671. summary: "clean",
  1672. }),
  1673. );
  1674. await runner.writeNextChapter(bookId);
  1675. const storyDir = join(state.bookDir(bookId), "story");
  1676. const currentState = await readFile(join(storyDir, "current_state.md"), "utf-8");
  1677. const hooks = await readFile(join(storyDir, "pending_hooks.md"), "utf-8");
  1678. const summaries = await readFile(join(storyDir, "chapter_summaries.md"), "utf-8");
  1679. const manifest = JSON.parse(await readFile(join(storyDir, "state", "manifest.json"), "utf-8"));
  1680. const stateCurrent = JSON.parse(await readFile(join(storyDir, "state", "current_state.json"), "utf-8"));
  1681. const stateHooks = JSON.parse(await readFile(join(storyDir, "state", "hooks.json"), "utf-8"));
  1682. const stateSummaries = JSON.parse(await readFile(join(storyDir, "state", "chapter_summaries.json"), "utf-8"));
  1683. expect(currentState).toContain("Follow the debt through the river-port ledger.");
  1684. expect(hooks).toContain("mentor-debt");
  1685. expect(summaries).toContain("River Ledger");
  1686. expect(manifest.lastAppliedChapter).toBe(1);
  1687. expect(stateCurrent.chapter).toBe(1);
  1688. expect(stateHooks.hooks[0]?.hookId).toBe("mentor-debt");
  1689. expect(stateSummaries.rows[0]?.title).toBe("River Ledger");
  1690. await rm(root, { recursive: true, force: true });
  1691. });
  1692. it("does not corrupt persisted runtime state when writer delta is invalid", async () => {
  1693. const { root, runner, state, bookId } = await createRunnerFixture({
  1694. inputGovernanceMode: "legacy",
  1695. });
  1696. const storyDir = join(state.bookDir(bookId), "story");
  1697. await mkdir(join(storyDir, "state"), { recursive: true });
  1698. await Promise.all([
  1699. writeFile(join(storyDir, "current_state.md"), createStateCard({
  1700. chapter: 0,
  1701. location: "Ashen ferry crossing",
  1702. protagonistState: "Lin Yue still hides the oath token.",
  1703. goal: "Find the vanished mentor.",
  1704. conflict: "The mentor debt is still personal.",
  1705. }), "utf-8"),
  1706. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  1707. writeFile(join(storyDir, "chapter_summaries.md"), "# Chapter Summaries\n", "utf-8"),
  1708. writeFile(join(storyDir, "state", "manifest.json"), JSON.stringify({
  1709. schemaVersion: 2,
  1710. language: "en",
  1711. lastAppliedChapter: 0,
  1712. projectionVersion: 1,
  1713. migrationWarnings: [],
  1714. }, null, 2), "utf-8"),
  1715. writeFile(join(storyDir, "state", "current_state.json"), JSON.stringify({
  1716. chapter: 0,
  1717. facts: [],
  1718. }, null, 2), "utf-8"),
  1719. writeFile(join(storyDir, "state", "hooks.json"), JSON.stringify({
  1720. hooks: [],
  1721. }, null, 2), "utf-8"),
  1722. writeFile(join(storyDir, "state", "chapter_summaries.json"), JSON.stringify({
  1723. rows: [],
  1724. }, null, 2), "utf-8"),
  1725. ]);
  1726. const beforeState = await readFile(join(storyDir, "current_state.md"), "utf-8");
  1727. const beforeManifest = await readFile(join(storyDir, "state", "manifest.json"), "utf-8");
  1728. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1729. createWriterOutput({
  1730. content: "Broken chapter body.",
  1731. wordCount: countChapterLength("Broken chapter body.", "en_words"),
  1732. postWriteErrors: [],
  1733. postWriteWarnings: [],
  1734. runtimeStateDelta: {
  1735. chapter: 0,
  1736. hookOps: {
  1737. upsert: [],
  1738. resolve: [],
  1739. defer: [],
  1740. },
  1741. notes: [],
  1742. } as unknown as NonNullable<ReturnType<typeof createWriterOutput>["runtimeStateDelta"]>,
  1743. }),
  1744. );
  1745. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1746. createAuditResult({
  1747. passed: true,
  1748. issues: [],
  1749. summary: "clean",
  1750. }),
  1751. );
  1752. await expect(runner.writeNextChapter(bookId)).rejects.toThrow();
  1753. await expect(readFile(join(storyDir, "current_state.md"), "utf-8")).resolves.toBe(beforeState);
  1754. await expect(readFile(join(storyDir, "state", "manifest.json"), "utf-8")).resolves.toBe(beforeManifest);
  1755. await rm(root, { recursive: true, force: true });
  1756. });
  1757. it("rolls back persisted runtime state when writer delta contains natural-language numeric drift", async () => {
  1758. const { root, runner, state, bookId } = await createRunnerFixture({
  1759. inputGovernanceMode: "legacy",
  1760. });
  1761. const storyDir = join(state.bookDir(bookId), "story");
  1762. await mkdir(join(storyDir, "state"), { recursive: true });
  1763. await Promise.all([
  1764. writeFile(join(storyDir, "current_state.md"), createStateCard({
  1765. chapter: 0,
  1766. location: "Ashen ferry crossing",
  1767. protagonistState: "Lin Yue still hides the oath token.",
  1768. goal: "Find the vanished mentor.",
  1769. conflict: "The mentor debt is still personal.",
  1770. }), "utf-8"),
  1771. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  1772. writeFile(join(storyDir, "chapter_summaries.md"), "# Chapter Summaries\n", "utf-8"),
  1773. writeFile(join(storyDir, "state", "manifest.json"), JSON.stringify({
  1774. schemaVersion: 2,
  1775. language: "en",
  1776. lastAppliedChapter: 0,
  1777. projectionVersion: 1,
  1778. migrationWarnings: [],
  1779. }, null, 2), "utf-8"),
  1780. writeFile(join(storyDir, "state", "current_state.json"), JSON.stringify({
  1781. chapter: 0,
  1782. facts: [],
  1783. }, null, 2), "utf-8"),
  1784. writeFile(join(storyDir, "state", "hooks.json"), JSON.stringify({
  1785. hooks: [],
  1786. }, null, 2), "utf-8"),
  1787. writeFile(join(storyDir, "state", "chapter_summaries.json"), JSON.stringify({
  1788. rows: [],
  1789. }, null, 2), "utf-8"),
  1790. ]);
  1791. const beforeState = await readFile(join(storyDir, "current_state.md"), "utf-8");
  1792. const beforeManifest = await readFile(join(storyDir, "state", "manifest.json"), "utf-8");
  1793. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  1794. createWriterOutput({
  1795. content: "Broken chapter body.",
  1796. wordCount: countChapterLength("Broken chapter body.", "en_words"),
  1797. postWriteErrors: [],
  1798. postWriteWarnings: [],
  1799. runtimeStateDelta: {
  1800. chapter: 1,
  1801. hookOps: {
  1802. upsert: [
  1803. {
  1804. hookId: "mentor-debt",
  1805. startChapter: 1,
  1806. type: "relationship",
  1807. status: "open",
  1808. lastAdvancedChapter: "chapter one",
  1809. expectedPayoff: "Reveal the debt.",
  1810. notes: "Bad numeric drift.",
  1811. },
  1812. ],
  1813. resolve: [],
  1814. defer: [],
  1815. },
  1816. notes: [],
  1817. } as unknown as NonNullable<ReturnType<typeof createWriterOutput>["runtimeStateDelta"]>,
  1818. }),
  1819. );
  1820. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  1821. createAuditResult({
  1822. passed: true,
  1823. issues: [],
  1824. summary: "clean",
  1825. }),
  1826. );
  1827. await expect(runner.writeNextChapter(bookId)).rejects.toThrow();
  1828. await expect(readFile(join(storyDir, "current_state.md"), "utf-8")).resolves.toBe(beforeState);
  1829. await expect(readFile(join(storyDir, "state", "manifest.json"), "utf-8")).resolves.toBe(beforeManifest);
  1830. await rm(root, { recursive: true, force: true });
  1831. });
  1832. it("reports only resumed chapters in import results", async () => {
  1833. const { root, runner, state, bookId } = await createRunnerFixture();
  1834. const now = "2026-03-19T00:00:00.000Z";
  1835. const existingIndex: ChapterMeta[] = [
  1836. {
  1837. number: 1,
  1838. title: "One",
  1839. status: "imported",
  1840. wordCount: 10,
  1841. createdAt: now,
  1842. updatedAt: now,
  1843. auditIssues: [],
  1844. lengthWarnings: [],
  1845. },
  1846. {
  1847. number: 2,
  1848. title: "Two",
  1849. status: "imported",
  1850. wordCount: 20,
  1851. createdAt: now,
  1852. updatedAt: now,
  1853. auditIssues: [],
  1854. lengthWarnings: [],
  1855. },
  1856. ];
  1857. await state.saveChapterIndex(bookId, existingIndex);
  1858. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockImplementation(async (input) =>
  1859. createAnalyzedOutput({
  1860. chapterNumber: input.chapterNumber,
  1861. title: input.chapterTitle ?? `Chapter ${input.chapterNumber}`,
  1862. content: input.chapterContent,
  1863. wordCount: input.chapterContent.length,
  1864. }),
  1865. );
  1866. vi.spyOn(WriterAgent.prototype, "saveChapter").mockResolvedValue(undefined);
  1867. vi.spyOn(WriterAgent.prototype, "saveNewTruthFiles").mockResolvedValue(undefined);
  1868. const result = await runner.importChapters({
  1869. bookId,
  1870. resumeFrom: 3,
  1871. chapters: [
  1872. { title: "One", content: "1111111111" },
  1873. { title: "Two", content: "22222222222222222222" },
  1874. { title: "Three", content: "333333333333333" },
  1875. { title: "Four", content: "4444444444444444444444444" },
  1876. ],
  1877. });
  1878. expect(result.importedCount).toBe(2);
  1879. expect(result.totalWords).toBe("333333333333333".length + "4444444444444444444444444".length);
  1880. expect(result.nextChapter).toBe(5);
  1881. await rm(root, { recursive: true, force: true });
  1882. });
  1883. sqliteIt("rebuilds fact history from imported chapter snapshots", async () => {
  1884. const { root, runner, state, bookId } = await createRunnerFixture();
  1885. vi.spyOn(ArchitectAgent.prototype, "generateFoundationFromImport").mockResolvedValue({
  1886. storyBible: "# Story Bible\n",
  1887. volumeOutline: "# Volume Outline\n",
  1888. bookRules: "---\nversion: \"1.0\"\n---\n\n# Book Rules\n",
  1889. currentState: createStateCard({
  1890. chapter: 0,
  1891. location: "Shrine outskirts",
  1892. protagonistState: "Lin Yue begins with the oath token hidden.",
  1893. goal: "Reach the trial city.",
  1894. conflict: "The trial deadline is closing in.",
  1895. }),
  1896. pendingHooks: "# Pending Hooks\n",
  1897. });
  1898. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter")
  1899. .mockResolvedValueOnce(createAnalyzedOutput({
  1900. chapterNumber: 1,
  1901. title: "One",
  1902. content: "One body.",
  1903. wordCount: "One body.".length,
  1904. updatedState: createStateCard({
  1905. chapter: 1,
  1906. location: "Ashen ferry crossing",
  1907. protagonistState: "Lin Yue still hides the oath token.",
  1908. goal: "Find the vanished mentor.",
  1909. conflict: "The mentor debt is still personal.",
  1910. }),
  1911. updatedHooks: "# Pending Hooks\n",
  1912. }))
  1913. .mockResolvedValueOnce(createAnalyzedOutput({
  1914. chapterNumber: 2,
  1915. title: "Two",
  1916. content: "Two body.",
  1917. wordCount: "Two body.".length,
  1918. updatedState: createStateCard({
  1919. chapter: 2,
  1920. location: "North watchtower",
  1921. protagonistState: "Lin Yue finally shows the oath token.",
  1922. goal: "Reach the watchtower before the guild.",
  1923. conflict: "The merchant guild now contests the mentor trail.",
  1924. }),
  1925. updatedHooks: "# Pending Hooks\n",
  1926. }));
  1927. try {
  1928. await runner.importChapters({
  1929. bookId,
  1930. chapters: [
  1931. { title: "One", content: "One body." },
  1932. { title: "Two", content: "Two body." },
  1933. ],
  1934. });
  1935. const memoryDb = new MemoryDB(state.bookDir(bookId));
  1936. try {
  1937. const chapterOneFacts = memoryDb.getFactsAt("protagonist", 1);
  1938. const currentFacts = memoryDb.getCurrentFacts();
  1939. expect(chapterOneFacts).toEqual(
  1940. expect.arrayContaining([
  1941. expect.objectContaining({
  1942. predicate: "Current Conflict",
  1943. object: "The mentor debt is still personal.",
  1944. }),
  1945. ]),
  1946. );
  1947. expect(currentFacts).toEqual(
  1948. expect.arrayContaining([
  1949. expect.objectContaining({
  1950. predicate: "Current Conflict",
  1951. object: "The merchant guild now contests the mentor trail.",
  1952. validFromChapter: 2,
  1953. sourceChapter: 2,
  1954. }),
  1955. ]),
  1956. );
  1957. } finally {
  1958. memoryDb.close();
  1959. }
  1960. } finally {
  1961. await rm(root, { recursive: true, force: true });
  1962. }
  1963. });
  1964. sqliteIt("rebuilds fact history from structured snapshot state instead of stale markdown snapshots", async () => {
  1965. const { root, runner, state, bookId } = await createRunnerFixture();
  1966. const storyDir = join(state.bookDir(bookId), "story");
  1967. const snapshotOneDir = join(storyDir, "snapshots", "1");
  1968. const snapshotOneStateDir = join(snapshotOneDir, "state");
  1969. await mkdir(snapshotOneStateDir, { recursive: true });
  1970. await Promise.all([
  1971. writeFile(
  1972. join(snapshotOneDir, "current_state.md"),
  1973. createStateCard({
  1974. chapter: 1,
  1975. location: "Old markdown ferry crossing",
  1976. protagonistState: "Markdown state still hides the oath token.",
  1977. goal: "Follow the markdown trail.",
  1978. conflict: "Old markdown conflict.",
  1979. }),
  1980. "utf-8",
  1981. ),
  1982. writeFile(join(snapshotOneStateDir, "current_state.json"), JSON.stringify({
  1983. chapter: 1,
  1984. facts: [
  1985. {
  1986. subject: "current",
  1987. predicate: "Current Location",
  1988. object: "Structured watchtower",
  1989. validFromChapter: 1,
  1990. validUntilChapter: null,
  1991. sourceChapter: 1,
  1992. },
  1993. {
  1994. subject: "protagonist",
  1995. predicate: "Current Conflict",
  1996. object: "Structured conflict replaces markdown drift.",
  1997. validFromChapter: 1,
  1998. validUntilChapter: null,
  1999. sourceChapter: 1,
  2000. },
  2001. ],
  2002. }, null, 2), "utf-8"),
  2003. ]);
  2004. try {
  2005. await (runner as unknown as {
  2006. syncCurrentStateFactHistory: (targetBookId: string, uptoChapter: number) => Promise<void>;
  2007. }).syncCurrentStateFactHistory(bookId, 1);
  2008. const memoryDb = new MemoryDB(state.bookDir(bookId));
  2009. try {
  2010. expect(memoryDb.getCurrentFacts()).toEqual(
  2011. expect.arrayContaining([
  2012. expect.objectContaining({
  2013. predicate: "Current Location",
  2014. object: "Structured watchtower",
  2015. validFromChapter: 1,
  2016. }),
  2017. expect.objectContaining({
  2018. predicate: "Current Conflict",
  2019. object: "Structured conflict replaces markdown drift.",
  2020. validFromChapter: 1,
  2021. }),
  2022. ]),
  2023. );
  2024. expect(memoryDb.getCurrentFacts()).not.toEqual(
  2025. expect.arrayContaining([
  2026. expect.objectContaining({
  2027. object: "Old markdown ferry crossing",
  2028. }),
  2029. expect.objectContaining({
  2030. object: "Old markdown conflict.",
  2031. }),
  2032. ]),
  2033. );
  2034. } finally {
  2035. memoryDb.close();
  2036. }
  2037. } finally {
  2038. await rm(root, { recursive: true, force: true });
  2039. }
  2040. });
  2041. it("tracks imported English chapters using word counts instead of characters", async () => {
  2042. const { root, runner, state, bookId } = await createRunnerFixture();
  2043. const englishBook = {
  2044. ...(await state.loadBookConfig(bookId)),
  2045. genre: "other",
  2046. language: "en" as const,
  2047. };
  2048. const now = "2026-03-19T00:00:00.000Z";
  2049. await state.saveBookConfig(bookId, englishBook);
  2050. await state.saveChapterIndex(bookId, [
  2051. {
  2052. number: 1,
  2053. title: "Prelude",
  2054. status: "imported",
  2055. wordCount: 3,
  2056. createdAt: now,
  2057. updatedAt: now,
  2058. auditIssues: [],
  2059. lengthWarnings: [],
  2060. },
  2061. {
  2062. number: 2,
  2063. title: "Crossroads",
  2064. status: "imported",
  2065. wordCount: 2,
  2066. createdAt: now,
  2067. updatedAt: now,
  2068. auditIssues: [],
  2069. lengthWarnings: [],
  2070. },
  2071. ]);
  2072. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockImplementation(async (input) =>
  2073. createAnalyzedOutput({
  2074. chapterNumber: input.chapterNumber,
  2075. title: input.chapterTitle ?? `Chapter ${input.chapterNumber}`,
  2076. content: input.chapterContent,
  2077. wordCount: countChapterLength(input.chapterContent, "en_words"),
  2078. }),
  2079. );
  2080. vi.spyOn(WriterAgent.prototype, "saveChapter").mockResolvedValue(undefined);
  2081. vi.spyOn(WriterAgent.prototype, "saveNewTruthFiles").mockResolvedValue(undefined);
  2082. const result = await runner.importChapters({
  2083. bookId,
  2084. resumeFrom: 3,
  2085. chapters: [
  2086. { title: "Prelude", content: "One two three" },
  2087. { title: "Crossroads", content: "Four five" },
  2088. { title: "The Watchtower", content: "The storm kept rolling west" },
  2089. { title: "Aftermath", content: "Lanterns dimmed before dawn broke" },
  2090. ],
  2091. });
  2092. const chapterIndex = await state.loadChapterIndex(bookId);
  2093. const chapterThree = chapterIndex.find((entry) => entry.number === 3);
  2094. const chapterFour = chapterIndex.find((entry) => entry.number === 4);
  2095. expect(result.importedCount).toBe(2);
  2096. expect(result.totalWords).toBe(10);
  2097. expect(chapterThree?.wordCount).toBe(5);
  2098. expect(chapterFour?.wordCount).toBe(5);
  2099. await rm(root, { recursive: true, force: true });
  2100. });
  2101. it("imports English chapters with English foundation seeds and persistence files", async () => {
  2102. const { root, runner, state, bookId } = await createRunnerFixture();
  2103. const englishBook = {
  2104. ...(await state.loadBookConfig(bookId)),
  2105. genre: "other",
  2106. language: "en" as const,
  2107. chapterWordCount: 2200,
  2108. };
  2109. await state.saveBookConfig(bookId, englishBook);
  2110. const foundation = vi.spyOn(ArchitectAgent.prototype, "generateFoundationFromImport").mockResolvedValue({
  2111. storyBible: "# Story Bible\n",
  2112. volumeOutline: "# Volume Outline\n",
  2113. bookRules: "---\nversion: \"1.0\"\n---\n\n# Book Rules\n",
  2114. currentState: createStateCard({
  2115. chapter: 0,
  2116. location: "Harbor gate",
  2117. protagonistState: "Mara arrives with a sealed letter.",
  2118. goal: "Find the missing captain before sunrise.",
  2119. conflict: "The harbor watch is searching every ship.",
  2120. }),
  2121. pendingHooks: "# Pending Hooks\n\n| hook_id | start_chapter | type | status | last_advanced_chapter | expected_payoff | notes |\n| --- | --- | --- | --- | --- | --- | --- |\n",
  2122. });
  2123. const saveChapter = vi.spyOn(WriterAgent.prototype, "saveChapter");
  2124. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  2125. createAnalyzedOutput({
  2126. chapterNumber: 1,
  2127. title: "Prelude",
  2128. content: "A cold wind crossed the harbor.",
  2129. wordCount: countChapterLength("A cold wind crossed the harbor.", "en_words"),
  2130. updatedState: createStateCard({
  2131. chapter: 1,
  2132. location: "Harbor gate",
  2133. protagonistState: "Mara hides the sealed letter under her coat.",
  2134. goal: "Slip past the harbor watch.",
  2135. conflict: "The watch now searches for the missing captain's courier.",
  2136. }),
  2137. updatedHooks: "# Pending Hooks\n\n| hook_id | start_chapter | type | status | last_advanced_chapter | expected_payoff | notes |\n| --- | --- | --- | --- | --- | --- | --- |\n| captain-letter | 1 | mystery | open | 1 | The captain's disappearance is explained. | The sealed letter points to the vanished captain. |\n",
  2138. chapterSummary: "| 1 | Prelude | Mara | Mara reaches the harbor with a sealed letter. | Mara hides the letter and studies the watch patrol. | The captain-letter mystery opens. | tense | setup |",
  2139. updatedSubplots: [
  2140. "# Subplot Board",
  2141. "",
  2142. "| Subplot | Status | Note |",
  2143. "| --- | --- | --- |",
  2144. "| Harbor search | Active | Mara begins the search for the missing captain. |",
  2145. "",
  2146. ].join("\n"),
  2147. updatedEmotionalArcs: "",
  2148. updatedCharacterMatrix: "",
  2149. }),
  2150. );
  2151. try {
  2152. await runner.importChapters({
  2153. bookId,
  2154. chapters: [
  2155. { title: "Prelude", content: "A cold wind crossed the harbor." },
  2156. ],
  2157. });
  2158. const storyDir = join(state.bookDir(bookId), "story");
  2159. const chapterPath = join(state.bookDir(bookId), "chapters", "0001_Prelude.md");
  2160. const chapterFile = await readFile(chapterPath, "utf-8");
  2161. const chapterSummaries = await readFile(join(storyDir, "chapter_summaries.md"), "utf-8");
  2162. const subplotBoard = await readFile(join(storyDir, "subplot_board.md"), "utf-8");
  2163. expect(foundation.mock.calls[0]?.[1]).toContain("Chapter 1: Prelude");
  2164. expect(foundation.mock.calls[0]?.[1]).not.toContain("第1章");
  2165. expect(saveChapter.mock.calls[0]?.[3]).toBe("en");
  2166. expect(chapterFile).toContain("# Chapter 1: Prelude");
  2167. expect(chapterSummaries).toContain("# Chapter Summaries");
  2168. expect(chapterSummaries).not.toContain("# 章节摘要");
  2169. expect(subplotBoard).toContain("# Subplot Board");
  2170. expect(subplotBoard).not.toContain("# 支线进度板");
  2171. } finally {
  2172. await rm(root, { recursive: true, force: true });
  2173. }
  2174. });
  2175. it("logs localized replay progress during chapter import", async () => {
  2176. const { logger, infos } = createCaptureLogger();
  2177. const { root, runner, bookId } = await createRunnerFixture({ logger });
  2178. vi.spyOn(ArchitectAgent.prototype, "generateFoundationFromImport").mockResolvedValue({
  2179. storyBible: "# Story Bible\n",
  2180. volumeOutline: "# Volume Outline\n",
  2181. bookRules: "---\nversion: \"1.0\"\n---\n\n# Book Rules\n",
  2182. currentState: createStateCard({
  2183. chapter: 0,
  2184. location: "Ashen ferry crossing",
  2185. protagonistState: "Lin Yue still hides the oath token.",
  2186. goal: "Find the vanished mentor.",
  2187. conflict: "The mentor debt is still personal.",
  2188. }),
  2189. pendingHooks: "# Pending Hooks\n",
  2190. });
  2191. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockResolvedValue(
  2192. createAnalyzedOutput({
  2193. chapterNumber: 1,
  2194. title: "Prelude",
  2195. content: "章节正文。",
  2196. wordCount: "章节正文。".length,
  2197. }),
  2198. );
  2199. vi.spyOn(WriterAgent.prototype, "saveChapter").mockResolvedValue(undefined);
  2200. vi.spyOn(WriterAgent.prototype, "saveNewTruthFiles").mockResolvedValue(undefined);
  2201. try {
  2202. await runner.importChapters({
  2203. bookId,
  2204. chapters: [
  2205. { title: "第一章", content: "章节正文。" },
  2206. ],
  2207. });
  2208. expect(infos).toEqual(expect.arrayContaining([
  2209. "步骤 1:从 1 章生成基础设定...",
  2210. "基础设定已生成。",
  2211. "步骤 2:从第 1 章开始顺序回放...",
  2212. "分析章节 1/1:第一章...",
  2213. "完成。已导入 1 章,共 5字。下一章:2",
  2214. ]));
  2215. } finally {
  2216. await rm(root, { recursive: true, force: true });
  2217. }
  2218. });
  2219. it("does not leak imported future state into early replay chapters", async () => {
  2220. const { root, runner, state, bookId } = await createRunnerFixture();
  2221. const storyDir = join(state.bookDir(bookId), "story");
  2222. const englishBook = {
  2223. ...(await state.loadBookConfig(bookId)),
  2224. genre: "other",
  2225. language: "en" as const,
  2226. chapterWordCount: 2200,
  2227. };
  2228. await state.saveBookConfig(bookId, englishBook);
  2229. await mkdir(join(storyDir, "snapshots", "0"), { recursive: true });
  2230. await Promise.all([
  2231. writeFile(join(storyDir, "subplot_board.md"), "# Subplot Board\n\nFUTURE LEAK subplot\n", "utf-8"),
  2232. writeFile(join(storyDir, "emotional_arcs.md"), "# Emotional Arcs\n\nFUTURE LEAK emotion\n", "utf-8"),
  2233. writeFile(join(storyDir, "character_matrix.md"), "# Character Matrix\n\nFUTURE LEAK matrix\n", "utf-8"),
  2234. writeFile(
  2235. join(storyDir, "chapter_summaries.md"),
  2236. [
  2237. "# Chapter Summaries",
  2238. "",
  2239. "| Chapter | Title | Characters | Key Events | State Changes | Hook Activity | Mood | Chapter Type |",
  2240. "| --- | --- | --- | --- | --- | --- | --- | --- |",
  2241. "| 99 | Future | Future Cast | FUTURE LEAK event | FUTURE LEAK state | FUTURE LEAK hook | grim | finale |",
  2242. "",
  2243. ].join("\n"),
  2244. "utf-8",
  2245. ),
  2246. writeFile(
  2247. join(storyDir, "snapshots", "0", "current_state.md"),
  2248. createStateCard({
  2249. chapter: 60,
  2250. location: "Chengdu court",
  2251. protagonistState: "FUTURE LEAK snapshot",
  2252. goal: "Secure the western kingdom.",
  2253. conflict: "Late-book imperial rivalry is now fully active.",
  2254. }),
  2255. "utf-8",
  2256. ),
  2257. writeFile(
  2258. join(storyDir, "snapshots", "0", "pending_hooks.md"),
  2259. [
  2260. "# Pending Hooks",
  2261. "",
  2262. "| hook_id | start_chapter | type | status | last_advanced_chapter | expected_payoff | notes |",
  2263. "| --- | --- | --- | --- | --- | --- | --- |",
  2264. "| future-hook | 60 | mystery | open | 60 | Future payoff | FUTURE LEAK |",
  2265. "",
  2266. ].join("\n"),
  2267. "utf-8",
  2268. ),
  2269. ]);
  2270. vi.spyOn(ArchitectAgent.prototype, "generateFoundationFromImport").mockResolvedValue({
  2271. storyBible: "# Story Bible\n",
  2272. volumeOutline: "# Volume Outline\n",
  2273. bookRules: "---\nversion: \"1.0\"\n---\n\n# Book Rules\n",
  2274. currentState: createStateCard({
  2275. chapter: 60,
  2276. location: "Chengdu court",
  2277. protagonistState: "FUTURE LEAK: Liu Bei already holds Yizhou.",
  2278. goal: "Secure the western kingdom.",
  2279. conflict: "Late-book imperial rivalry is now fully active.",
  2280. }),
  2281. pendingHooks: [
  2282. "# Pending Hooks",
  2283. "",
  2284. "| hook_id | start_chapter | type | status | last_advanced_chapter | expected_payoff | notes |",
  2285. "| --- | --- | --- | --- | --- | --- | --- |",
  2286. "| future-hook | 60 | mystery | open | 60 | Future payoff | FUTURE LEAK |",
  2287. "",
  2288. ].join("\n"),
  2289. });
  2290. let stateSeenByFirstReplay = "";
  2291. let hooksSeenByFirstReplay = "";
  2292. let subplotSeenByFirstReplay = "";
  2293. let emotionalSeenByFirstReplay = "";
  2294. let matrixSeenByFirstReplay = "";
  2295. let summariesSeenByFirstReplay = "";
  2296. vi.spyOn(ChapterAnalyzerAgent.prototype, "analyzeChapter").mockImplementationOnce(async (input) => {
  2297. stateSeenByFirstReplay = await readFile(join(input.bookDir, "story", "current_state.md"), "utf-8");
  2298. hooksSeenByFirstReplay = await readFile(join(input.bookDir, "story", "pending_hooks.md"), "utf-8");
  2299. subplotSeenByFirstReplay = await readFile(join(input.bookDir, "story", "subplot_board.md"), "utf-8").catch(() => "");
  2300. emotionalSeenByFirstReplay = await readFile(join(input.bookDir, "story", "emotional_arcs.md"), "utf-8").catch(() => "");
  2301. matrixSeenByFirstReplay = await readFile(join(input.bookDir, "story", "character_matrix.md"), "utf-8").catch(() => "");
  2302. summariesSeenByFirstReplay = await readFile(join(input.bookDir, "story", "chapter_summaries.md"), "utf-8").catch(() => "");
  2303. return createAnalyzedOutput({
  2304. chapterNumber: 1,
  2305. title: "Prelude",
  2306. content: "A cold wind crossed the harbor.",
  2307. wordCount: countChapterLength("A cold wind crossed the harbor.", "en_words"),
  2308. updatedState: createStateCard({
  2309. chapter: 1,
  2310. location: "Harbor gate",
  2311. protagonistState: "Mara hides the sealed letter under her coat.",
  2312. goal: "Slip past the harbor watch.",
  2313. conflict: "The watch now searches for the missing captain's courier.",
  2314. }),
  2315. updatedHooks: [
  2316. "# Pending Hooks",
  2317. "",
  2318. "| hook_id | start_chapter | type | status | last_advanced_chapter | expected_payoff | notes |",
  2319. "| --- | --- | --- | --- | --- | --- | --- |",
  2320. "| captain-letter | 1 | mystery | open | 1 | The captain's disappearance is explained. | The sealed letter points to the vanished captain. |",
  2321. "",
  2322. ].join("\n"),
  2323. });
  2324. });
  2325. try {
  2326. await runner.importChapters({
  2327. bookId,
  2328. chapters: [
  2329. { title: "Prelude", content: "A cold wind crossed the harbor." },
  2330. ],
  2331. });
  2332. expect(stateSeenByFirstReplay).toContain("| Current Chapter | 0 |");
  2333. expect(stateSeenByFirstReplay).not.toContain("FUTURE LEAK");
  2334. expect(hooksSeenByFirstReplay).toContain("# Pending Hooks");
  2335. expect(hooksSeenByFirstReplay).not.toContain("future-hook");
  2336. expect(hooksSeenByFirstReplay).not.toContain("FUTURE LEAK");
  2337. expect(subplotSeenByFirstReplay).not.toContain("FUTURE LEAK");
  2338. expect(emotionalSeenByFirstReplay).not.toContain("FUTURE LEAK");
  2339. expect(matrixSeenByFirstReplay).not.toContain("FUTURE LEAK");
  2340. expect(summariesSeenByFirstReplay).not.toContain("FUTURE LEAK");
  2341. const snapshotZeroState = await readFile(join(storyDir, "snapshots", "0", "current_state.md"), "utf-8");
  2342. const snapshotZeroHooks = await readFile(join(storyDir, "snapshots", "0", "pending_hooks.md"), "utf-8");
  2343. expect(snapshotZeroState).toContain("| Current Chapter | 0 |");
  2344. expect(snapshotZeroState).not.toContain("FUTURE LEAK");
  2345. expect(snapshotZeroHooks).toContain("# Pending Hooks");
  2346. expect(snapshotZeroHooks).not.toContain("future-hook");
  2347. expect(snapshotZeroHooks).not.toContain("FUTURE LEAK");
  2348. } finally {
  2349. await rm(root, { recursive: true, force: true });
  2350. }
  2351. });
  2352. sqliteIt("rebuilds current facts from the revised chapter snapshot", async () => {
  2353. const { root, runner, state, bookId } = await createRunnerFixture();
  2354. const storyDir = join(state.bookDir(bookId), "story");
  2355. const chaptersDir = join(state.bookDir(bookId), "chapters");
  2356. const oldState = createStateCard({
  2357. chapter: 1,
  2358. location: "Ashen ferry crossing",
  2359. protagonistState: "Lin Yue still hides the oath token.",
  2360. goal: "Find the vanished mentor.",
  2361. conflict: "The mentor debt is still personal.",
  2362. });
  2363. const revisedState = createStateCard({
  2364. chapter: 1,
  2365. location: "Ashen ferry crossing",
  2366. protagonistState: "Lin Yue no longer hides the oath token.",
  2367. goal: "Confront the vanished mentor.",
  2368. conflict: "The oath token is public now, forcing the confrontation.",
  2369. });
  2370. await Promise.all([
  2371. writeFile(join(chaptersDir, "0001_Test_Chapter.md"), "# 第1章 Test Chapter\n\nOriginal body.", "utf-8"),
  2372. writeFile(join(storyDir, "current_state.md"), oldState, "utf-8"),
  2373. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  2374. ]);
  2375. await state.saveChapterIndex(bookId, [{
  2376. number: 1,
  2377. title: "Test Chapter",
  2378. status: "audit-failed",
  2379. wordCount: "Original body.".length,
  2380. createdAt: "2026-03-19T00:00:00.000Z",
  2381. updatedAt: "2026-03-19T00:00:00.000Z",
  2382. auditIssues: [],
  2383. lengthWarnings: [],
  2384. }]);
  2385. await state.snapshotState(bookId, 1);
  2386. vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  2387. .mockResolvedValueOnce(
  2388. createAuditResult({
  2389. passed: false,
  2390. issues: [CRITICAL_ISSUE],
  2391. summary: "needs revision",
  2392. }),
  2393. )
  2394. .mockResolvedValueOnce(
  2395. createAuditResult({
  2396. passed: true,
  2397. issues: [],
  2398. summary: "clean",
  2399. }),
  2400. );
  2401. vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  2402. createReviseOutput({
  2403. revisedContent: "Revised body.",
  2404. wordCount: "Revised body.".length,
  2405. updatedState: revisedState,
  2406. updatedHooks: "# Pending Hooks\n",
  2407. }),
  2408. );
  2409. try {
  2410. await runner.reviseDraft(bookId, 1);
  2411. const memoryDb = new MemoryDB(state.bookDir(bookId));
  2412. try {
  2413. expect(memoryDb.getCurrentFacts()).toEqual(
  2414. expect.arrayContaining([
  2415. expect.objectContaining({
  2416. predicate: "Current Conflict",
  2417. object: "The oath token is public now, forcing the confrontation.",
  2418. validFromChapter: 1,
  2419. sourceChapter: 1,
  2420. }),
  2421. ]),
  2422. );
  2423. } finally {
  2424. memoryDb.close();
  2425. }
  2426. } finally {
  2427. await rm(root, { recursive: true, force: true });
  2428. }
  2429. });
  2430. it("feeds long-span fatigue warnings back into pipeline audit and drift correction", async () => {
  2431. const { root, runner, state, bookId } = await createRunnerFixture();
  2432. const storyDir = join(state.bookDir(bookId), "story");
  2433. const now = "2026-03-19T00:00:00.000Z";
  2434. await Promise.all([
  2435. writeFile(join(storyDir, "current_state.md"), createStateCard({
  2436. chapter: 2,
  2437. location: "Ashen ferry crossing",
  2438. protagonistState: "Lin Yue still hides the oath token.",
  2439. goal: "Find the vanished mentor.",
  2440. conflict: "The debt trail keeps narrowing.",
  2441. }), "utf-8"),
  2442. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  2443. writeFile(
  2444. join(storyDir, "chapter_summaries.md"),
  2445. [
  2446. "# 章节摘要",
  2447. "",
  2448. "| 章节 | 标题 | 出场人物 | 关键事件 | 状态变化 | 伏笔动态 | 情绪基调 | 章节类型 |",
  2449. "|------|------|----------|----------|----------|----------|----------|----------|",
  2450. "| 1 | 旧路 | 林越 | 进城 | 潜伏开始 | 债印未解 | 克制 | 布局 |",
  2451. "| 2 | 暗巷 | 林越 | 试探 | 目标未变 | 债印未解 | 克制 | 布局 |",
  2452. ].join("\n"),
  2453. "utf-8",
  2454. ),
  2455. writeFile(join(state.bookDir(bookId), "chapters", "0001_旧路.md"), "# 第1章 旧路\n\n城门在晨雾里半开。林越顺着石阶慢慢往里走。巷口那盏灯一直没有灭。", "utf-8"),
  2456. writeFile(join(state.bookDir(bookId), "chapters", "0002_暗巷.md"), "# 第2章 暗巷\n\n午后的风掠过墙头。林越没有回头,只是沿着阴影继续向前。墙后的铃声很轻。", "utf-8"),
  2457. ]);
  2458. await state.saveChapterIndex(bookId, [
  2459. {
  2460. number: 1,
  2461. title: "旧路",
  2462. status: "ready-for-review",
  2463. wordCount: 36,
  2464. createdAt: now,
  2465. updatedAt: now,
  2466. auditIssues: [],
  2467. lengthWarnings: [],
  2468. },
  2469. {
  2470. number: 2,
  2471. title: "暗巷",
  2472. status: "ready-for-review",
  2473. wordCount: 36,
  2474. createdAt: now,
  2475. updatedAt: now,
  2476. auditIssues: [],
  2477. lengthWarnings: [],
  2478. },
  2479. ]);
  2480. vi.spyOn(WriterAgent.prototype, "writeChapter").mockResolvedValue(
  2481. createWriterOutput({
  2482. chapterNumber: 3,
  2483. title: "回声",
  2484. content: "夜色慢慢压低了屋檐。林越先停在门外,随后才抬手去碰那道旧债印。风从更深的巷子里吹了出来。",
  2485. wordCount: "夜色慢慢压低了屋檐。林越先停在门外,随后才抬手去碰那道旧债印。风从更深的巷子里吹了出来。".length,
  2486. updatedState: createStateCard({
  2487. chapter: 3,
  2488. location: "Ashen ferry crossing",
  2489. protagonistState: "Lin Yue still hides the oath token.",
  2490. goal: "Find the vanished mentor.",
  2491. conflict: "The debt trail keeps narrowing.",
  2492. }),
  2493. updatedLedger: "",
  2494. updatedHooks: "# Pending Hooks\n",
  2495. chapterSummary: "| 3 | 回声 | 林越 | 继续潜伏 | 目标未变 | 债印未解 | 克制 | 布局 |",
  2496. }),
  2497. );
  2498. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  2499. createAuditResult({
  2500. passed: true,
  2501. issues: [],
  2502. summary: "ok",
  2503. }),
  2504. );
  2505. try {
  2506. const result = await runner.writeNextChapter(bookId);
  2507. const currentState = await readFile(join(storyDir, "current_state.md"), "utf-8");
  2508. expect(result.auditResult.issues.some((issue) => issue.category === "节奏单调")).toBe(true);
  2509. expect(currentState).toContain("节奏单调");
  2510. } finally {
  2511. await rm(root, { recursive: true, force: true });
  2512. }
  2513. });
  2514. it("defaults manual reviseDraft to spot-fix when mode is omitted", async () => {
  2515. const { root, runner, state, bookId } = await createRunnerFixture();
  2516. const storyDir = join(state.bookDir(bookId), "story");
  2517. const chaptersDir = join(state.bookDir(bookId), "chapters");
  2518. await Promise.all([
  2519. writeFile(join(chaptersDir, "0001_Test_Chapter.md"), "# 第1章 Test Chapter\n\nOriginal body.", "utf-8"),
  2520. writeFile(join(storyDir, "current_state.md"), createStateCard({
  2521. chapter: 1,
  2522. location: "Ashen ferry crossing",
  2523. protagonistState: "Lin Yue still hides the oath token.",
  2524. goal: "Find the vanished mentor.",
  2525. conflict: "The mentor debt is still personal.",
  2526. }), "utf-8"),
  2527. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  2528. ]);
  2529. await state.saveChapterIndex(bookId, [{
  2530. number: 1,
  2531. title: "Test Chapter",
  2532. status: "audit-failed",
  2533. wordCount: "Original body.".length,
  2534. createdAt: "2026-03-19T00:00:00.000Z",
  2535. updatedAt: "2026-03-19T00:00:00.000Z",
  2536. auditIssues: [],
  2537. lengthWarnings: [],
  2538. }]);
  2539. vi.spyOn(ContinuityAuditor.prototype, "auditChapter").mockResolvedValue(
  2540. createAuditResult({
  2541. passed: false,
  2542. issues: [CRITICAL_ISSUE],
  2543. summary: "needs revision",
  2544. }),
  2545. );
  2546. const reviseChapter = vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  2547. createReviseOutput({
  2548. revisedContent: "Spot-fixed body.",
  2549. wordCount: "Spot-fixed body.".length,
  2550. updatedState: createStateCard({
  2551. chapter: 1,
  2552. location: "Ashen ferry crossing",
  2553. protagonistState: "Lin Yue still hides the oath token.",
  2554. goal: "Find the vanished mentor.",
  2555. conflict: "The mentor debt is repaired.",
  2556. }),
  2557. updatedHooks: "# Pending Hooks\n",
  2558. }),
  2559. );
  2560. try {
  2561. await runner.reviseDraft(bookId, 1);
  2562. expect(reviseChapter).toHaveBeenCalledTimes(1);
  2563. expect(reviseChapter.mock.calls[0]?.[4]).toBe("spot-fix");
  2564. } finally {
  2565. await rm(root, { recursive: true, force: true });
  2566. }
  2567. });
  2568. it("passes governed control inputs into manual revise in v2 mode", async () => {
  2569. const { root, runner, state, bookId } = await createRunnerFixture({
  2570. inputGovernanceMode: "v2",
  2571. });
  2572. const storyDir = join(state.bookDir(bookId), "story");
  2573. const chaptersDir = join(state.bookDir(bookId), "chapters");
  2574. const originalBody = "林越推门进去,先看见柜台后那盏没关的灯。";
  2575. await Promise.all([
  2576. writeFile(join(storyDir, "current_focus.md"), "# 当前聚焦\n\n## 当前重点\n\n把注意力收回师债主线。\n", "utf-8"),
  2577. writeFile(join(storyDir, "volume_outline.md"), "# 卷纲\n\n## 第1章\n先处理商会路线噪音。\n", "utf-8"),
  2578. writeFile(join(storyDir, "current_state.md"), createStateCard({
  2579. chapter: 1,
  2580. location: "旧港便利店",
  2581. protagonistState: "林越仍在追查师债。",
  2582. goal: "把注意力拉回师债线索。",
  2583. conflict: "商会路线仍在分散注意力。",
  2584. }), "utf-8"),
  2585. writeFile(join(storyDir, "story_bible.md"), "# 世界观设定\n\n- 誓令碎片不可伪造。\n", "utf-8"),
  2586. writeFile(join(storyDir, "pending_hooks.md"), "# 伏笔池\n\n- 师债线索仍未回收。\n", "utf-8"),
  2587. writeFile(join(storyDir, "chapter_summaries.md"), [
  2588. "# 章节摘要",
  2589. "",
  2590. "| 章节 | 标题 | 出场人物 | 关键事件 | 状态变化 | 伏笔动态 | 情绪基调 | 章节类型 |",
  2591. "| --- | --- | --- | --- | --- | --- | --- | --- |",
  2592. "| 1 | 夜灯 | 林越 | 林越继续追查师债 | 追查意图更强 | 师债推进 | 压抑 | 主线推进 |",
  2593. "",
  2594. ].join("\n"), "utf-8"),
  2595. writeFile(join(chaptersDir, "0001_夜灯.md"), `# 第1章 夜灯\n\n${originalBody}`, "utf-8"),
  2596. ]);
  2597. await state.saveChapterIndex(bookId, [{
  2598. number: 1,
  2599. title: "夜灯",
  2600. status: "audit-failed",
  2601. wordCount: originalBody.length,
  2602. createdAt: "2026-03-19T00:00:00.000Z",
  2603. updatedAt: "2026-03-19T00:00:00.000Z",
  2604. auditIssues: [],
  2605. lengthWarnings: [],
  2606. }]);
  2607. const auditChapter = vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  2608. .mockResolvedValueOnce(
  2609. createAuditResult({
  2610. passed: false,
  2611. issues: [CRITICAL_ISSUE],
  2612. summary: "needs revision",
  2613. }),
  2614. )
  2615. .mockResolvedValueOnce(
  2616. createAuditResult({
  2617. passed: true,
  2618. issues: [],
  2619. summary: "clean",
  2620. }),
  2621. );
  2622. const reviseChapter = vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  2623. createReviseOutput({
  2624. revisedContent: "林越推门进去,先停在门槛外听了一息,再去看柜台后那盏没关的灯。",
  2625. wordCount: "林越推门进去,先停在门槛外听了一息,再去看柜台后那盏没关的灯。".length,
  2626. fixedIssues: ["- 收紧了主线焦点。"],
  2627. updatedState: createStateCard({
  2628. chapter: 1,
  2629. location: "旧港便利店",
  2630. protagonistState: "林越把注意力重新拉回师债。",
  2631. goal: "继续追查师债。",
  2632. conflict: "商会路线暂时退居背景。",
  2633. }),
  2634. updatedHooks: "# 伏笔池\n\n- 师债线索仍未回收。\n",
  2635. }),
  2636. );
  2637. try {
  2638. await runner.reviseDraft(bookId, 1);
  2639. expect(auditChapter.mock.calls[0]?.[4]).toMatchObject({
  2640. chapterIntent: expect.stringContaining("# Chapter Intent"),
  2641. contextPackage: expect.objectContaining({
  2642. selectedContext: expect.any(Array),
  2643. }),
  2644. ruleStack: expect.objectContaining({
  2645. activeOverrides: expect.any(Array),
  2646. }),
  2647. });
  2648. expect(reviseChapter.mock.calls[0]?.[6]).toMatchObject({
  2649. chapterIntent: expect.stringContaining("# Chapter Intent"),
  2650. contextPackage: expect.objectContaining({
  2651. selectedContext: expect.any(Array),
  2652. }),
  2653. ruleStack: expect.objectContaining({
  2654. activeOverrides: expect.any(Array),
  2655. }),
  2656. lengthSpec: expect.objectContaining({
  2657. target: 3000,
  2658. }),
  2659. });
  2660. } finally {
  2661. await rm(root, { recursive: true, force: true });
  2662. }
  2663. });
  2664. it("passes merged AI-tell issues into manual revise and rejects no-improvement revisions", async () => {
  2665. const { root, runner, state, bookId } = await createRunnerFixture();
  2666. const storyDir = join(state.bookDir(bookId), "story");
  2667. const chaptersDir = join(state.bookDir(bookId), "chapters");
  2668. const originalBody = "林越抬手。林越停步。林越转身。林越侧耳。";
  2669. await Promise.all([
  2670. writeFile(join(chaptersDir, "0001_Test_Chapter.md"), `# 第1章 Test Chapter\n\n${originalBody}`, "utf-8"),
  2671. writeFile(join(storyDir, "current_state.md"), createStateCard({
  2672. chapter: 1,
  2673. location: "Ashen ferry crossing",
  2674. protagonistState: "Lin Yue still hides the oath token.",
  2675. goal: "Find the vanished mentor.",
  2676. conflict: "The mentor debt is still personal.",
  2677. }), "utf-8"),
  2678. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  2679. ]);
  2680. await state.saveChapterIndex(bookId, [{
  2681. number: 1,
  2682. title: "Test Chapter",
  2683. status: "audit-failed",
  2684. wordCount: originalBody.length,
  2685. createdAt: "2026-03-19T00:00:00.000Z",
  2686. updatedAt: "2026-03-19T00:00:00.000Z",
  2687. auditIssues: [],
  2688. lengthWarnings: [],
  2689. }]);
  2690. vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  2691. .mockResolvedValueOnce(
  2692. createAuditResult({
  2693. passed: false,
  2694. issues: [{
  2695. severity: "warning",
  2696. category: "节奏",
  2697. description: "结尾解释略多。",
  2698. suggestion: "压缩一行解释。",
  2699. }],
  2700. summary: "needs revision",
  2701. }),
  2702. )
  2703. .mockResolvedValueOnce(
  2704. createAuditResult({
  2705. passed: false,
  2706. issues: [{
  2707. severity: "warning",
  2708. category: "节奏",
  2709. description: "结尾解释略多。",
  2710. suggestion: "压缩一行解释。",
  2711. }],
  2712. summary: "still weak",
  2713. }),
  2714. );
  2715. const reviseChapter = vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  2716. createReviseOutput({
  2717. revisedContent: `${originalBody}\n\n修订后收束更利落。`,
  2718. wordCount: `${originalBody}\n\n修订后收束更利落。`.length,
  2719. fixedIssues: ["- 压缩了结尾解释。"],
  2720. }),
  2721. );
  2722. try {
  2723. const result = await runner.reviseDraft(bookId, 1);
  2724. const savedChapter = await readFile(join(chaptersDir, "0001_Test_Chapter.md"), "utf-8");
  2725. const savedIndex = await state.loadChapterIndex(bookId);
  2726. expect(reviseChapter).toHaveBeenCalledTimes(1);
  2727. expect(reviseChapter.mock.calls[0]?.[3]).toEqual(
  2728. expect.arrayContaining([
  2729. expect.objectContaining({ category: "节奏" }),
  2730. expect.objectContaining({ category: "列表式结构" }),
  2731. ]),
  2732. );
  2733. expect(result.applied).toBe(false);
  2734. expect(result.status).toBe("unchanged");
  2735. expect(result.skippedReason).toContain("did not improve");
  2736. expect(savedChapter).toContain(originalBody);
  2737. expect(savedChapter).not.toContain("修订后收束更利落");
  2738. expect(savedIndex[0]?.status).toBe("audit-failed");
  2739. } finally {
  2740. await rm(root, { recursive: true, force: true });
  2741. }
  2742. });
  2743. it("persists manual revisions only when merged audit improves", async () => {
  2744. const { root, runner, state, bookId } = await createRunnerFixture();
  2745. const storyDir = join(state.bookDir(bookId), "story");
  2746. const chaptersDir = join(state.bookDir(bookId), "chapters");
  2747. const originalBody = "林越抬手。林越停步。林越转身。林越侧耳。";
  2748. const revisedBody = "门被风顶开,林越先停在门槛前。\n\n他侧过身,听见墙后那道更轻的呼吸。";
  2749. await Promise.all([
  2750. writeFile(join(chaptersDir, "0001_Test_Chapter.md"), `# 第1章 Test Chapter\n\n${originalBody}`, "utf-8"),
  2751. writeFile(join(storyDir, "current_state.md"), createStateCard({
  2752. chapter: 1,
  2753. location: "Ashen ferry crossing",
  2754. protagonistState: "Lin Yue still hides the oath token.",
  2755. goal: "Find the vanished mentor.",
  2756. conflict: "The mentor debt is still personal.",
  2757. }), "utf-8"),
  2758. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  2759. ]);
  2760. await state.saveChapterIndex(bookId, [{
  2761. number: 1,
  2762. title: "Test Chapter",
  2763. status: "audit-failed",
  2764. wordCount: originalBody.length,
  2765. createdAt: "2026-03-19T00:00:00.000Z",
  2766. updatedAt: "2026-03-19T00:00:00.000Z",
  2767. auditIssues: [],
  2768. lengthWarnings: [],
  2769. }]);
  2770. vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  2771. .mockResolvedValueOnce(
  2772. createAuditResult({
  2773. passed: false,
  2774. issues: [{
  2775. severity: "warning",
  2776. category: "节奏",
  2777. description: "结尾解释略多。",
  2778. suggestion: "压缩一行解释。",
  2779. }],
  2780. summary: "needs revision",
  2781. }),
  2782. )
  2783. .mockResolvedValueOnce(
  2784. createAuditResult({
  2785. passed: true,
  2786. issues: [],
  2787. summary: "clean",
  2788. }),
  2789. );
  2790. vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  2791. createReviseOutput({
  2792. revisedContent: revisedBody,
  2793. wordCount: revisedBody.length,
  2794. fixedIssues: ["- 收紧了结尾节奏。"],
  2795. updatedState: createStateCard({
  2796. chapter: 1,
  2797. location: "Ashen ferry crossing",
  2798. protagonistState: "Lin Yue still hides the oath token.",
  2799. goal: "Find the vanished mentor.",
  2800. conflict: "The mentor debt sharpens into a direct threat.",
  2801. }),
  2802. updatedHooks: "# Pending Hooks\n",
  2803. }),
  2804. );
  2805. try {
  2806. const result = await runner.reviseDraft(bookId, 1);
  2807. const savedChapter = await readFile(join(chaptersDir, "0001_Test_Chapter.md"), "utf-8");
  2808. const savedIndex = await state.loadChapterIndex(bookId);
  2809. expect(result.applied).toBe(true);
  2810. expect(result.status).toBe("ready-for-review");
  2811. expect(result.fixedIssues).toEqual(["- 收紧了结尾节奏。"]);
  2812. expect(savedChapter).toContain(revisedBody);
  2813. expect(savedIndex[0]?.status).toBe("ready-for-review");
  2814. expect(savedIndex[0]?.auditIssues).toEqual([]);
  2815. } finally {
  2816. await rm(root, { recursive: true, force: true });
  2817. }
  2818. });
  2819. it("re-audits revisions against updated state overrides instead of stale on-disk truth files", async () => {
  2820. const { root, runner, state, bookId } = await createRunnerFixture();
  2821. const storyDir = join(state.bookDir(bookId), "story");
  2822. const chaptersDir = join(state.bookDir(bookId), "chapters");
  2823. const originalBody = "Taryn kept one hand on the annexe key and listened at the door.";
  2824. const revisedBody = `${originalBody}\n\nHe checked the seal again before he moved.`;
  2825. await state.saveBookConfig(bookId, {
  2826. ...(await state.loadBookConfig(bookId)),
  2827. platform: "other",
  2828. genre: "progression",
  2829. language: "en",
  2830. chapterWordCount: 1800,
  2831. });
  2832. await Promise.all([
  2833. writeFile(join(chaptersDir, "0001_First.md"), `# Chapter 1: First\n\nOpening chapter.`, "utf-8"),
  2834. writeFile(join(chaptersDir, "0002_Test_Chapter.md"), `# Chapter 2: Test Chapter\n\n${originalBody}`, "utf-8"),
  2835. writeFile(join(storyDir, "current_state.md"), createStateCard({
  2836. chapter: 1,
  2837. location: "Orsden archive lower hall",
  2838. protagonistState: "Taryn is still moving under Renn's first warning.",
  2839. goal: "Reach the annexe.",
  2840. conflict: "The archive is already compromised.",
  2841. }), "utf-8"),
  2842. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  2843. ]);
  2844. await state.saveChapterIndex(bookId, [
  2845. {
  2846. number: 1,
  2847. title: "First",
  2848. status: "ready-for-review",
  2849. wordCount: countChapterLength("Opening chapter.", "en_words"),
  2850. createdAt: "2026-03-19T00:00:00.000Z",
  2851. updatedAt: "2026-03-19T00:00:00.000Z",
  2852. auditIssues: [],
  2853. lengthWarnings: [],
  2854. },
  2855. {
  2856. number: 2,
  2857. title: "Test Chapter",
  2858. status: "audit-failed",
  2859. wordCount: countChapterLength(originalBody, "en_words"),
  2860. createdAt: "2026-03-19T00:00:00.000Z",
  2861. updatedAt: "2026-03-19T00:00:00.000Z",
  2862. auditIssues: [],
  2863. lengthWarnings: [],
  2864. },
  2865. ]);
  2866. const auditChapter = vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  2867. .mockResolvedValueOnce(
  2868. createAuditResult({
  2869. passed: false,
  2870. issues: [{
  2871. severity: "warning",
  2872. category: "Pacing Check",
  2873. description: "The beat needs a firmer end stop.",
  2874. suggestion: "Tighten the closing move.",
  2875. }],
  2876. summary: "needs revision",
  2877. }),
  2878. )
  2879. .mockImplementationOnce(async (_bookDir, _chapterContent, chapterNumber, _genre, options) => {
  2880. const overrideState = (options as { truthFileOverrides?: { currentState?: string } } | undefined)
  2881. ?.truthFileOverrides?.currentState;
  2882. if (chapterNumber === 2 && overrideState?.includes("| Current Chapter | 2 |")) {
  2883. return createAuditResult({
  2884. passed: true,
  2885. issues: [],
  2886. summary: "clean",
  2887. });
  2888. }
  2889. return createAuditResult({
  2890. passed: false,
  2891. issues: [{
  2892. severity: "critical",
  2893. category: "Chronicle Drift Check",
  2894. description: "The chapter is presented as 'chapter 2', but the supplied Current State Card still lists 'Current Chapter | 1'.",
  2895. suggestion: "Sync the state card before re-audit.",
  2896. }],
  2897. summary: "stale state card",
  2898. });
  2899. });
  2900. vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  2901. createReviseOutput({
  2902. revisedContent: revisedBody,
  2903. wordCount: countChapterLength(revisedBody, "en_words"),
  2904. fixedIssues: ["- Synced the annexe beat and tightened the ending."],
  2905. updatedState: createStateCard({
  2906. chapter: 2,
  2907. location: "East annexe corridor",
  2908. protagonistState: "Taryn is pressed against the annexe door with the true key in hand.",
  2909. goal: "Open the annexe before the cart clears the court.",
  2910. conflict: "A forged key and rival searchers have turned lawful access into a trap.",
  2911. }),
  2912. updatedHooks: "# Pending Hooks\n",
  2913. }),
  2914. );
  2915. try {
  2916. const result = await runner.reviseDraft(bookId, 2);
  2917. const savedIndex = await state.loadChapterIndex(bookId);
  2918. expect(auditChapter).toHaveBeenCalledTimes(2);
  2919. expect(result.applied).toBe(true);
  2920. expect(result.status).toBe("ready-for-review");
  2921. expect(savedIndex[1]?.status).toBe("ready-for-review");
  2922. expect(savedIndex[1]?.auditIssues).toEqual([]);
  2923. } finally {
  2924. await rm(root, { recursive: true, force: true });
  2925. }
  2926. });
  2927. it("uses chapter length telemetry target for manual revise when available", async () => {
  2928. const { root, runner, state, bookId } = await createRunnerFixture();
  2929. const storyDir = join(state.bookDir(bookId), "story");
  2930. const chaptersDir = join(state.bookDir(bookId), "chapters");
  2931. const originalBody = "Tarin waited by the crooked berth marker and counted the missing lines twice.";
  2932. const revisedBody = `${originalBody}\n\nHe did not move until the second bell rang across the water.`;
  2933. await state.saveBookConfig(bookId, {
  2934. ...(await state.loadBookConfig(bookId)),
  2935. platform: "other",
  2936. genre: "progression",
  2937. language: "en",
  2938. chapterWordCount: 1800,
  2939. });
  2940. await Promise.all([
  2941. writeFile(join(chaptersDir, "0001_Test_Chapter.md"), `# Chapter 1: Test Chapter\n\n${originalBody}`, "utf-8"),
  2942. writeFile(join(storyDir, "current_state.md"), createStateCard({
  2943. chapter: 1,
  2944. location: "Dock Nine",
  2945. protagonistState: "Tarin still carries the sealed packet.",
  2946. goal: "Find Captain Voss.",
  2947. conflict: "The berth is wrong and the crew is missing.",
  2948. }), "utf-8"),
  2949. writeFile(join(storyDir, "pending_hooks.md"), "# Pending Hooks\n", "utf-8"),
  2950. ]);
  2951. await state.saveChapterIndex(bookId, [{
  2952. number: 1,
  2953. title: "Test Chapter",
  2954. status: "audit-failed",
  2955. wordCount: countChapterLength(originalBody, "en_words"),
  2956. createdAt: "2026-03-19T00:00:00.000Z",
  2957. updatedAt: "2026-03-19T00:00:00.000Z",
  2958. auditIssues: [],
  2959. lengthWarnings: [],
  2960. lengthTelemetry: {
  2961. target: 900,
  2962. softMin: 778,
  2963. softMax: 1022,
  2964. hardMin: 655,
  2965. hardMax: 1145,
  2966. countingMode: "en_words",
  2967. writerCount: countChapterLength(originalBody, "en_words"),
  2968. postWriterNormalizeCount: countChapterLength(originalBody, "en_words"),
  2969. postReviseCount: 0,
  2970. finalCount: countChapterLength(originalBody, "en_words"),
  2971. normalizeApplied: false,
  2972. lengthWarning: false,
  2973. },
  2974. }]);
  2975. vi.spyOn(ContinuityAuditor.prototype, "auditChapter")
  2976. .mockResolvedValueOnce(
  2977. createAuditResult({
  2978. passed: false,
  2979. issues: [CRITICAL_ISSUE],
  2980. summary: "needs revision",
  2981. }),
  2982. )
  2983. .mockResolvedValueOnce(
  2984. createAuditResult({
  2985. passed: true,
  2986. issues: [],
  2987. summary: "clean",
  2988. }),
  2989. );
  2990. const reviseChapter = vi.spyOn(ReviserAgent.prototype, "reviseChapter").mockResolvedValue(
  2991. createReviseOutput({
  2992. revisedContent: revisedBody,
  2993. wordCount: countChapterLength(revisedBody, "en_words"),
  2994. fixedIssues: ["- Tightened the berth discovery beat."],
  2995. updatedState: createStateCard({
  2996. chapter: 1,
  2997. location: "Dock Nine",
  2998. protagonistState: "Tarin still carries the sealed packet.",
  2999. goal: "Find Captain Voss.",
  3000. conflict: "The berth is wrong and the crew is missing.",
  3001. }),
  3002. updatedHooks: "# Pending Hooks\n",
  3003. }),
  3004. );
  3005. try {
  3006. await runner.reviseDraft(bookId, 1, "polish");
  3007. expect(reviseChapter).toHaveBeenCalledTimes(1);
  3008. expect(reviseChapter.mock.calls[0]?.[6]?.lengthSpec).toMatchObject({
  3009. target: 900,
  3010. countingMode: "en_words",
  3011. });
  3012. } finally {
  3013. await rm(root, { recursive: true, force: true });
  3014. }
  3015. });
  3016. });