narrarium-engine 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +409 -27
  2. package/dist/ai/budget.d.ts +18 -2
  3. package/dist/ai/budget.d.ts.map +1 -1
  4. package/dist/ai/budget.js +9 -2
  5. package/dist/ai/budget.js.map +1 -1
  6. package/dist/ai/catalog-fetch.d.ts.map +1 -1
  7. package/dist/ai/catalog-fetch.js +2 -1
  8. package/dist/ai/catalog-fetch.js.map +1 -1
  9. package/dist/ai/fetch-client.d.ts +13 -6
  10. package/dist/ai/fetch-client.d.ts.map +1 -1
  11. package/dist/ai/fetch-client.js +26 -3
  12. package/dist/ai/fetch-client.js.map +1 -1
  13. package/dist/ai/request.d.ts +1 -1
  14. package/dist/ai/request.d.ts.map +1 -1
  15. package/dist/ai/request.js +31 -5
  16. package/dist/ai/request.js.map +1 -1
  17. package/dist/ai/routing.d.ts.map +1 -1
  18. package/dist/ai/routing.js +1 -1
  19. package/dist/ai/routing.js.map +1 -1
  20. package/dist/ai/types.d.ts +29 -2
  21. package/dist/ai/types.d.ts.map +1 -1
  22. package/dist/ai/types.js +5 -2
  23. package/dist/ai/types.js.map +1 -1
  24. package/dist/autopilot/chapter-state.d.ts +19 -0
  25. package/dist/autopilot/chapter-state.d.ts.map +1 -0
  26. package/dist/autopilot/chapter-state.js +31 -0
  27. package/dist/autopilot/chapter-state.js.map +1 -0
  28. package/dist/autopilot/errors.d.ts +2 -1
  29. package/dist/autopilot/errors.d.ts.map +1 -1
  30. package/dist/autopilot/errors.js +17 -1
  31. package/dist/autopilot/errors.js.map +1 -1
  32. package/dist/autopilot/estimate-math.d.ts +19 -0
  33. package/dist/autopilot/estimate-math.d.ts.map +1 -0
  34. package/dist/autopilot/estimate-math.js +74 -0
  35. package/dist/autopilot/estimate-math.js.map +1 -0
  36. package/dist/autopilot/estimate-texts.d.ts +40 -0
  37. package/dist/autopilot/estimate-texts.d.ts.map +1 -0
  38. package/dist/autopilot/estimate-texts.js +130 -0
  39. package/dist/autopilot/estimate-texts.js.map +1 -0
  40. package/dist/autopilot/estimate.d.ts +303 -0
  41. package/dist/autopilot/estimate.d.ts.map +1 -0
  42. package/dist/autopilot/estimate.js +887 -0
  43. package/dist/autopilot/estimate.js.map +1 -0
  44. package/dist/autopilot/frozen.d.ts +166 -0
  45. package/dist/autopilot/frozen.d.ts.map +1 -0
  46. package/dist/autopilot/frozen.js +483 -0
  47. package/dist/autopilot/frozen.js.map +1 -0
  48. package/dist/autopilot/outline-change.d.ts +69 -0
  49. package/dist/autopilot/outline-change.d.ts.map +1 -0
  50. package/dist/autopilot/outline-change.js +42 -0
  51. package/dist/autopilot/outline-change.js.map +1 -0
  52. package/dist/autopilot/outline-check.d.ts +40 -0
  53. package/dist/autopilot/outline-check.d.ts.map +1 -0
  54. package/dist/autopilot/outline-check.js +84 -0
  55. package/dist/autopilot/outline-check.js.map +1 -0
  56. package/dist/autopilot/outline-compose.d.ts +203 -0
  57. package/dist/autopilot/outline-compose.d.ts.map +1 -0
  58. package/dist/autopilot/outline-compose.js +492 -0
  59. package/dist/autopilot/outline-compose.js.map +1 -0
  60. package/dist/autopilot/planner.d.ts +29 -1
  61. package/dist/autopilot/planner.d.ts.map +1 -1
  62. package/dist/autopilot/planner.js +78 -8
  63. package/dist/autopilot/planner.js.map +1 -1
  64. package/dist/autopilot/presets.d.ts +36 -0
  65. package/dist/autopilot/presets.d.ts.map +1 -0
  66. package/dist/autopilot/presets.js +54 -0
  67. package/dist/autopilot/presets.js.map +1 -0
  68. package/dist/autopilot/profile-check.d.ts +7 -4
  69. package/dist/autopilot/profile-check.d.ts.map +1 -1
  70. package/dist/autopilot/profile-check.js +9 -6
  71. package/dist/autopilot/profile-check.js.map +1 -1
  72. package/dist/autopilot/runner.d.ts +61 -7
  73. package/dist/autopilot/runner.d.ts.map +1 -1
  74. package/dist/autopilot/runner.js +313 -32
  75. package/dist/autopilot/runner.js.map +1 -1
  76. package/dist/autopilot/session.d.ts +50 -7
  77. package/dist/autopilot/session.d.ts.map +1 -1
  78. package/dist/autopilot/session.js +225 -10
  79. package/dist/autopilot/session.js.map +1 -1
  80. package/dist/autopilot/speed.d.ts +30 -0
  81. package/dist/autopilot/speed.d.ts.map +1 -0
  82. package/dist/autopilot/speed.js +71 -0
  83. package/dist/autopilot/speed.js.map +1 -0
  84. package/dist/autopilot/state.d.ts +21 -2
  85. package/dist/autopilot/state.d.ts.map +1 -1
  86. package/dist/autopilot/state.js +215 -3
  87. package/dist/autopilot/state.js.map +1 -1
  88. package/dist/autopilot/tasks.d.ts +14 -2
  89. package/dist/autopilot/tasks.d.ts.map +1 -1
  90. package/dist/autopilot/tasks.js +478 -34
  91. package/dist/autopilot/tasks.js.map +1 -1
  92. package/dist/autopilot/types.d.ts +238 -14
  93. package/dist/autopilot/types.d.ts.map +1 -1
  94. package/dist/autopilot/types.js +18 -2
  95. package/dist/autopilot/types.js.map +1 -1
  96. package/dist/book/context.d.ts +3 -0
  97. package/dist/book/context.d.ts.map +1 -1
  98. package/dist/book/context.js +7 -1
  99. package/dist/book/context.js.map +1 -1
  100. package/dist/book/freeze.d.ts +115 -0
  101. package/dist/book/freeze.d.ts.map +1 -0
  102. package/dist/book/freeze.js +286 -0
  103. package/dist/book/freeze.js.map +1 -0
  104. package/dist/book/outline.d.ts +245 -0
  105. package/dist/book/outline.d.ts.map +1 -0
  106. package/dist/book/outline.js +488 -0
  107. package/dist/book/outline.js.map +1 -0
  108. package/dist/book/paths.d.ts +18 -0
  109. package/dist/book/paths.d.ts.map +1 -1
  110. package/dist/book/paths.js +25 -0
  111. package/dist/book/paths.js.map +1 -1
  112. package/dist/book/snapshot.d.ts +25 -1
  113. package/dist/book/snapshot.d.ts.map +1 -1
  114. package/dist/book/snapshot.js +24 -4
  115. package/dist/book/snapshot.js.map +1 -1
  116. package/dist/director/opinion.d.ts +6 -0
  117. package/dist/director/opinion.d.ts.map +1 -1
  118. package/dist/director/opinion.js +4 -1
  119. package/dist/director/opinion.js.map +1 -1
  120. package/dist/index.d.ts +10 -0
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js +11 -0
  123. package/dist/index.js.map +1 -1
  124. package/dist/profiles/evaluation-style.d.ts +44 -0
  125. package/dist/profiles/evaluation-style.d.ts.map +1 -0
  126. package/dist/profiles/evaluation-style.js +152 -0
  127. package/dist/profiles/evaluation-style.js.map +1 -0
  128. package/dist/server/client.d.ts +92 -7
  129. package/dist/server/client.d.ts.map +1 -1
  130. package/dist/server/client.js +138 -11
  131. package/dist/server/client.js.map +1 -1
  132. package/dist/server/protocol.d.ts +226 -2
  133. package/dist/server/protocol.d.ts.map +1 -1
  134. package/dist/server/protocol.js +69 -0
  135. package/dist/server/protocol.js.map +1 -1
  136. package/dist/util/text.d.ts +6 -0
  137. package/dist/util/text.d.ts.map +1 -1
  138. package/dist/util/text.js +21 -0
  139. package/dist/util/text.js.map +1 -1
  140. package/dist/version.d.ts +1 -1
  141. package/dist/version.d.ts.map +1 -1
  142. package/dist/version.js +1 -1
  143. package/dist/version.js.map +1 -1
  144. package/package.json +1 -1
@@ -1,19 +1,23 @@
1
1
  import { normalizeScore, requireStructuredFields, splitReasoningBlock } from "../ai/structured.js";
2
2
  import { AI_CAPABILITIES, AiReplyRejectedError } from "../ai/types.js";
