write.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import { Command } from "commander";
  2. import { PipelineRunner, StateManager } from "@actalk/inkos-core";
  3. import { readdir, unlink } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { createInterface } from "node:readline";
  6. import { loadConfig, buildPipelineConfig, findProjectRoot, getLegacyMigrationHint, resolveContext, resolveBookId, log, logError } from "../utils.js";
  7. import { formatWriteNextComplete, formatWriteNextProgress, formatWriteNextResultLines, resolveCliLanguage } from "../localization.js";
  8. export const writeCommand = new Command("write")
  9. .description("Write chapters");
  10. writeCommand
  11. .command("next")
  12. .description("Write the next chapter for a book")
  13. .argument("[book-id]", "Book ID (auto-detected if only one book)")
  14. .option("--count <n>", "Number of chapters to write", "1")
  15. .option("--words <n>", "Words per chapter (overrides book config)")
  16. .option("--context <text>", "Creative guidance (natural language)")
  17. .option("--context-file <path>", "Read guidance from file")
  18. .option("--json", "Output JSON")
  19. .option("-q, --quiet", "Suppress console output")
  20. .action(async (bookIdArg: string | undefined, opts) => {
  21. try {
  22. const root = findProjectRoot();
  23. const bookId = await resolveBookId(bookIdArg, root);
  24. const context = await resolveContext(opts);
  25. const state = new StateManager(root);
  26. const book = await state.loadBookConfig(bookId);
  27. const language = resolveCliLanguage(book.language);
  28. const migrationHint = await getLegacyMigrationHint(root, bookId);
  29. if (migrationHint && !opts.json) {
  30. log(`[migration] ${migrationHint}`);
  31. }
  32. const config = await loadConfig();
  33. const pipeline = new PipelineRunner(buildPipelineConfig(config, root, { externalContext: context, quiet: opts.quiet }));
  34. const count = parseInt(opts.count, 10);
  35. const wordCount = opts.words ? parseInt(opts.words, 10) : undefined;
  36. const results = [];
  37. for (let i = 0; i < count; i++) {
  38. if (!opts.json) log(formatWriteNextProgress(language, i + 1, count, bookId));
  39. const result = await pipeline.writeNextChapter(bookId, wordCount);
  40. results.push(result);
  41. if (!opts.json) {
  42. for (const line of formatWriteNextResultLines(language, {
  43. chapterNumber: result.chapterNumber,
  44. title: result.title,
  45. wordCount: result.wordCount,
  46. auditPassed: result.auditResult.passed,
  47. revised: result.revised,
  48. status: result.status,
  49. issues: result.auditResult.issues,
  50. })) {
  51. log(line);
  52. }
  53. log("");
  54. }
  55. }
  56. if (opts.json) {
  57. log(JSON.stringify(results, null, 2));
  58. } else {
  59. log(formatWriteNextComplete(language));
  60. }
  61. } catch (e) {
  62. if (opts.json) {
  63. log(JSON.stringify({ error: String(e) }));
  64. } else {
  65. logError(`Failed to write chapter: ${e}`);
  66. }
  67. process.exit(1);
  68. }
  69. });
  70. writeCommand
  71. .command("rewrite")
  72. .description("Re-generate a specific chapter: rewrite [book-id] <chapter>")
  73. .argument("<args...>", "Book ID (optional) and chapter number")
  74. .option("--force", "Skip confirmation prompt")
  75. .option("--words <n>", "Words per chapter (overrides book config)")
  76. .option("--json", "Output JSON")
  77. .action(async (args: ReadonlyArray<string>, opts) => {
  78. try {
  79. const root = findProjectRoot();
  80. let bookId: string;
  81. let chapter: number;
  82. if (args.length === 1) {
  83. chapter = parseInt(args[0]!, 10);
  84. if (isNaN(chapter)) throw new Error(`Expected chapter number, got "${args[0]}"`);
  85. bookId = await resolveBookId(undefined, root);
  86. } else if (args.length === 2) {
  87. chapter = parseInt(args[1]!, 10);
  88. if (isNaN(chapter)) throw new Error(`Expected chapter number, got "${args[1]}"`);
  89. bookId = await resolveBookId(args[0], root);
  90. } else {
  91. throw new Error("Usage: inkos write rewrite [book-id] <chapter>");
  92. }
  93. if (!opts.force) {
  94. const rl = createInterface({ input: process.stdin, output: process.stdout });
  95. const answer = await new Promise<string>((resolve) => {
  96. rl.question(`Rewrite chapter ${chapter} of "${bookId}"? This will delete chapter ${chapter} and all later chapters. (y/N) `, resolve);
  97. });
  98. rl.close();
  99. if (answer.toLowerCase() !== "y") {
  100. log("Cancelled.");
  101. return;
  102. }
  103. }
  104. const state = new StateManager(root);
  105. const bookDir = state.bookDir(bookId);
  106. const chaptersDir = join(bookDir, "chapters");
  107. const migrationHint = await getLegacyMigrationHint(root, bookId);
  108. if (migrationHint && !opts.json) {
  109. log(`[migration] ${migrationHint}`);
  110. }
  111. // Remove existing chapter file
  112. const files = await readdir(chaptersDir);
  113. const paddedNum = String(chapter).padStart(4, "0");
  114. const existing = files.filter((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  115. for (const f of existing) {
  116. await unlink(join(chaptersDir, f));
  117. if (!opts.json) log(`Removed: ${f}`);
  118. }
  119. // Remove from index (and all chapters after it)
  120. const index = await state.loadChapterIndex(bookId);
  121. const trimmed = index.filter((ch) => ch.number < chapter);
  122. await state.saveChapterIndex(bookId, trimmed);
  123. // Also remove later chapter files since state will be rolled back
  124. const laterFiles = files.filter((f) => {
  125. const num = parseInt(f.slice(0, 4), 10);
  126. return num > chapter && f.endsWith(".md");
  127. });
  128. for (const f of laterFiles) {
  129. await unlink(join(chaptersDir, f));
  130. if (!opts.json) log(`Removed later chapter: ${f}`);
  131. }
  132. // Restore state to previous chapter's end-state (chapter 1 uses snapshot-0 from initBook)
  133. const restoreFrom = chapter - 1;
  134. const restored = await state.restoreState(bookId, restoreFrom);
  135. if (restored) {
  136. if (!opts.json) log(`State restored from chapter ${restoreFrom} snapshot.`);
  137. } else {
  138. if (!opts.json) log(`Warning: no snapshot for chapter ${restoreFrom}. Using current state.`);
  139. }
  140. if (!opts.json) log(`Regenerating chapter ${chapter}...`);
  141. const wordCount = opts.words ? parseInt(opts.words, 10) : undefined;
  142. const config = await loadConfig();
  143. const pipeline = new PipelineRunner(buildPipelineConfig(config, root));
  144. const result = await pipeline.writeNextChapter(bookId, wordCount);
  145. const book = await state.loadBookConfig(bookId);
  146. const language = resolveCliLanguage(book.language);
  147. if (opts.json) {
  148. log(JSON.stringify(result, null, 2));
  149. } else {
  150. for (const line of formatWriteNextResultLines(language, {
  151. chapterNumber: result.chapterNumber,
  152. title: result.title,
  153. wordCount: result.wordCount,
  154. auditPassed: result.auditResult.passed,
  155. revised: result.revised,
  156. status: result.status,
  157. issues: result.auditResult.issues,
  158. })) {
  159. log(line);
  160. }
  161. }
  162. } catch (e) {
  163. if (opts.json) {
  164. log(JSON.stringify({ error: String(e) }));
  165. } else {
  166. logError(`Failed to rewrite chapter: ${e}`);
  167. }
  168. process.exit(1);
  169. }
  170. });