planner.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. import { readFile, writeFile, mkdir } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { BaseAgent } from "./base.js";
  4. import type { BookConfig } from "../models/book.js";
  5. import { parseBookRules } from "../models/book-rules.js";
  6. import { ChapterIntentSchema, type ChapterConflict, type ChapterIntent } from "../models/input-governance.js";
  7. import {
  8. parseChapterSummariesMarkdown,
  9. renderHookSnapshot,
  10. renderSummarySnapshot,
  11. retrieveMemorySelection,
  12. } from "../utils/memory-retrieval.js";
  13. import { analyzeChapterCadence } from "../utils/chapter-cadence.js";
  14. import { buildPlannerHookAgenda } from "../utils/hook-agenda.js";
  15. export interface PlanChapterInput {
  16. readonly book: BookConfig;
  17. readonly bookDir: string;
  18. readonly chapterNumber: number;
  19. readonly externalContext?: string;
  20. }
  21. export interface PlanChapterOutput {
  22. readonly intent: ChapterIntent;
  23. readonly intentMarkdown: string;
  24. readonly plannerInputs: ReadonlyArray<string>;
  25. readonly runtimePath: string;
  26. }
  27. export class PlannerAgent extends BaseAgent {
  28. get name(): string {
  29. return "planner";
  30. }
  31. async planChapter(input: PlanChapterInput): Promise<PlanChapterOutput> {
  32. const storyDir = join(input.bookDir, "story");
  33. const runtimeDir = join(storyDir, "runtime");
  34. await mkdir(runtimeDir, { recursive: true });
  35. const sourcePaths = {
  36. authorIntent: join(storyDir, "author_intent.md"),
  37. currentFocus: join(storyDir, "current_focus.md"),
  38. storyBible: join(storyDir, "story_bible.md"),
  39. volumeOutline: join(storyDir, "volume_outline.md"),
  40. chapterSummaries: join(storyDir, "chapter_summaries.md"),
  41. bookRules: join(storyDir, "book_rules.md"),
  42. currentState: join(storyDir, "current_state.md"),
  43. } as const;
  44. const [
  45. authorIntent,
  46. currentFocus,
  47. storyBible,
  48. volumeOutline,
  49. chapterSummaries,
  50. bookRulesRaw,
  51. currentState,
  52. ] = await Promise.all([
  53. this.readFileOrDefault(sourcePaths.authorIntent),
  54. this.readFileOrDefault(sourcePaths.currentFocus),
  55. this.readFileOrDefault(sourcePaths.storyBible),
  56. this.readFileOrDefault(sourcePaths.volumeOutline),
  57. this.readFileOrDefault(sourcePaths.chapterSummaries),
  58. this.readFileOrDefault(sourcePaths.bookRules),
  59. this.readFileOrDefault(sourcePaths.currentState),
  60. ]);
  61. const outlineNode = this.findOutlineNode(volumeOutline, input.chapterNumber);
  62. const matchedOutlineAnchor = this.hasMatchedOutlineAnchor(volumeOutline, input.chapterNumber);
  63. const goal = this.deriveGoal(input.externalContext, currentFocus, authorIntent, outlineNode, input.chapterNumber);
  64. const parsedRules = parseBookRules(bookRulesRaw);
  65. const mustKeep = this.collectMustKeep(currentState, storyBible);
  66. const mustAvoid = this.collectMustAvoid(currentFocus, parsedRules.rules.prohibitions);
  67. const styleEmphasis = this.collectStyleEmphasis(authorIntent, currentFocus);
  68. const conflicts = this.collectConflicts(input.externalContext, currentFocus, outlineNode, volumeOutline);
  69. const planningAnchor = conflicts.length > 0 ? undefined : outlineNode;
  70. const memorySelection = await retrieveMemorySelection({
  71. bookDir: input.bookDir,
  72. chapterNumber: input.chapterNumber,
  73. goal,
  74. outlineNode: planningAnchor,
  75. mustKeep,
  76. });
  77. const activeHookCount = memorySelection.activeHooks.filter(
  78. (hook) => hook.status !== "resolved" && hook.status !== "deferred",
  79. ).length;
  80. const hookAgenda = buildPlannerHookAgenda({
  81. hooks: memorySelection.activeHooks,
  82. chapterNumber: input.chapterNumber,
  83. targetChapters: input.book.targetChapters,
  84. language: input.book.language ?? "zh",
  85. });
  86. const directives = this.buildStructuredDirectives({
  87. chapterNumber: input.chapterNumber,
  88. language: input.book.language,
  89. volumeOutline,
  90. outlineNode,
  91. matchedOutlineAnchor,
  92. chapterSummaries,
  93. });
  94. const intent = ChapterIntentSchema.parse({
  95. chapter: input.chapterNumber,
  96. goal,
  97. outlineNode,
  98. ...directives,
  99. mustKeep,
  100. mustAvoid,
  101. styleEmphasis,
  102. conflicts,
  103. hookAgenda,
  104. });
  105. const runtimePath = join(runtimeDir, `chapter-${String(input.chapterNumber).padStart(4, "0")}.intent.md`);
  106. const intentMarkdown = this.renderIntentMarkdown(
  107. intent,
  108. input.book.language ?? "zh",
  109. renderHookSnapshot(memorySelection.hooks, input.book.language ?? "zh"),
  110. renderSummarySnapshot(memorySelection.summaries, input.book.language ?? "zh"),
  111. activeHookCount,
  112. );
  113. await writeFile(runtimePath, intentMarkdown, "utf-8");
  114. return {
  115. intent,
  116. intentMarkdown,
  117. plannerInputs: [
  118. ...Object.values(sourcePaths),
  119. join(storyDir, "pending_hooks.md"),
  120. ...(memorySelection.dbPath ? [memorySelection.dbPath] : []),
  121. ],
  122. runtimePath,
  123. };
  124. }
  125. private buildStructuredDirectives(input: {
  126. readonly chapterNumber: number;
  127. readonly language?: string;
  128. readonly volumeOutline: string;
  129. readonly outlineNode: string | undefined;
  130. readonly matchedOutlineAnchor: boolean;
  131. readonly chapterSummaries: string;
  132. }): Pick<ChapterIntent, "sceneDirective" | "arcDirective" | "moodDirective" | "titleDirective"> {
  133. const recentSummaries = parseChapterSummariesMarkdown(input.chapterSummaries)
  134. .filter((summary) => summary.chapter < input.chapterNumber)
  135. .sort((left, right) => left.chapter - right.chapter)
  136. .slice(-4);
  137. const cadence = analyzeChapterCadence({
  138. language: this.isChineseLanguage(input.language) ? "zh" : "en",
  139. rows: recentSummaries.map((summary) => ({
  140. chapter: summary.chapter,
  141. title: summary.title,
  142. mood: summary.mood,
  143. chapterType: summary.chapterType,
  144. })),
  145. });
  146. return {
  147. arcDirective: this.buildArcDirective(
  148. input.language,
  149. input.volumeOutline,
  150. input.outlineNode,
  151. input.matchedOutlineAnchor,
  152. ),
  153. sceneDirective: this.buildSceneDirective(input.language, cadence),
  154. moodDirective: this.buildMoodDirective(input.language, cadence),
  155. titleDirective: this.buildTitleDirective(input.language, cadence),
  156. };
  157. }
  158. private deriveGoal(
  159. externalContext: string | undefined,
  160. currentFocus: string,
  161. authorIntent: string,
  162. outlineNode: string | undefined,
  163. chapterNumber: number,
  164. ): string {
  165. const first = this.extractFirstDirective(externalContext);
  166. if (first) return first;
  167. const localOverride = this.extractLocalOverrideGoal(currentFocus);
  168. if (localOverride) return localOverride;
  169. const outline = this.extractFirstDirective(outlineNode);
  170. if (outline) return outline;
  171. const focus = this.extractFocusGoal(currentFocus);
  172. if (focus) return focus;
  173. const author = this.extractFirstDirective(authorIntent);
  174. if (author) return author;
  175. return `Advance chapter ${chapterNumber} with clear narrative focus.`;
  176. }
  177. private collectMustKeep(currentState: string, storyBible: string): string[] {
  178. return this.unique([
  179. ...this.extractListItems(currentState, 2),
  180. ...this.extractListItems(storyBible, 2),
  181. ]).slice(0, 4);
  182. }
  183. private collectMustAvoid(currentFocus: string, prohibitions: ReadonlyArray<string>): string[] {
  184. const avoidSection = this.extractSection(currentFocus, [
  185. "avoid",
  186. "must avoid",
  187. "禁止",
  188. "避免",
  189. "避雷",
  190. ]);
  191. const focusAvoids = avoidSection
  192. ? this.extractListItems(avoidSection, 10)
  193. : currentFocus
  194. .split("\n")
  195. .map((line) => line.trim())
  196. .filter((line) =>
  197. line.startsWith("-") &&
  198. /avoid|don't|do not|不要|别|禁止/i.test(line),
  199. )
  200. .map((line) => this.cleanListItem(line))
  201. .filter((line): line is string => Boolean(line));
  202. return this.unique([...focusAvoids, ...prohibitions]).slice(0, 6);
  203. }
  204. private collectStyleEmphasis(authorIntent: string, currentFocus: string): string[] {
  205. return this.unique([
  206. ...this.extractFocusStyleItems(currentFocus),
  207. ...this.extractListItems(authorIntent, 2),
  208. ]).slice(0, 4);
  209. }
  210. private collectConflicts(
  211. externalContext: string | undefined,
  212. currentFocus: string,
  213. outlineNode: string | undefined,
  214. volumeOutline: string,
  215. ): ChapterConflict[] {
  216. const outlineText = outlineNode ?? volumeOutline;
  217. if (!outlineText || outlineText === "(文件尚未创建)") return [];
  218. if (externalContext) {
  219. const indicatesOverride = /ignore|skip|defer|instead|不要|别|先别|暂停/i.test(externalContext);
  220. if (!indicatesOverride && this.hasKeywordOverlap(externalContext, outlineText)) return [];
  221. return [
  222. {
  223. type: "outline_vs_request",
  224. resolution: "allow local outline deferral",
  225. },
  226. ];
  227. }
  228. const localOverride = this.extractLocalOverrideGoal(currentFocus);
  229. if (!localOverride || !outlineNode) {
  230. return [];
  231. }
  232. return [
  233. {
  234. type: "outline_vs_current_focus",
  235. resolution: "allow explicit current focus override",
  236. detail: localOverride,
  237. },
  238. ];
  239. }
  240. private extractFirstDirective(content?: string): string | undefined {
  241. if (!content) return undefined;
  242. return content
  243. .split("\n")
  244. .map((line) => line.trim())
  245. .find((line) =>
  246. line.length > 0
  247. && !line.startsWith("#")
  248. && !line.startsWith("-")
  249. && !this.isTemplatePlaceholder(line),
  250. );
  251. }
  252. private extractListItems(content: string, limit: number): string[] {
  253. return content
  254. .split("\n")
  255. .map((line) => line.trim())
  256. .filter((line) => line.startsWith("-"))
  257. .map((line) => this.cleanListItem(line))
  258. .filter((line): line is string => Boolean(line))
  259. .slice(0, limit);
  260. }
  261. private extractFocusGoal(currentFocus: string): string | undefined {
  262. const focusSection = this.extractSection(currentFocus, [
  263. "active focus",
  264. "focus",
  265. "当前聚焦",
  266. "当前焦点",
  267. "近期聚焦",
  268. ]) ?? currentFocus;
  269. const directives = this.extractFocusStyleItems(focusSection, 3);
  270. if (directives.length === 0) {
  271. return this.extractFirstDirective(focusSection);
  272. }
  273. return directives.join(this.containsChinese(focusSection) ? ";" : "; ");
  274. }
  275. private extractLocalOverrideGoal(currentFocus: string): string | undefined {
  276. const overrideSection = this.extractSection(currentFocus, [
  277. "local override",
  278. "explicit override",
  279. "chapter override",
  280. "local task override",
  281. "局部覆盖",
  282. "本章覆盖",
  283. "临时覆盖",
  284. "当前覆盖",
  285. ]);
  286. if (!overrideSection) {
  287. return undefined;
  288. }
  289. const directives = this.extractListItems(overrideSection, 3);
  290. if (directives.length > 0) {
  291. return directives.join(this.containsChinese(overrideSection) ? ";" : "; ");
  292. }
  293. return this.extractFirstDirective(overrideSection);
  294. }
  295. private extractFocusStyleItems(currentFocus: string, limit = 3): string[] {
  296. const focusSection = this.extractSection(currentFocus, [
  297. "active focus",
  298. "focus",
  299. "当前聚焦",
  300. "当前焦点",
  301. "近期聚焦",
  302. ]) ?? currentFocus;
  303. return this.extractListItems(focusSection, limit);
  304. }
  305. private buildArcDirective(
  306. language: string | undefined,
  307. volumeOutline: string,
  308. outlineNode: string | undefined,
  309. matchedOutlineAnchor: boolean,
  310. ): string | undefined {
  311. if (matchedOutlineAnchor || !outlineNode || volumeOutline === "(文件尚未创建)") {
  312. return undefined;
  313. }
  314. return this.isChineseLanguage(language)
  315. ? "不要继续依赖卷纲的 fallback 指令,必须把本章推进到新的弧线节点或地点变化。"
  316. : "Do not keep leaning on the outline fallback. Force this chapter toward a fresh arc beat or location change.";
  317. }
  318. private buildSceneDirective(
  319. language: string | undefined,
  320. cadence: ReturnType<typeof analyzeChapterCadence>,
  321. ): string | undefined {
  322. if (cadence.scenePressure?.pressure !== "high") {
  323. return undefined;
  324. }
  325. const repeatedType = cadence.scenePressure.repeatedType;
  326. return this.isChineseLanguage(language)
  327. ? `最近章节连续停留在“${repeatedType}”,本章必须更换场景容器、地点或行动方式。`
  328. : `Recent chapters are stuck in repeated ${repeatedType} beats. Change the scene container, location, or action pattern this chapter.`;
  329. }
  330. private buildMoodDirective(
  331. language: string | undefined,
  332. cadence: ReturnType<typeof analyzeChapterCadence>,
  333. ): string | undefined {
  334. if (cadence.moodPressure?.pressure !== "high") {
  335. return undefined;
  336. }
  337. const moods = cadence.moodPressure.recentMoods;
  338. return this.isChineseLanguage(language)
  339. ? `最近${moods.length}章情绪持续高压(${moods.slice(0, 3).join("、")}),本章必须降调——安排日常/喘息/温情/幽默场景,让读者呼吸。`
  340. : `The last ${moods.length} chapters have been relentlessly tense (${moods.slice(0, 3).join(", ")}). This chapter must downshift — write a quieter scene with warmth, humor, or breathing room.`;
  341. }
  342. private buildTitleDirective(
  343. language: string | undefined,
  344. cadence: ReturnType<typeof analyzeChapterCadence>,
  345. ): string | undefined {
  346. if (cadence.titlePressure?.pressure !== "high") {
  347. return undefined;
  348. }
  349. const repeatedToken = cadence.titlePressure.repeatedToken;
  350. return this.isChineseLanguage(language)
  351. ? `标题不要再围绕“${repeatedToken}”重复命名,换一个新的意象或动作焦点。`
  352. : `Avoid another ${repeatedToken}-centric title. Pick a new image or action focus for this chapter title.`;
  353. }
  354. private renderHookBudget(activeCount: number, language: "zh" | "en"): string {
  355. const cap = 12;
  356. if (activeCount < 10) {
  357. return language === "en"
  358. ? `### Hook Budget\n- ${activeCount} active hooks (capacity: ${cap})`
  359. : `### 伏笔预算\n- 当前 ${activeCount} 条活跃伏笔(容量:${cap})`;
  360. }
  361. const remaining = Math.max(0, cap - activeCount);
  362. return language === "en"
  363. ? `### Hook Budget\n- ${activeCount} active hooks — approaching capacity (${cap}). Only ${remaining} new hook(s) allowed. Prioritize resolving existing debt over opening new threads.`
  364. : `### 伏笔预算\n- 当前 ${activeCount} 条活跃伏笔——接近容量上限(${cap})。仅剩 ${remaining} 个新坑位。优先回收旧债,不要轻易开新线。`;
  365. }
  366. private extractSection(content: string, headings: ReadonlyArray<string>): string | undefined {
  367. const targets = headings.map((heading) => this.normalizeHeading(heading));
  368. const lines = content.split("\n");
  369. let buffer: string[] | null = null;
  370. let sectionLevel = 0;
  371. for (const line of lines) {
  372. const headingMatch = line.match(/^(#+)\s*(.+?)\s*$/);
  373. if (headingMatch) {
  374. const level = headingMatch[1]!.length;
  375. const heading = this.normalizeHeading(headingMatch[2]!);
  376. if (buffer && level <= sectionLevel) {
  377. break;
  378. }
  379. if (targets.includes(heading)) {
  380. buffer = [];
  381. sectionLevel = level;
  382. continue;
  383. }
  384. }
  385. if (buffer) {
  386. buffer.push(line);
  387. }
  388. }
  389. const section = buffer?.join("\n").trim();
  390. return section && section.length > 0 ? section : undefined;
  391. }
  392. private normalizeHeading(heading: string): string {
  393. return heading
  394. .toLowerCase()
  395. .replace(/[*_`:#]/g, "")
  396. .replace(/\s+/g, " ")
  397. .trim();
  398. }
  399. private cleanListItem(line: string): string | undefined {
  400. const cleaned = line.replace(/^-\s*/, "").trim();
  401. if (cleaned.length === 0) return undefined;
  402. if (/^[-|]+$/.test(cleaned)) return undefined;
  403. if (this.isTemplatePlaceholder(cleaned)) return undefined;
  404. return cleaned;
  405. }
  406. private isTemplatePlaceholder(line: string): boolean {
  407. const normalized = line.trim();
  408. if (!normalized) return false;
  409. return (
  410. /^\((describe|briefly describe|write)\b[\s\S]*\)$/i.test(normalized)
  411. || /^((?:在这里描述|描述|填写|写下)[\s\S]*)$/u.test(normalized)
  412. );
  413. }
  414. private containsChinese(content: string): boolean {
  415. return /[\u4e00-\u9fff]/.test(content);
  416. }
  417. private findOutlineNode(volumeOutline: string, chapterNumber: number): string | undefined {
  418. const lines = volumeOutline.split("\n").map((line) => line.trim()).filter(Boolean);
  419. for (let index = 0; index < lines.length; index += 1) {
  420. const line = lines[index]!;
  421. const match = this.matchExactOutlineLine(line, chapterNumber);
  422. if (!match) continue;
  423. const inlineContent = this.cleanOutlineContent(match[1]);
  424. if (inlineContent) {
  425. return inlineContent;
  426. }
  427. const nextContent = this.findNextOutlineContent(lines, index + 1);
  428. if (nextContent) {
  429. return nextContent;
  430. }
  431. }
  432. for (let index = 0; index < lines.length; index += 1) {
  433. const line = lines[index]!;
  434. const match = this.matchRangeOutlineLine(line, chapterNumber);
  435. if (!match) continue;
  436. const inlineContent = this.cleanOutlineContent(match[3]);
  437. if (inlineContent) {
  438. return inlineContent;
  439. }
  440. const nextContent = this.findNextOutlineContent(lines, index + 1);
  441. if (nextContent) {
  442. return nextContent;
  443. }
  444. }
  445. for (let index = 0; index < lines.length; index += 1) {
  446. const line = lines[index]!;
  447. if (!this.isOutlineAnchorLine(line)) continue;
  448. const exactMatch = this.matchAnyExactOutlineLine(line);
  449. if (exactMatch) {
  450. const inlineContent = this.cleanOutlineContent(exactMatch[1]);
  451. if (inlineContent) {
  452. return inlineContent;
  453. }
  454. }
  455. const rangeMatch = this.matchAnyRangeOutlineLine(line);
  456. if (rangeMatch) {
  457. const inlineContent = this.cleanOutlineContent(rangeMatch[3]);
  458. if (inlineContent) {
  459. return inlineContent;
  460. }
  461. }
  462. const nextContent = this.findNextOutlineContent(lines, index + 1);
  463. if (nextContent) {
  464. return nextContent;
  465. }
  466. break;
  467. }
  468. return this.extractFirstDirective(volumeOutline);
  469. }
  470. private cleanOutlineContent(content?: string): string | undefined {
  471. const cleaned = content?.trim();
  472. if (!cleaned) return undefined;
  473. if (/^[*_`~::-]+$/.test(cleaned)) return undefined;
  474. return cleaned;
  475. }
  476. private findNextOutlineContent(lines: ReadonlyArray<string>, startIndex: number): string | undefined {
  477. for (let index = startIndex; index < lines.length; index += 1) {
  478. const line = lines[index]!;
  479. if (!line) {
  480. continue;
  481. }
  482. if (this.isOutlineAnchorLine(line)) {
  483. return undefined;
  484. }
  485. if (line.startsWith("#")) {
  486. continue;
  487. }
  488. const cleaned = this.cleanOutlineContent(line);
  489. if (cleaned) {
  490. return cleaned;
  491. }
  492. }
  493. return undefined;
  494. }
  495. private hasMatchedOutlineAnchor(volumeOutline: string, chapterNumber: number): boolean {
  496. const lines = volumeOutline.split("\n").map((line) => line.trim()).filter(Boolean);
  497. return lines.some((line) =>
  498. this.matchExactOutlineLine(line, chapterNumber) !== undefined
  499. || this.matchRangeOutlineLine(line, chapterNumber) !== undefined,
  500. );
  501. }
  502. private matchExactOutlineLine(line: string, chapterNumber: number): RegExpMatchArray | undefined {
  503. const patterns = [
  504. new RegExp(`^(?:#+\\s*)?(?:[-*]\\s+)?(?:\\*\\*)?Chapter\\s*${chapterNumber}(?!\\d|\\s*[-~–—]\\s*\\d)(?:[::-])?(?:\\*\\*)?\\s*(.*)$`, "i"),
  505. new RegExp(`^(?:#+\\s*)?(?:[-*]\\s+)?(?:\\*\\*)?第\\s*${chapterNumber}\\s*章(?!\\d|\\s*[-~–—]\\s*\\d)(?:[::-])?(?:\\*\\*)?\\s*(.*)$`),
  506. ];
  507. return patterns
  508. .map((pattern) => line.match(pattern))
  509. .find((result): result is RegExpMatchArray => Boolean(result));
  510. }
  511. private matchAnyExactOutlineLine(line: string): RegExpMatchArray | undefined {
  512. const patterns = [
  513. /^(?:#+\s*)?(?:[-*]\s+)?(?:\*\*)?Chapter\s*\d+(?!\s*[-~–—]\s*\d)(?:[::-])?(?:\*\*)?\s*(.*)$/i,
  514. /^(?:#+\s*)?(?:[-*]\s+)?(?:\*\*)?第\s*\d+\s*章(?!\s*[-~–—]\s*\d)(?:[::-])?(?:\*\*)?\s*(.*)$/i,
  515. ];
  516. return patterns
  517. .map((pattern) => line.match(pattern))
  518. .find((result): result is RegExpMatchArray => Boolean(result));
  519. }
  520. private matchRangeOutlineLine(line: string, chapterNumber: number): RegExpMatchArray | undefined {
  521. const match = this.matchAnyRangeOutlineLine(line);
  522. if (!match) return undefined;
  523. if (this.isChapterWithinRange(match[1], match[2], chapterNumber)) {
  524. return match;
  525. }
  526. return undefined;
  527. }
  528. private matchAnyRangeOutlineLine(line: string): RegExpMatchArray | undefined {
  529. const patterns = [
  530. /^(?:#+\s*)?(?:[-*]\s+)?(?:\*\*)?Chapter\s*(\d+)\s*[-~–—]\s*(\d+)\b(?:[::-])?(?:\*\*)?\s*(.*)$/i,
  531. /^(?:#+\s*)?(?:[-*]\s+)?(?:\*\*)?第\s*(\d+)\s*[-~–—]\s*(\d+)\s*章(?:[::-])?(?:\*\*)?\s*(.*)$/i,
  532. ];
  533. return patterns
  534. .map((pattern) => line.match(pattern))
  535. .find((result): result is RegExpMatchArray => Boolean(result));
  536. }
  537. private isOutlineAnchorLine(line: string): boolean {
  538. return this.matchAnyExactOutlineLine(line) !== undefined
  539. || this.matchAnyRangeOutlineLine(line) !== undefined;
  540. }
  541. private isChapterWithinRange(startText: string | undefined, endText: string | undefined, chapterNumber: number): boolean {
  542. const start = Number.parseInt(startText ?? "", 10);
  543. const end = Number.parseInt(endText ?? "", 10);
  544. if (!Number.isFinite(start) || !Number.isFinite(end)) return false;
  545. const lower = Math.min(start, end);
  546. const upper = Math.max(start, end);
  547. return chapterNumber >= lower && chapterNumber <= upper;
  548. }
  549. private hasKeywordOverlap(left: string, right: string): boolean {
  550. const keywords = this.extractKeywords(left);
  551. if (keywords.length === 0) return false;
  552. const normalizedRight = right.toLowerCase();
  553. return keywords.some((keyword) => normalizedRight.includes(keyword.toLowerCase()));
  554. }
  555. private extractKeywords(content: string): string[] {
  556. const english = content.match(/[a-z]{4,}/gi) ?? [];
  557. const chinese = content.match(/[\u4e00-\u9fff]{2,4}/g) ?? [];
  558. return this.unique([...english, ...chinese]);
  559. }
  560. private renderIntentMarkdown(
  561. intent: ChapterIntent,
  562. language: "zh" | "en",
  563. pendingHooks: string,
  564. chapterSummaries: string,
  565. activeHookCount: number,
  566. ): string {
  567. const conflictLines = intent.conflicts.length > 0
  568. ? intent.conflicts.map((conflict) => `- ${conflict.type}: ${conflict.resolution}`).join("\n")
  569. : "- none";
  570. const mustKeep = intent.mustKeep.length > 0
  571. ? intent.mustKeep.map((item) => `- ${item}`).join("\n")
  572. : "- none";
  573. const mustAvoid = intent.mustAvoid.length > 0
  574. ? intent.mustAvoid.map((item) => `- ${item}`).join("\n")
  575. : "- none";
  576. const styleEmphasis = intent.styleEmphasis.length > 0
  577. ? intent.styleEmphasis.map((item) => `- ${item}`).join("\n")
  578. : "- none";
  579. const directives = [
  580. intent.arcDirective ? `- arc: ${intent.arcDirective}` : undefined,
  581. intent.sceneDirective ? `- scene: ${intent.sceneDirective}` : undefined,
  582. intent.moodDirective ? `- mood: ${intent.moodDirective}` : undefined,
  583. intent.titleDirective ? `- title: ${intent.titleDirective}` : undefined,
  584. ].filter(Boolean).join("\n") || "- none";
  585. const hookAgenda = [
  586. "### Must Advance",
  587. intent.hookAgenda.mustAdvance.length > 0
  588. ? intent.hookAgenda.mustAdvance.map((item) => `- ${item}`).join("\n")
  589. : "- none",
  590. "",
  591. "### Eligible Resolve",
  592. intent.hookAgenda.eligibleResolve.length > 0
  593. ? intent.hookAgenda.eligibleResolve.map((item) => `- ${item}`).join("\n")
  594. : "- none",
  595. "",
  596. "### Stale Debt",
  597. intent.hookAgenda.staleDebt.length > 0
  598. ? intent.hookAgenda.staleDebt.map((item) => `- ${item}`).join("\n")
  599. : "- none",
  600. "",
  601. "### Avoid New Hook Families",
  602. intent.hookAgenda.avoidNewHookFamilies.length > 0
  603. ? intent.hookAgenda.avoidNewHookFamilies.map((item) => `- ${item}`).join("\n")
  604. : "- none",
  605. "",
  606. this.renderHookBudget(activeHookCount, language),
  607. ].join("\n");
  608. return [
  609. "# Chapter Intent",
  610. "",
  611. "## Goal",
  612. intent.goal,
  613. "",
  614. "## Outline Node",
  615. intent.outlineNode ?? "(not found)",
  616. "",
  617. "## Must Keep",
  618. mustKeep,
  619. "",
  620. "## Must Avoid",
  621. mustAvoid,
  622. "",
  623. "## Style Emphasis",
  624. styleEmphasis,
  625. "",
  626. "## Structured Directives",
  627. directives,
  628. "",
  629. "## Hook Agenda",
  630. hookAgenda,
  631. "",
  632. "## Conflicts",
  633. conflictLines,
  634. "",
  635. "## Pending Hooks Snapshot",
  636. pendingHooks,
  637. "",
  638. "## Chapter Summaries Snapshot",
  639. chapterSummaries,
  640. "",
  641. ].join("\n");
  642. }
  643. private unique(values: ReadonlyArray<string>): string[] {
  644. return [...new Set(values.map((value) => value.trim()).filter(Boolean))];
  645. }
  646. private isChineseLanguage(language: string | undefined): boolean {
  647. return (language ?? "zh").toLowerCase().startsWith("zh");
  648. }
  649. private async readFileOrDefault(path: string): Promise<string> {
  650. try {
  651. return await readFile(path, "utf-8");
  652. } catch {
  653. return "(文件尚未创建)";
  654. }
  655. }
  656. }