3
3
  import { canonDetails, canonManifest, ghostwriterBlock, isThinDocument, loadChapterParagraphs, loadGhostwriter, markedChapterText, mentionedCanon, readBody, readDocument, secretRules, } from "../book/context.js";
4
- import { AUTOPILOT_PLAN_FILE, BOOK_FILE, CONTEXT_FILE, PLOT_FILE, STORY_DESIGN_FILE, TOTAL_RESUME_FILE, canonPath, canonSlug, chapterFilePath, chapterResumePath, chapterSlug, directorOpinionPath, formatOrdinal, paragraphFilePath, paragraphId, paragraphSlug, readerEvaluationPath, readerSummaryPath, } from "../book/paths.js";
4
+ import { AUTOPILOT_PLAN_FILE, BOOK_FILE, CONTEXT_FILE, OUTLINE_BOOK_FILE, PLOT_FILE, STORY_DESIGN_FILE, TOTAL_RESUME_FILE, canonPath, canonSlug, chapterFilePath, chapterResumePath, chapterSlug, directorOpinionPath, formatOrdinal, isValidGhostwriterSlug, outlineChapterPath, paragraphFilePath, paragraphId, paragraphSlug, readerEvaluationPath, readerSummaryPath, } from "../book/paths.js";
5
+ import { chapterFreezeRecord, freezeChapterChanges, frozenChanges, markReviewedChanges } from "../book/freeze.js";
6
+ import { OUTLINE_TITLE_MAX_CHARS, OutlineReader, outlineBookDigest, outlineEntryDigest, serializeOutlineBook, serializeOutlineChapter } from "../book/outline.js";
5
7
  import { askDirector, directorSystemPrompt, parseDirectorVerdict, renderDirectorOpinion, withheldApprovalNote } from "../director/opinion.js";
6
8
  import { assertFrontmatterReadable, frontmatterString, parseMarkdown, renderMarkdown } from "../markdown/frontmatter.js";
9
+ import { evaluationStyleBlock, evaluationStyleInstruction } from "../profiles/evaluation-style.js";
7
10
  import { readerPersonaSystemPrompt } from "../profiles/readers.js";
8
11
  import { currentRequest, unescapePromptData, untrustedData } from "../prompt/trust.js";
9
12
  import { READER_EVALUATION_TOOL, READER_SUMMARY_TOOL, chapterReaderText, normalizeReaderEvaluationOutput, renderReaderEvaluationBody, renderReaderSummaryBody, } from "../readers/evaluation.js";
10
13
  import { sha256Hex } from "../util/hash.js";
11
14
  import { asArray, asInteger, asOneOf, asRecord, asString, asStringList } from "../util/json.js";
12
- import { bulletList, countWords, isItalian, languageName, OUTPUT_TOKENS_CEILING, sceneCharacterLimit, scaleOutputTokens, tokensPerWord, truncate } from "../util/text.js";
15
+ import { bulletList, clipText, countWords, isItalian, languageName, OUTPUT_TOKENS_CEILING, sceneCharacterLimit, scaleOutputTokens, tokensPerWord, truncate } from "../util/text.js";
13
16
  import { chapterLines, layoutChapters, listSection, outlineList } from "./outline.js";
14
- import { batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts, sceneFile } from "./planner.js";
17
+ import { legacyChapters, queuedMarkReviewed, startedReview } from "./frozen.js";
18
+ import { batchesNamed, effectiveTargetChapters, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts, sceneFile } from "./planner.js";
15
19
  import { CHAPTER_REVIEW_TOOL, CHAPTER_SUMMARY_TOOL, CONCEPT_TOOL, CONSOLIDATION_TOOL, FINDINGS_TOOL, IMPACT_TOOL, PLAN_REACTION_TOOL, PLAN_REVIEW_TOOL, PLAN_TOOL, SCENES_TOOL, SCENE_SUMMARY_TOOL, architectSystemPrompt, continuitySystemPrompt, specialistsSystemPrompt, writerSystemPrompt, } from "./prompts.js";
16
- import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES, closedRound, normalizeFinalReview, recordChapterRound } from "./state.js";
20
+ import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES, CONCEPT_LOGLINE_CHARACTERS, closedRound, normalizeFinalReview, recordChapterRound } from "./state.js";
17
21
  import { STORY_SO_FAR_MAX_WORDS, STORY_SO_FAR_TARGET_WORDS, pruneStorySnapshots, readStorySoFar, renderTotalResumeBody, storySoFarExcess } from "./story-so-far.js";
18
22
  // ─── Shared prompt fragments ────────────────────────────────────────────────
19
23
  function bookHeader(ctx) {
@@ -102,6 +106,139 @@ function ghostwriterOf(ctx, chapter) {
102
106
  onInvalid: (slug) => ctx.insight("warning", isItalian(ctx.language) ? `Il ghostwriter «${slug}» non è un nome di file valido: scrive quello predefinito` : `The ghostwriter «${slug}» is not a valid file name: the default one writes`, isItalian(ctx.language) ? "Correggi la riga `ghostwriter` del libro, del capitolo o della scena." : "Correct the `ghostwriter` line of the book, the chapter or the scene."),
103
107
  });
104
108
  }
109
+ // ─── The outline (Scaletta) and the evaluation style ───────────────────────
110
+ const outlineReaders = new WeakMap();
111
+ /** The outline of the book: the run's reader (with its cache), or one over the snapshot for a step that runs on its own. */
112
+ function outlineOf(ctx) {
113
+ if (ctx.outline)
114
+ return ctx.outline;
115
+ let reader = outlineReaders.get(ctx);
116
+ if (!reader) {
117
+ reader = OutlineReader.of(ctx.store, ctx.snapshot);
118
+ outlineReaders.set(ctx, reader);
119
+ }
120
+ return reader;
121
+ }
122
+ /** Characters of the description of the book, of the entries of the chapters a step plans (shared among them), and of the list of the others. */
123
+ const OUTLINE_BOOK_CHARS = 3000;
124
+ const OUTLINE_BATCH_CHARS = 24_000;
125
+ const OUTLINE_CONTEXT_CHARS = 12_000;
126
+ const OUTLINE_ENTRY_MIN_CHARS = 400;
127
+ async function authorOutline(ctx) {
128
+ const outline = outlineOf(ctx);
129
+ if (outline.empty)
130
+ return { entries: new Map(), any: false, lastChapter: 0 };
131
+ const [book, chapters] = await Promise.all([outline.book(), outline.chapters()]);
132
+ const entries = new Map(chapters.filter((entry) => !entry.intact).map((entry) => [entry.number, entry]));
133
+ const description = book && !book.intact && (book.body || book.title)
134
+ ? truncate([book.title ? `Working title: ${book.title}` : "", book.body].filter(Boolean).join("\n"), OUTLINE_BOOK_CHARS)
135
+ : undefined;
136
+ const lastChapter = [...entries.keys()].reduce((highest, number) => Math.max(highest, number), 0);
137
+ return { ...(description ? { book: description } : {}), entries, any: Boolean(description) || entries.size > 0, lastChapter };
138
+ }
139
+ function entryHeading(entry) {
140
+ return `Chapter ${entry.number} ${entry.title ? `«${entry.title}»` : "(no title yet: give it one)"}`;
141
+ }
142
+ const OUTLINE_ENTRIES = {
143
+ render(entry, detail) {
144
+ const head = `${entry.number}. ${entry.title || "(no title yet)"}`;
145
+ if (detail === "title" || !entry.body)
146
+ return head;
147
+ return `${head} — ${truncate(entry.body.replace(/\s+/g, " "), detail === "full" ? 600 : 200)}`;
148
+ },
149
+ collapse(entries, titles) {
150
+ const range = `Chapters ${entries[0].number}-${entries[entries.length - 1].number}`;
151
+ return titles ? `${range}: ${entries.map((entry) => entry.title || "(no title yet)").join("; ")}` : `${range} (entries of the outline)`;
152
+ },
153
+ };
154
+ function outlineBookSection(view) {
155
+ return view.book ? `AUTHOR'S OUTLINE, THE BOOK (binding):\n${view.book}` : "";
156
+ }
157
+ /** The entries of the chapters `from` to `to`, whole as far as their share of the budget allows. */
158
+ function outlineBatchSection(view, from, to) {
159
+ const entries = [...view.entries.values()].filter((entry) => entry.number >= from && entry.number <= to).sort((left, right) => left.number - right.number);
160
+ if (!entries.length)
161
+ return "";
162
+ const share = Math.max(OUTLINE_ENTRY_MIN_CHARS, Math.floor(OUTLINE_BATCH_CHARS / entries.length));
163
+ const label = from === to ? `CHAPTER ${from}` : `CHAPTERS ${from}-${to}`;
164
+ return `AUTHOR'S OUTLINE, ${label} (binding):\n${entries.map((entry) => `${entryHeading(entry)}:\n${truncate(entry.body, share) || "(no text)"}`).join("\n\n")}`;
165
+ }
166
+ /** Other entries of the outline, condensed around `around` like every list of chapters. */
167
+ function outlineListSection(entries, around, label) {
168
+ return entries.length ? listSection(label, layoutChapters(entries, OUTLINE_ENTRIES, { around, maxChars: OUTLINE_CONTEXT_CHARS })) : "";
169
+ }
170
+ const OUTLINE_RULE = "Follow the author's outline (AUTHOR'S OUTLINE, in the data): the same chapters, in the same order, with the same hypothetical titles (refine a title only where the entry has none) and the same events. Enrich it, never change it.";
171
+ const OUTLINE_AND_SYNOPSIS = "The chapter-by-chapter synopsis of the brief still applies where the outline says nothing; where they differ, the outline wins.";
172
+ /** The ghostwriter an entry names, when the book has it. One it does not have is said (with its code), and the book's writes the chapter. */
173
+ function outlineGhostwriter(ctx, entry) {
174
+ const slug = entry?.ghostwriter;
175
+ if (!entry || !slug)
176
+ return undefined;
177
+ if (isValidGhostwriterSlug(slug) && ctx.snapshot.ghostwriterSlugs.includes(slug))
178
+ return slug;
179
+ const italian = isItalian(ctx.language);
180
+ ctx.insight("warning", italian ? `La Scaletta del capitolo ${entry.number} indica il ghostwriter «${slug}», che non esiste: lo scrive quello del libro` : `The outline of chapter ${entry.number} names the ghostwriter «${slug}», which does not exist: the book's ghostwriter writes it`, italian ? `Crea ghostwriters/${slug}.md, oppure correggi la voce della Scaletta.` : `Create ghostwriters/${slug}.md, or correct the entry of the outline.`, { code: "outlineGhostwriter", chapterNumber: entry.number, ghostwriter: slug });
181
+ return undefined;
182
+ }
183
+ /** What the autopilot writes in the outline for a chapter: its title, then its summary and its key events as a list. */
184
+ function outlineContentOf(chapter) {
185
+ const body = [chapter.summary.trim(), chapter.keyEvents.length ? bulletList(chapter.keyEvents) : ""].filter(Boolean).join("\n\n");
186
+ return { title: chapter.title, body, ...(chapter.ghostwriter ? { ghostwriter: chapter.ghostwriter } : {}) };
187
+ }
188
+ /**
189
+ * The outline after a plan: a planned chapter without an entry gets one, as the autopilot's (`origin: autopilot`, with the `digest`
190
+ * of what it wrote); a chapter the author wrote gets one only when it has none, with its summary; an entry of the autopilot that
191
+ * nobody touched follows the new plan of its chapter; an entry of the author is never touched. Every chapter remembers the digest
192
+ * of its entry as it is after this step, so that a later change of the author is recognized. With `fillOutline` off nothing is
193
+ * written. `outline/book.md` is written once, when it is missing, with the logline of the concept.
194
+ */
195
+ async function fillOutline(ctx, planned, imported) {
196
+ const fill = ctx.state.options.fillOutline !== false;
197
+ const outline = outlineOf(ctx);
198
+ const entries = new Map((await outline.chapters()).map((entry) => [entry.number, entry]));
199
+ const changes = [];
200
+ const write = async (chapter, existing) => {
201
+ const content = outlineContentOf(chapter);
202
+ const digest = await outlineEntryDigest(content);
203
+ if (!existing || digest !== existing.contentDigest) {
204
+ changes.push({
205
+ path: existing?.path ?? outlineChapterPath(chapter.number),
206
+ content: serializeOutlineChapter({ number: chapter.number, ...content, origin: "autopilot", digest, frontmatter: existing?.frontmatter }),
207
+ expectedHash: existing ? existing.hash : null,
208
+ });
209
+ }
210
+ chapter.outlineDigest = digest;
211
+ };
212
+ for (const chapter of imported) {
213
+ const entry = entries.get(chapter.number);
214
+ if (entry)
215
+ chapter.outlineDigest = entry.contentDigest;
216
+ else if (fill && chapter.summary.trim())
217
+ await write(chapter);
218
+ else
219
+ delete chapter.outlineDigest;
220
+ }
221
+ for (const chapter of planned) {
222
+ const entry = entries.get(chapter.number);
223
+ if (entry && !(entry.intact && fill))
224
+ chapter.outlineDigest = entry.contentDigest;
225
+ else if (fill)
226
+ await write(chapter, entry ?? undefined);
227
+ else
228
+ delete chapter.outlineDigest;
229
+ }
230
+ if (fill && !outline.index.book) {
231
+ const body = clipText(ctx.state.concept.logline || ctx.state.brief.idea, CONCEPT_LOGLINE_CHARACTERS).trim();
232
+ if (body)
233
+ changes.push({ path: OUTLINE_BOOK_FILE, content: serializeOutlineBook({ body, origin: "autopilot", digest: await outlineBookDigest({ body }) }), expectedHash: null });
234
+ }
235
+ return changes;
236
+ }
237
+ /** The style a step that judges is given, among the data, and the instruction to judge with it; nothing without a style. */
238
+ function evaluationStyleOf(ctx, kind) {
239
+ const block = evaluationStyleBlock(ctx.evaluationStyle, { criteria: kind !== "plan" });
240
+ return block ? { block, rule: evaluationStyleInstruction(kind) } : { block: "", rule: "" };
241
+ }
105
242
  const MAX_NOTE_CHARACTERS = 400;
106
243
  /** Same note despite case, punctuation, quotes or spacing. */
107
244
  function noteKey(note) {
@@ -152,7 +289,7 @@ function sceneOf(chapter, number) {
152
289
  }
153
290
  function chapterFiles(ctx, chapter) {
154
291
  return ctx.snapshot.chapters.find((entry) => entry.slug === chapter.slug)
155
- ?? { slug: chapter.slug, number: chapter.number, title: chapter.title, pov: chapter.pov, path: chapterFilePath(chapter.slug), paragraphs: [] };
292
+ ?? { slug: chapter.slug, number: chapter.number, title: chapter.title, pov: chapter.pov, path: chapterFilePath(chapter.slug), paragraphs: [], ...(chapter.ghostwriter ? { ghostwriter: chapter.ghostwriter } : {}) };
156
293
  }
157
294
  /** A line that only labels the scene, in Latin script ("Scene 3:", "Scena 3."): the writer is asked for prose and nothing else. */
158
295
  const LATIN_SCENE_HEADING = /^(?:scene|scena)\s+\d+\s*[:.—-]/i;
@@ -209,12 +346,18 @@ async function assertRewritable(ctx, paths) {
209
346
  assertFrontmatterReadable(path, parseMarkdown(file.content), ctx.language);
210
347
  }
211
348
  }
212
- function chapterDocument(chapter) {
213
- return renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary: chapter.summary, pov: chapter.pov, canon: "draft" }, `# ${chapter.title}\n\n${chapter.goal || chapter.summary || ""}`);
349
+ /** The ghostwriter that writes a chapter that names none: the book's, else the default profile, else the first. */
350
+ function bookGhostwriter(snapshot) {
351
+ return snapshot.book.ghostwriter ?? (snapshot.ghostwriterSlugs.includes("default") ? "default" : snapshot.ghostwriterSlugs[0]);
352
+ }
353
+ /** The `chapter.md` of a chapter the plan creates, with the chapter's own ghostwriter when it is not the book's. */
354
+ function chapterDocument(chapter, snapshot) {
355
+ const ghostwriter = chapter.ghostwriter && (!snapshot || chapter.ghostwriter !== bookGhostwriter(snapshot)) ? chapter.ghostwriter : undefined;
356
+ return renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary: chapter.summary, pov: chapter.pov, ...(ghostwriter ? { ghostwriter } : {}), canon: "draft" }, `# ${chapter.title}\n\n${chapter.goal || chapter.summary || ""}`);
214
357
  }
215
358
  function ensureChapterFile(ctx, chapter) {
216
359
  const path = chapterFilePath(chapter.slug);
217
- return ctx.snapshot.files.has(path) ? null : { path, content: chapterDocument(chapter), expectedHash: null };
360
+ return ctx.snapshot.files.has(path) ? null : { path, content: chapterDocument(chapter, ctx.snapshot), expectedHash: null };
218
361
  }
219
362
  /** Human-readable mirror of the plan, refreshed whenever the plan changes. */
220
363
  export function renderPlanMarkdown(state, language) {
@@ -300,10 +443,11 @@ function compact(changes) {
300
443
  }
301
444
  // ─── Concept ────────────────────────────────────────────────────────────────
302
445
  async function runConcept(ctx) {
303
- const [bookBody, design, context] = await Promise.all([
446
+ const [bookBody, design, context, view] = await Promise.all([
304
447
  readBody(ctx.store, BOOK_FILE, 2500),
305
448
  readDocument(ctx.store, STORY_DESIGN_FILE),
306
449
  readDocument(ctx.store, CONTEXT_FILE),
450
+ authorOutline(ctx),
307
451
  ]);
308
452
  // Both files are rewritten from what the model says: one whose frontmatter cannot be read is refused before the call.
309
453
  if (design)
@@ -315,14 +459,17 @@ async function runConcept(ctx) {
315
459
  label: "autopilot:concept",
316
460
  system: architectSystemPrompt(ctx.language),
317
461
  user: `${request([
318
- `Design the foundation of this novel from the author's brief, for about ${ctx.state.brief.targetChapters} chapters.`,
462
+ `Design the foundation of this novel from the author's brief, for about ${effectiveTargetChapters(ctx.state, view)} chapters.`,
319
463
  "Create 3 to 8 characters with clear desires, fears and arcs, the key locations, factions only when useful, and 1 to 5 secrets that drive the plot, each with the chapter where the reader learns it.",
320
464
  ctx.state.brief.synopsis ? "The author's chapter-by-chapter synopsis is binding: the concept must make it possible exactly as written." : "",
465
+ view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) is binding too, and wins over the synopsis: the concept must make it possible exactly as written." : "",
321
466
  "Reuse the existing canon names instead of duplicating them.",
322
467
  authorRules(ctx),
323
468
  ])}\n\n${data([
324
469
  bookHeader(ctx),
325
470
  briefBlock(ctx),
471
+ outlineBookSection(view),
472
+ outlineListSection([...view.entries.values()], undefined, "AUTHOR'S OUTLINE, CHAPTER BY CHAPTER (binding)"),
326
473
  bookBody ? `BOOK DESCRIPTION:\n${bookBody}` : "",
327
474
  design?.document.body ? `CURRENT STORY DESIGN:\n${truncate(design.document.body, 4000)}` : "",
328
475
  context?.document.body ? `CURRENT WORLD CONTEXT:\n${truncate(context.document.body, 3000)}` : "",
@@ -415,7 +562,9 @@ async function runConcept(ctx) {
415
562
  const revealChapter = asInteger(secret.revealChapter, 0, 0, MAX_BOOK_CHAPTERS);
416
563
  secrets.push({ slug, title, revealChapter: revealChapter || undefined });
417
564
  }
418
- ctx.state.concept = { done: true, generated: true, secrets };
565
+ // The pitch of the book, kept for the description of the outline that the plan writes when the author has none.
566
+ const pitch = clipText(logline || asString(output.premise), CONCEPT_LOGLINE_CHARACTERS).trim();
567
+ ctx.state.concept = { done: true, generated: true, secrets, ...(pitch ? { logline: pitch } : {}) };
419
568
  if (logline)
420
569
  ctx.insight("ok", logline);
421
570
  const summary = italian
@@ -471,6 +620,13 @@ async function runSummarizeImported(ctx) {
471
620
  }
472
621
  if (planned)
473
622
  planned.summary = summary;
623
+ // A chapter the author wrote, summarized after the plan was made, gets its entry of the outline when it has none.
624
+ if (planned && ctx.state.options.fillOutline !== false && !outlineOf(ctx).has(chapter.number)) {
625
+ const content = { title: chapter.title, body: summary };
626
+ const digest = await outlineEntryDigest(content);
627
+ changes.push({ path: outlineChapterPath(chapter.number), content: serializeOutlineChapter({ number: chapter.number, ...content, origin: "autopilot", digest }), expectedHash: null });
628
+ planned.outlineDigest = digest;
629
+ }
474
630
  ctx.insight("ok", isItalian(ctx.language) ? `Capitolo ${chapter.number} riassunto` : `Chapter ${chapter.number} summarized`, summary);
475
631
  return { changes: compact(changes), summary };
476
632
  }
@@ -505,7 +661,10 @@ async function runPlan(ctx) {
505
661
  // The history of the rounds of a chapter that was reviewed outlives the plan being made again around it (the book is being extended).
506
662
  return earlier?.rounds?.length ? { ...kept, rounds: earlier.rounds } : kept;
507
663
  });
508
- const range = planRange(imported, ctx.state.brief.targetChapters);
664
+ // The author's outline binds the plan: its chapters, its order, its titles, its events, and as many chapters as it has.
665
+ const view = await authorOutline(ctx);
666
+ const target = effectiveTargetChapters(ctx.state, view);
667
+ const range = planRange(imported, target);
509
668
  const batch = nextPlanBatch(previous, range);
510
669
  if (!batch)
511
670
  throw new Error("There is no chapter left to plan.");
@@ -524,6 +683,10 @@ async function runPlan(ctx) {
524
683
  const changesToApply = notes.filter((note) => !isExtensionNote(note));
525
684
  const secretsPlan = ctx.state.concept.secrets.filter((secret) => secret.revealChapter).map((secret) => `- ${secret.title}: reveal in chapter ${secret.revealChapter}`).join("\n");
526
685
  const otherChapters = batched && previous ? { ...previous, chapters: previous.chapters.filter((chapter) => !chapter.imported && (chapter.number < from || chapter.number > to)) } : null;
686
+ // The chapters of this call that the outline says nothing about, and the entries of the chapters not planned yet beyond it.
687
+ const plannedNumbers = new Set((previous?.chapters ?? []).map((chapter) => chapter.number));
688
+ const unlisted = view.any ? Array.from({ length: batchCount }, (_, index) => from + index).filter((number) => !view.entries.has(number)) : [];
689
+ const ahead = [...view.entries.values()].filter((entry) => entry.number >= startNumber && (entry.number < from || entry.number > to) && !plannedNumbers.has(entry.number));
527
690
  const response = await ctx.ai({
528
691
  capability: AI_CAPABILITIES.writer,
529
692
  label: "autopilot:plan",
@@ -532,17 +695,22 @@ async function runPlan(ctx) {
532
695
  revising
533
696
  ? `Revise the chapter plan (chapters ${from}-${to}) applying the director's changes:\n${bulletList(notes)}`
534
697
  : `Plan the next ${batchCount} chapters of the novel, numbered ${from} to ${to}.`,
535
- batched ? `The novel will have ${ctx.state.brief.targetChapters} chapters in all and is planned in batches: this call covers only chapters ${from} to ${to}.` : "",
698
+ batched ? `The novel will have ${target} chapters in all and is planned in batches: this call covers only chapters ${from} to ${to}.` : "",
536
699
  batched ? (to < lastNumber ? `The story must not end before chapter ${lastNumber}: leave room for what the following chapters have to tell.` : `These are the last chapters of the book: close its arcs and end the story in chapter ${lastNumber}.`) : "",
537
700
  batched && revising ? `Apply only the changes that concern chapters ${from} to ${to} or the whole book: the other chapters are revised in their own call. Return every chapter of the range.` : "",
538
701
  batched && !revising && changesToApply.length ? `Apply the changes below that concern these chapters or the whole book:\n${bulletList(changesToApply)}` : "",
539
- ctx.state.brief.synopsis ? "Follow the author's chapter-by-chapter synopsis exactly: same chapters, same order, same events. Enrich, never change." : "",
702
+ view.any ? OUTLINE_RULE : ctx.state.brief.synopsis ? "Follow the author's chapter-by-chapter synopsis exactly: same chapters, same order, same events. Enrich, never change." : "",
703
+ view.any && ctx.state.brief.synopsis ? OUTLINE_AND_SYNOPSIS : "",
704
+ unlisted.length && unlisted.length < batchCount ? `The outline has no entry for ${unlisted.length === 1 ? `chapter ${unlisted[0]}` : `chapters ${unlisted.join(", ")}`}: plan ${unlisted.length === 1 ? "it" : "them"} so that the story leads from the entries before to the entries after.` : "",
540
705
  imported.length ? `Chapters 1-${startNumber - 1} are already written by the author: continue from them without changing them.` : "",
541
706
  "Every chapter must change something and raise the stakes; place every secret reveal in a specific chapter; vary the shape of chapters.",
542
707
  authorRules(ctx),
543
708
  ])}\n\n${data([
544
709
  bookHeader(ctx),
545
710
  briefBlock(ctx),
711
+ outlineBookSection(view),
712
+ outlineBatchSection(view, from, to),
713
+ outlineListSection(ahead, from, "AUTHOR'S OUTLINE, THE CHAPTERS AFTER THESE (binding)"),
546
714
  design ? `STORY DESIGN:\n${design}` : "",
547
715
  context ? `WORLD CONTEXT:\n${context}` : "",
548
716
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
@@ -563,7 +731,10 @@ async function runPlan(ctx) {
563
731
  throw new AiReplyRejectedError(`The chapter plan has ${proposed.length} chapters with a title, but ${batchCount} were requested (chapters ${from}-${to}).`);
564
732
  const planned = proposed.map((chapter, index) => {
565
733
  const number = from + index;
566
- const title = asString(chapter.title);
734
+ // The hypothetical title of the author's entry is the chapter's: the model refines a title only where the entry has none.
735
+ const entry = view.entries.get(number);
736
+ const title = entry?.title ? clipText(entry.title, OUTLINE_TITLE_MAX_CHARS).trim() : asString(chapter.title);
737
+ const ghostwriter = outlineGhostwriter(ctx, entry);
567
738
  return {
568
739
  number,
569
740
  title,
@@ -575,6 +746,7 @@ async function runPlan(ctx) {
575
746
  reveals: asStringList(chapter.reveals, 8),
576
747
  status: "planned",
577
748
  scenes: [],
749
+ ...(ghostwriter ? { ghostwriter } : {}),
578
750
  };
579
751
  });
580
752
  // The chapters of the range that are outside this batch stay as they are; the batch replaces what it covers.
@@ -621,7 +793,10 @@ async function runPlan(ctx) {
621
793
  readersDone: previous?.readersDone ?? false,
622
794
  ...(previous?.skippedReaders?.length ? { skippedReaders: previous.skippedReaders } : {}),
623
795
  awaitingAuthor: false,
796
+ ...(previous?.removedChapters?.length ? { removedChapters: previous.removedChapters } : {}),
624
797
  };
798
+ // The outline is filled from the plan in the same commit: what the author did not write, the author can now correct.
799
+ changes.push(...await fillOutline(ctx, planned, imported));
625
800
  changes.push(await planFileChange(ctx));
626
801
  // A batch of a long plan is reported under the chapters it covers; a short book's only batch, as ever, under their number.
627
802
  const italian = isItalian(ctx.language);
@@ -713,7 +888,8 @@ async function runPlanReview(ctx) {
713
888
  toRewrite.push(path);
714
889
  }
715
890
  await assertRewritable(ctx, toRewrite);
716
- const design = await readBody(ctx.store, STORY_DESIGN_FILE, 5000);
891
+ const [design, view] = await Promise.all([readBody(ctx.store, STORY_DESIGN_FILE, 5000), authorOutline(ctx)]);
892
+ const style = evaluationStyleOf(ctx, "plan");
717
893
  const lastRound = plan.rounds >= 2;
718
894
  const response = await ctx.ai({
719
895
  capability: AI_CAPABILITIES.director,
@@ -722,12 +898,17 @@ async function runPlanReview(ctx) {
722
898
  user: `${request([
723
899
  `Review the concept and the chapter plan before any prose is written (review ${plan.rounds + 1}).`,
724
900
  "Approve when the plan delivers the brief and the vision with a satisfying shape; otherwise list precise changes chapter by chapter. Weigh the simulated readers by their weights: do not chase every opinion.",
901
+ view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) binds the plan: never ask to change its chapters, their order, their titles or their events; ask only for what enriches them." : "",
902
+ style.rule,
725
903
  lastRound ? "This is the final plan review: approve it and turn anything still imperfect into standing guidance." : "",
726
904
  ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical choice you cannot settle from the vision and the author's rules.",
727
905
  authorRules(ctx, false),
728
906
  ])}\n\n${data([
729
907
  bookHeader(ctx),
730
908
  briefBlock(ctx),
909
+ outlineBookSection(view),
910
+ outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
911
+ style.block,
731
912
  design ? `STORY DESIGN:\n${design}` : "",
732
913
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
733
914
  listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
@@ -762,7 +943,7 @@ async function runPlanReview(ctx) {
762
943
  plan.rounds += 1;
763
944
  plan.revisionNotes = changesRequested;
764
945
  // Only the batches that hold the chapters the changes name are planned again; a change that names none concerns them all.
765
- plan.revisionBatches = batchesNamed(planRange(importedChapters(ctx.snapshot), ctx.state.brief.targetChapters), requested.map((change) => change.chapterNumber));
946
+ plan.revisionBatches = batchesNamed(planRange(importedChapters(ctx.snapshot), effectiveTargetChapters(ctx.state, view)), requested.map((change) => change.chapterNumber));
766
947
  ctx.insight("warning", isItalian(ctx.language) ? `Il direttore chiede ${changesRequested.length} modifiche al piano` : `The director asks for ${changesRequested.length} plan changes`, changesRequested.slice(0, 3).join(" · "));
767
948
  }
768
949
  else {
@@ -801,6 +982,113 @@ async function runPlanReview(ctx) {
801
982
  changes.push(await planFileChange(ctx));
802
983
  return { changes: compact(changes), summary: `${approved ? "approve" : "revise"} ${score}/10 — ${summaryText}` };
803
984
  }
985
+ // ─── The author changed the outline of a chapter not written yet ────────────
986
+ /**
987
+ * The `chapter.md` of a chapter with no text yet, made or brought up to date with its new plan: title, summary, point of view and
988
+ * the ghostwriter of the outline. A ghostwriter written by hand in a chapter the outline never gave one is left as it is.
989
+ */
990
+ async function chapterStubChange(ctx, chapter, before) {
991
+ const path = chapterFilePath(chapter.slug);
992
+ if (!ctx.snapshot.files.has(path))
993
+ return { path, content: chapterDocument(chapter, ctx.snapshot), expectedHash: null };
994
+ const own = chapter.ghostwriter && chapter.ghostwriter !== bookGhostwriter(ctx.snapshot) ? chapter.ghostwriter : undefined;
995
+ const oldBody = `# ${before.title}\n\n${before.goal || before.summary || ""}`.trim();
996
+ return changeFor(ctx, path, (existing) => {
997
+ const frontmatter = { ...(existing?.frontmatter ?? {}), title: chapter.title, summary: chapter.summary, pov: chapter.pov };
998
+ if (own)
999
+ frontmatter.ghostwriter = own;
1000
+ else if (before.ghostwriter)
1001
+ delete frontmatter.ghostwriter;
1002
+ const body = !existing || existing.body.trim() === oldBody ? `# ${chapter.title}\n\n${chapter.goal || chapter.summary || ""}` : existing.body;
1003
+ return renderMarkdown(frontmatter, body);
1004
+ });
1005
+ }
1006
+ /**
1007
+ * A chapter whose entry of the outline the author changed, or deleted, since it was planned, and of which nothing is written yet. It
1008
+ * is planned again following the new entry (its title, summary, purpose, events and ghostwriter; its scenes are planned again), or,
1009
+ * without an entry, it leaves the plan, and the book when its folder is empty. No other chapter is touched, and none is renumbered.
1010
+ */
1011
+ async function runReplan(ctx) {
1012
+ const plan = ctx.state.plan;
1013
+ const chapter = chapterOf(ctx);
1014
+ const italian = isItalian(ctx.language);
1015
+ const number = chapter.number;
1016
+ const entry = await outlineOf(ctx).chapter(number);
1017
+ const folder = ctx.snapshot.chapters.find((info) => info.slug === chapter.slug);
1018
+ const stubPath = chapterFilePath(chapter.slug);
1019
+ const stubHash = ctx.snapshot.files.get(stubPath);
1020
+ const written = Boolean(folder?.paragraphs.length);
1021
+ const changes = [];
1022
+ if (!entry) {
1023
+ plan.chapters = plan.chapters.filter((item) => item !== chapter);
1024
+ plan.removedChapters = [...new Set([...(plan.removedChapters ?? []), number])].sort((left, right) => left - right);
1025
+ if (stubHash && !written)
1026
+ changes.push({ path: stubPath, content: null, expectedHash: stubHash });
1027
+ ctx.insight("warning", italian ? `Il capitolo ${number} non è più nella Scaletta: esce dal piano` : `Chapter ${number} is no longer in the outline: it leaves the plan`, italian ? "I capitoli successivi mantengono il loro numero: rinumera la Scaletta se vuoi chiudere il vuoto." : "The following chapters keep their number: renumber the outline if you want to close the gap.", { code: "outlineRemoved", chapterNumber: number });
1028
+ changes.push(await planFileChange(ctx));
1029
+ return { changes: compact(changes), summary: italian ? `Il capitolo ${number} è uscito dal piano: la sua voce della Scaletta è stata cancellata.` : `Chapter ${number} left the plan: its entry of the outline was deleted.` };
1030
+ }
1031
+ const [view, design, resume] = await Promise.all([authorOutline(ctx), readBody(ctx.store, STORY_DESIGN_FILE, 2500), storySoFar(ctx, number, 4000)]);
1032
+ const secretsPlan = ctx.state.concept.secrets.filter((secret) => secret.revealChapter).map((secret) => `- ${secret.title}: reveal in chapter ${secret.revealChapter}`).join("\n");
1033
+ const around = chapterLines(plan.chapters.filter((item) => item.number !== number), { around: number });
1034
+ const response = await ctx.ai({
1035
+ capability: AI_CAPABILITIES.writer,
1036
+ label: `autopilot:replan:${number}`,
1037
+ system: architectSystemPrompt(ctx.language),
1038
+ user: `${request([
1039
+ `The author changed the outline of chapter ${number}. Plan chapter ${number} again, numbered ${number} to ${number}, following the new entry (AUTHOR'S OUTLINE, CHAPTER ${number}): the same hypothetical title (refine it only if the entry has none) and the same events. Enrich it, never change it.`,
1040
+ "Keep it consistent with the other chapters, which do not change, and place the reveals the chapter has to hold.",
1041
+ authorRules(ctx),
1042
+ ])}\n\n${data([
1043
+ bookHeader(ctx),
1044
+ briefBlock(ctx),
1045
+ `AUTHOR'S OUTLINE, CHAPTER ${number} (the new entry, binding):\n${entryHeading(entry)}:\n${truncate(entry.body, OUTLINE_BATCH_CHARS) || "(no text)"}`,
1046
+ outlineBookSection(view),
1047
+ design ? `STORY DESIGN (excerpt):\n${design}` : "",
1048
+ `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
1049
+ secretsPlan ? `PLANNED REVEALS:\n${secretsPlan}` : "",
1050
+ around.text ? listSection("THE OTHER CHAPTERS OF THE PLAN", around) : "",
1051
+ resume ? `STORY SO FAR (before this chapter):\n${resume}` : "",
1052
+ `THE PLAN OF CHAPTER ${number} UNTIL NOW (replace it):\n${chapterPlanBlock(chapter)}`,
1053
+ `DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
1054
+ ])}`,
1055
+ json: PLAN_TOOL,
1056
+ maxOutputTokens: outputLimit(ctx, 3000),
1057
+ temperature: 0.7,
1058
+ });
1059
+ const output = requireStructuredFields(response.json, { chapters: "list" }, "The plan of the chapter");
1060
+ const proposal = asArray(output.chapters).map(asRecord).find((item) => asString(item.title) || asString(item.summary));
1061
+ if (!proposal)
1062
+ throw new AiReplyRejectedError(`The plan of chapter ${number} has no chapter: return chapter ${number} with its title, summary, goal, point of view, key events and reveals.`);
1063
+ const before = { title: chapter.title, goal: chapter.goal, summary: chapter.summary, ...(chapter.ghostwriter ? { ghostwriter: chapter.ghostwriter } : {}) };
1064
+ const title = entry.title ? clipText(entry.title, OUTLINE_TITLE_MAX_CHARS).trim() : asString(proposal.title) || chapter.title;
1065
+ const ghostwriter = outlineGhostwriter(ctx, entry);
1066
+ // A folder with somebody's text in it keeps its name; an empty one follows the new title, as a plan made again does.
1067
+ const slug = written ? chapter.slug : chapterSlug(number, title);
1068
+ if (slug !== chapter.slug && stubHash)
1069
+ changes.push({ path: stubPath, content: null, expectedHash: stubHash });
1070
+ Object.assign(chapter, {
1071
+ title,
1072
+ slug,
1073
+ summary: asString(proposal.summary),
1074
+ goal: asString(proposal.goal),
1075
+ pov: asStringList(proposal.pov, 6),
1076
+ keyEvents: asStringList(proposal.keyEvents, 12),
1077
+ reveals: asStringList(proposal.reveals, 8),
1078
+ status: "planned",
1079
+ scenes: [],
1080
+ outlineDigest: entry.contentDigest,
1081
+ });
1082
+ if (ghostwriter)
1083
+ chapter.ghostwriter = ghostwriter;
1084
+ else
1085
+ delete chapter.ghostwriter;
1086
+ delete chapter.skipReaders;
1087
+ changes.push(await chapterStubChange(ctx, chapter, before));
1088
+ changes.push(await planFileChange(ctx));
1089
+ ctx.insight("info", italian ? `Hai cambiato la Scaletta del capitolo ${number}: lo ripianifico` : `You changed the outline of chapter ${number}: I am planning it again`, `${number}. ${title}${chapter.summary ? ` — ${chapter.summary}` : ""}`, { code: "outlineChanged", chapterNumber: number });
1090
+ return { changes: compact(changes), summary: `${number}. ${title}${chapter.summary ? ` — ${truncate(chapter.summary, 240)}` : ""}` };
1091
+ }
804
1092
  // ─── Scenes and prose ───────────────────────────────────────────────────────
805
1093
  async function runScenes(ctx) {
806
1094
  const chapter = chapterOf(ctx);
@@ -854,7 +1142,25 @@ async function runScenes(ctx) {
854
1142
  }));
855
1143
  chapter.status = "writing";
856
1144
  ctx.insight("info", isItalian(ctx.language) ? `Capitolo ${chapter.number}: ${chapter.scenes.length} scene` : `Chapter ${chapter.number}: ${chapter.scenes.length} scenes`, chapter.scenes.map((scene) => scene.title).join(" · "));
857
- return { changes: compact([ensureChapterFile(ctx, chapter), await planFileChange(ctx)]), summary: chapter.scenes.map((scene) => `${scene.number}. ${scene.title}`).join("; ") };
1145
+ const ghostwriter = await outlineGhostwriterArrived(ctx, chapter);
1146
+ return { changes: compact([ensureChapterFile(ctx, chapter), ghostwriter, await planFileChange(ctx)]), summary: chapter.scenes.map((scene) => `${scene.number}. ${scene.title}`).join("; ") };
1147
+ }
1148
+ /**
1149
+ * The ghostwriter the outline names for a chapter that is starting, when it did not exist at the time of the plan and exists now
1150
+ * (the author created it after being told): the chapter takes it, and its `chapter.md` says it. Nothing else of the plan changes.
1151
+ */
1152
+ async function outlineGhostwriterArrived(ctx, chapter) {
1153
+ const entry = await outlineOf(ctx).chapter(chapter.number);
1154
+ const slug = entry?.ghostwriter;
1155
+ if (!entry || entry.unreadable || !slug || slug === chapter.ghostwriter || entry.contentDigest !== chapter.outlineDigest)
1156
+ return null;
1157
+ if (!isValidGhostwriterSlug(slug) || !ctx.snapshot.ghostwriterSlugs.includes(slug))
1158
+ return null;
1159
+ chapter.ghostwriter = slug;
1160
+ const path = chapterFilePath(chapter.slug);
1161
+ if (!ctx.snapshot.files.has(path) || slug === bookGhostwriter(ctx.snapshot))
1162
+ return null;
1163
+ return changeFor(ctx, path, (existing) => (existing ? renderMarkdown({ ...existing.frontmatter, ghostwriter: slug }, existing.body) : null));
858
1164
  }
859
1165
  /** One or two sentences on what a scene does, for continuity; `null` when the summary call fails. */
860
1166
  async function summarizeScene(ctx, chapter, scene, prose) {
@@ -1103,6 +1409,7 @@ async function runSpecialists(ctx) {
1103
1409
  const [ghostwriter, secrets] = await Promise.all([ghostwriterOf(ctx, info), secretRules(ctx.store, ctx.snapshot, chapter.number)]);
1104
1410
  const relevant = mentionedCanon(ctx.snapshot, text, 16);
1105
1411
  const previousChapters = chapterLines(ctx.state.plan.chapters.filter((entry) => entry.number < chapter.number), { around: chapter.number });
1412
+ const style = evaluationStyleOf(ctx, "specialists");
1106
1413
  const response = await ctx.ai({
1107
1414
  capability: AI_CAPABILITIES.specialist,
1108
1415
  label: `autopilot:specialists:${chapter.number}`,
@@ -1110,10 +1417,12 @@ async function runSpecialists(ctx) {
1110
1417
  user: `${request([
1111
1418
  `Review chapter ${chapter.number} «${chapter.title}» (review round ${review.round}). Return at most 12 findings, most important first, using the scene numbers of the markers.`,
1112
1419
  review.previousFixes.length ? `These fixes were applied after the previous round: verify them and report only remaining or new real problems.\n${bulletList(review.previousFixes)}` : "",
1420
+ style.rule,
1113
1421
  authorRules(ctx, false),
1114
1422
  ])}\n\n${data([
1115
1423
  bookHeader(ctx),
1116
1424
  `GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
1425
+ style.block,
1117
1426
  previousChapters.text ? listSection("PREVIOUS CHAPTERS", previousChapters) : "",
1118
1427
  chapterPlanBlock(chapter),
1119
1428
  `SCENE PLANS:\n${chapter.scenes.map((scene) => `- Scene ${scene.number} «${scene.title}»: ${scene.goal}`).join("\n")}`,
@@ -1178,6 +1487,8 @@ async function runDirectorReview(ctx) {
1178
1487
  const maxRounds = ctx.director.maxReviewRounds;
1179
1488
  const last = review.round >= maxRounds;
1180
1489
  const perScene = sceneLimit(ctx, Math.max(3000, Math.floor(60000 / Math.max(1, source.paragraphs.length))));
1490
+ const style = evaluationStyleOf(ctx, "chapter");
1491
+ const authorNote = review.authorEdit ? startedReview(ctx.state)?.note : undefined;
1181
1492
  const response = await ctx.ai({
1182
1493
  capability: AI_CAPABILITIES.director,
1183
1494
  label: `autopilot:director-review:${chapter.number}`,
@@ -1186,13 +1497,18 @@ async function runDirectorReview(ctx) {
1186
1497
  `Decide on chapter ${chapter.number} «${chapter.title}» (review round ${review.round} of ${maxRounds}).`,
1187
1498
  "For EVERY finding decide exactly once: accept it with a precise, minimal remediation for the ghostwriter and its scene number, or reject it with the reason. Reject unfounded or unanchored findings, findings against the vision or the author's rules, and single-reader taste the intended audience would not share.",
1188
1499
  `Score the chapter from 1 to 10. Verdict "approve" when it deserves at least ${ctx.director.approvalScore}/10 and nothing critical remains; otherwise "revise".`,
1189
- last ? "This is the LAST review round: accepted fixes will be applied and the chapter closed without another review, so accept only what really matters." : "",
1500
+ style.rule,
1501
+ review.authorEdit
1502
+ ? "The author changed this chapter after it was approved: judge the chapter as it is now. The author's text stays as it is: no fix will be applied and there is no other round, so your accepted fixes are advice for the author."
1503
+ : last ? "This is the LAST review round: accepted fixes will be applied and the chapter closed without another review, so accept only what really matters." : "",
1504
+ authorNote ? `The author's note on the change: «${authorNote}»` : "",
1190
1505
  "Add standing guidance for the next chapters when this chapter taught you something.",
1191
1506
  ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical matter you must not settle alone.",
1192
1507
  authorRules(ctx, false),
1193
1508
  ])}\n\n${data([
1194
1509
  bookHeader(ctx),
1195
1510
  directorGuidance(ctx),
1511
+ style.block,
1196
1512
  chapterPlanBlock(chapter),
1197
1513
  `SCENE PLANS:\n${chapter.scenes.map((scene) => `- Scene ${scene.number} «${scene.title}»: ${scene.goal}`).join("\n")}`,
1198
1514
  resume ? `STORY SO FAR (before this chapter):\n${resume}` : "",
@@ -1290,7 +1606,8 @@ async function runDirectorReview(ctx) {
1290
1606
  review.verdict = verdict;
1291
1607
  review.score = score;
1292
1608
  review.summary = summaryText;
1293
- review.repairQueue = [...new Set(accepted.map((decision) => decision.sceneNumber))].sort((left, right) => left - right);
1609
+ // The fixes of a review of the author's change are advice: the author's text is never rewritten for them.
1610
+ review.repairQueue = review.authorEdit ? [] : [...new Set(accepted.map((decision) => decision.sceneNumber))].sort((left, right) => left - right);
1294
1611
  // The readers read the chapter once, in the first round of its review: their average is in the record of that round and of no other. The verdict is the one the plan acts on.
1295
1612
  recordChapterRound(chapter, closedRound({ director: score, readers: review.history.length === 0 ? review.readerScores.map((entry) => entry.score) : undefined, verdict, accepted: accepted.length, rejected: rejected.length }));
1296
1613
  review.history = [...review.history, { round: review.round, verdict, score, accepted: accepted.length, rejected: rejected.length }];
@@ -1460,9 +1777,16 @@ async function runConsolidate(ctx) {
1460
1777
  }
1461
1778
  const stateChanges = asRecord(output.stateChanges);
1462
1779
  const changes = [];
1780
+ // The director approved it: the chapter is frozen as it was read for this closing, in the same commit. One the author wrote is frozen
1781
+ // only when the author froze it (it is closed again after a change was reviewed); who froze it does not change.
1782
+ const folder = ctx.snapshot.chapters.find((entry) => entry.slug === chapter.slug);
1783
+ const freezeBy = !chapter.imported ? (folder?.frozen?.by ?? "autopilot") : folder?.frozen?.by;
1784
+ const prefix = `chapters/${chapter.slug}/`;
1785
+ const scenes = source.paragraphs.map((paragraph) => ({ name: paragraph.path.startsWith(prefix) ? paragraph.path.slice(prefix.length) : paragraph.path.split("/").pop(), body: paragraph.body }));
1786
+ const record = (body) => (freezeBy ? { frozen: chapterFreezeRecord({ at: ctx.now().toISOString(), by: freezeBy, chapterBody: body, scenes }) } : {});
1463
1787
  changes.push(await changeFor(ctx, chapterFilePath(chapter.slug), (existing) => existing
1464
- ? renderMarkdown({ ...existing.frontmatter, summary }, existing.body)
1465
- : renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary, canon: "draft" }, `# ${chapter.title}`)));
1788
+ ? renderMarkdown({ ...existing.frontmatter, summary, ...record(existing.body) }, existing.body)
1789
+ : renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary, canon: "draft", ...record(`# ${chapter.title}`) }, `# ${chapter.title}`)));
1466
1790
  changes.push(await changeFor(ctx, chapterResumePath(chapter.slug), (existing) => renderMarkdown({
1467
1791
  ...(existing?.frontmatter ?? {}),
1468
1792
  type: "resume",
@@ -1530,32 +1854,105 @@ function revisionFocus(revision, written) {
1530
1854
  const named = /\b(?:chapters?|capitol[oi]|cap\.)\s*(\d{1,6})\b/i.exec(revision.instruction)?.[1] ?? otherChapterMention(revision.instruction);
1531
1855
  return named ? Number(named) : written.at(-1)?.number;
1532
1856
  }
1857
+ /** What the autopilot knew of a chapter, for the analysis of the impact of a change of it. */
1858
+ function chapterViewBlock(view) {
1859
+ if (!view)
1860
+ return "Not known.";
1861
+ return [
1862
+ `Title: ${view.title}`,
1863
+ view.summary ? `Summary: ${view.summary}` : "Summary: none.",
1864
+ view.keyEvents.length ? `Key events:\n${bulletList(view.keyEvents)}` : "",
1865
+ view.storySoFar ? `Story so far at its close:\n${view.storySoFar}` : "",
1866
+ ].filter(Boolean).join("\n");
1867
+ }
1868
+ /** The request of the impact of a revision that comes from a change (of a frozen chapter, or of the outline of a written one), and its data. */
1869
+ async function sourceImpactPrompt(ctx, revision, scenesList) {
1870
+ const source = revision.source;
1871
+ if (!source)
1872
+ return null;
1873
+ const number = source.chapterNumber;
1874
+ const chapter = ctx.state.plan?.chapters.find((entry) => entry.number === number);
1875
+ const title = quotedTitle(chapter?.title);
1876
+ const extra = revision.instruction.split("\n").slice(1).map((line) => line.trim()).filter(Boolean);
1877
+ const notes = [
1878
+ source.note ? `The author's note on the change: «${source.note}»` : "",
1879
+ extra.length ? `The author also asked: «${extra.join(" ")}»` : "",
1880
+ ];
1881
+ const listed = scenesList.note ? "Some chapters are listed without their scenes: a scene of such a chapter can still be chosen by its chapter and scene number." : "";
1882
+ if (revision.onlyChapter === number) {
1883
+ const entry = await outlineOf(ctx).chapter(number);
1884
+ return {
1885
+ lines: [
1886
+ `The author changed the outline entry of chapter ${number}${title}, which is already written. Decide which written scenes of chapter ${number} must be rewritten so that the chapter follows the new entry (AUTHOR'S OUTLINE, CHAPTER ${number}, in the data), in reading order, with a precise instruction for each.`,
1887
+ "Choose the minimum set: keep what already follows the entry. Only the scenes of this chapter can be chosen.",
1888
+ ...notes,
1889
+ listed,
1890
+ ],
1891
+ sections: [
1892
+ entry ? `AUTHOR'S OUTLINE, CHAPTER ${number} (the new entry, binding):\n${entryHeading(entry)}:\n${truncate(entry.body, OUTLINE_BATCH_CHARS) || "(no text)"}` : "",
1893
+ source.before ? `THE PLAN OF CHAPTER ${number} UNTIL NOW:\n${chapterViewBlock(source.before)}` : "",
1894
+ listSection(`WRITTEN SCENES OF CHAPTER ${number}`, scenesList),
1895
+ ],
1896
+ };
1897
+ }
1898
+ const changed = source.kind === "frozen"
1899
+ ? `The author changed chapter ${number}${title} after it was approved. The author's text stands: chapter ${number} is never rewritten.`
1900
+ : `Chapter ${number}${title} was rewritten to follow the author's new outline entry. It stands as it is now: it is never rewritten here.`;
1901
+ return {
1902
+ lines: [
1903
+ changed,
1904
+ `Compare what the book knew of chapter ${number} BEFORE the change with what it is AFTER it, and decide which written scenes of the LATER chapters must change to stay consistent with it, in reading order, with a precise instruction for each. Choose the minimum set; when nothing later depends on the change, return no target.`,
1905
+ ...notes,
1906
+ listed,
1907
+ ],
1908
+ sections: [
1909
+ `CHAPTER ${number} BEFORE THE CHANGE (what the book knew of it when it was frozen):\n${chapterViewBlock(source.before)}`,
1910
+ `CHAPTER ${number} AFTER THE CHANGE (its new closing):\n${chapterViewBlock(source.after)}`,
1911
+ listSection("WRITTEN SCENES OF THE LATER CHAPTERS", scenesList),
1912
+ ],
1913
+ };
1914
+ }
1915
+ function quotedTitle(title) {
1916
+ return title ? ` «${title}»` : "";
1917
+ }
1533
1918
  async function runImpact(ctx) {
1534
1919
  const revision = ctx.state.revision;
1535
1920
  const plan = ctx.state.plan;
1536
- const written = (plan?.chapters ?? []).flatMap((chapter) => {
1921
+ // A revision that comes from a change looks only where the change can reach: the later chapters, or the chapter rewritten to follow its
1922
+ // outline; one the autopilot decided by itself never rewrites a chapter the author wrote; and none rewrites a chapter whose own change of
1923
+ // the author's waits (its text is the author's until the author has decided about it).
1924
+ const authorEdited = revision.source ? new Set(frozenChanges(ctx.snapshot).map((change) => change.slug)) : new Set();
1925
+ const reachable = (chapter) => (revision.afterChapter === undefined || chapter.number > revision.afterChapter)
1926
+ && (revision.onlyChapter === undefined || chapter.number === revision.onlyChapter)
1927
+ && !(revision.source?.auto && chapter.imported)
1928
+ && (revision.onlyChapter === chapter.number || !authorEdited.has(chapter.slug));
1929
+ const written = (plan?.chapters ?? []).filter(reachable).flatMap((chapter) => {
1537
1930
  const scenes = chapter.scenes.filter((scene) => scene.status !== "planned" && scene.path);
1538
1931
  return scenes.length ? [{ number: chapter.number, chapter, scenes }] : [];
1539
1932
  });
1540
1933
  if (!written.length) {
1541
1934
  revision.targets = [];
1542
- return { changes: [], summary: "Nothing written yet: the instruction becomes a permanent rule." };
1935
+ return { changes: [], summary: revision.source ? "No written scene the change can reach." : "Nothing written yet: the instruction becomes a permanent rule." };
1543
1936
  }
1544
1937
  const design = await readBody(ctx.store, STORY_DESIGN_FILE, 3000);
1545
- const scenesList = layoutChapters(written, WRITTEN_SCENES, { around: revisionFocus(revision, written) });
1938
+ const focus = revision.afterChapter !== undefined ? written[0]?.number : revisionFocus(revision, written);
1939
+ const scenesList = layoutChapters(written, WRITTEN_SCENES, { around: focus });
1940
+ const fromChange = await sourceImpactPrompt(ctx, revision, scenesList);
1546
1941
  const response = await ctx.ai({
1547
1942
  capability: AI_CAPABILITIES.director,
1548
1943
  label: "autopilot:impact",
1549
1944
  system: directorSystemPrompt(ctx.director, ctx.language),
1550
- user: `${request([
1551
- `The author asked to revise what is already written: «${revision.instruction}».`,
1552
- "Decide which written scenes must change to honor it, in reading order, with a precise instruction for each. Choose the minimum set; include later scenes only when they depend on the change.",
1553
- scenesList.note ? "Some chapters are listed without their scenes: a scene of such a chapter can still be chosen by its chapter and scene number." : "",
1554
- ])}\n\n${data([
1555
- bookHeader(ctx),
1556
- design ? `STORY DESIGN:\n${design}` : "",
1557
- listSection("WRITTEN SCENES", scenesList),
1558
- ])}`,
1945
+ user: fromChange
1946
+ ? `${request(fromChange.lines)}\n\n${data([bookHeader(ctx), design ? `STORY DESIGN:\n${design}` : "", ...fromChange.sections])}`
1947
+ : `${request([
1948
+ `The author asked to revise what is already written: «${revision.instruction}».`,
1949
+ "Decide which written scenes must change to honor it, in reading order, with a precise instruction for each. Choose the minimum set; include later scenes only when they depend on the change.",
1950
+ scenesList.note ? "Some chapters are listed without their scenes: a scene of such a chapter can still be chosen by its chapter and scene number." : "",
1951
+ ])}\n\n${data([
1952
+ bookHeader(ctx),
1953
+ design ? `STORY DESIGN:\n${design}` : "",
1954
+ listSection("WRITTEN SCENES", scenesList),
1955
+ ])}`,
1559
1956
  json: IMPACT_TOOL,
1560
1957
  maxOutputTokens: outputLimit(ctx, 3000),
1561
1958
  });
@@ -1606,6 +2003,7 @@ async function runFinal(ctx) {
1606
2003
  now: ctx.now,
1607
2004
  source: "autopilot",
1608
2005
  instruction: "Every chapter has been approved: judge the arcs, the promises made to the reader, the open threads and the ending, and list what the author should still consider.",
2006
+ ...(ctx.evaluationStyle ? { evaluationStyle: ctx.evaluationStyle } : {}),
1609
2007
  });
1610
2008
  ctx.state.finalDone = true;
1611
2009
  const finalReview = normalizeFinalReview({ verdict: result.opinion.verdict === "approve" ? "approve" : "revise", score: result.opinion.score, text: result.opinion.summary, at: result.opinion.createdAt });
@@ -1617,12 +2015,57 @@ async function runFinal(ctx) {
1617
2015
  ctx.insight(result.opinion.verdict === "approve" ? "ok" : "warning", isItalian(ctx.language) ? `Giudizio finale del direttore: ${result.opinion.score}/10` : `Director's final judgement: ${result.opinion.score}/10`, result.opinion.summary);
1618
2016
  return { changes: compact([change]), summary: `${result.opinion.verdict} ${result.opinion.score}/10 — ${result.opinion.summary}` };
1619
2017
  }
2018
+ /**
2019
+ * Freezing without the model: the chapters an older engine approved (once, the first time a state that does not know frozen chapters
2020
+ * runs; never a chapter the author wrote), and the changes the author marked as reviewed through a decision that waited for a run
2021
+ * (frozen as they are, unless they changed again since: then they are asked about again).
2022
+ */
2023
+ async function runFreeze(ctx) {
2024
+ const at = ctx.now().toISOString();
2025
+ const italian = isItalian(ctx.language);
2026
+ const changes = [];
2027
+ const done = [];
2028
+ if (!ctx.state.frozenSince) {
2029
+ const legacy = legacyChapters(ctx.state, ctx.snapshot);
2030
+ for (const folder of legacy)
2031
+ changes.push(...freezeChapterChanges(ctx.snapshot, folder.slug, "autopilot", at));
2032
+ ctx.state.frozenSince = at;
2033
+ if (legacy.length) {
2034
+ done.push(italian ? `${legacy.length} capitoli approvati congelati` : `${legacy.length} approved chapters frozen`);
2035
+ ctx.insight("info", italian
2036
+ ? `${legacy.length === 1 ? "Il capitolo già approvato è congelato" : `I ${legacy.length} capitoli già approvati sono congelati`}: d'ora in poi una tua modifica viene notata`
2037
+ : `${legacy.length === 1 ? "The chapter already approved is frozen" : `The ${legacy.length} chapters already approved are frozen`}: from now on a change you make to them is noticed`, legacy.map((folder) => folder.slug).join(", "), { code: "frozenMigrated" });
2038
+ }
2039
+ }
2040
+ const pending = queuedMarkReviewed(ctx.state);
2041
+ if (pending.length) {
2042
+ const current = new Map(frozenChanges(ctx.snapshot).map((change) => [change.number, change]));
2043
+ const plan = ctx.state.plan?.chapters ?? [];
2044
+ for (const entry of pending) {
2045
+ const slug = plan.find((chapter) => chapter.number === entry.number)?.slug;
2046
+ const change = current.get(entry.number);
2047
+ if (slug && change && change.slug === slug && change.fingerprint === entry.fingerprint) {
2048
+ changes.push(...markReviewedChanges(ctx.snapshot, slug, at));
2049
+ done.push(italian ? `capitolo ${entry.number} segnato come rivisto` : `chapter ${entry.number} marked as reviewed`);
2050
+ ctx.insight("ok", italian ? `Capitolo ${entry.number} segnato come rivisto: congelato così com'è` : `Chapter ${entry.number} marked as reviewed: frozen as it is`, undefined, { code: "frozenReviewed", chapterNumber: entry.number });
2051
+ }
2052
+ }
2053
+ const ids = new Set(pending.map((entry) => entry.id));
2054
+ const left = (ctx.state.pendingReviews ?? []).filter((entry) => !ids.has(entry.id));
2055
+ if (left.length)
2056
+ ctx.state.pendingReviews = left;
2057
+ else
2058
+ delete ctx.state.pendingReviews;
2059
+ }
2060
+ return { changes, summary: done.join("; ") || (italian ? "Nulla da congelare." : "Nothing to freeze.") };
2061
+ }
1620
2062
  export const TASK_EXECUTORS = {
1621
2063
  concept: runConcept,
1622
2064
  "summarize-imported": runSummarizeImported,
1623
2065
  plan: runPlan,
1624
2066
  "plan-reader": runPlanReader,
1625
2067
  "plan-review": runPlanReview,
2068
+ replan: runReplan,
1626
2069
  scenes: runScenes,
1627
2070
  write: runWrite,
1628
2071
  reader: runReader,
@@ -1634,5 +2077,6 @@ export const TASK_EXECUTORS = {
1634
2077
  impact: runImpact,
1635
2078
  revise: runRevise,
1636
2079
  final: runFinal,
2080
+ freeze: runFreeze,
1637
2081
  };
1638
2082
  //# sourceMappingURL=tasks.js.map