narrarium-engine 0.0.0-stage → 0.1.0

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 (142) hide show
  1. package/README.md +104 -2
  2. package/dist/ai/config.d.ts +69 -0
  3. package/dist/ai/config.d.ts.map +1 -0
  4. package/dist/ai/config.js +100 -0
  5. package/dist/ai/config.js.map +1 -0
  6. package/dist/ai/fetch-client.d.ts +34 -0
  7. package/dist/ai/fetch-client.d.ts.map +1 -0
  8. package/dist/ai/fetch-client.js +322 -0
  9. package/dist/ai/fetch-client.js.map +1 -0
  10. package/dist/ai/router.d.ts +20 -0
  11. package/dist/ai/router.d.ts.map +1 -0
  12. package/dist/ai/router.js +95 -0
  13. package/dist/ai/router.js.map +1 -0
  14. package/dist/ai/structured.d.ts +59 -0
  15. package/dist/ai/structured.d.ts.map +1 -0
  16. package/dist/ai/structured.js +210 -0
  17. package/dist/ai/structured.js.map +1 -0
  18. package/dist/ai/token-limit.d.ts +5 -0
  19. package/dist/ai/token-limit.d.ts.map +1 -0
  20. package/dist/ai/token-limit.js +16 -0
  21. package/dist/ai/token-limit.js.map +1 -0
  22. package/dist/ai/types.d.ts +86 -0
  23. package/dist/ai/types.d.ts.map +1 -0
  24. package/dist/ai/types.js +46 -0
  25. package/dist/ai/types.js.map +1 -0
  26. package/dist/autopilot/planner.d.ts +56 -0
  27. package/dist/autopilot/planner.d.ts.map +1 -0
  28. package/dist/autopilot/planner.js +357 -0
  29. package/dist/autopilot/planner.js.map +1 -0
  30. package/dist/autopilot/prompts.d.ts +16 -0
  31. package/dist/autopilot/prompts.d.ts.map +1 -0
  32. package/dist/autopilot/prompts.js +284 -0
  33. package/dist/autopilot/prompts.js.map +1 -0
  34. package/dist/autopilot/runner.d.ts +92 -0
  35. package/dist/autopilot/runner.d.ts.map +1 -0
  36. package/dist/autopilot/runner.js +531 -0
  37. package/dist/autopilot/runner.js.map +1 -0
  38. package/dist/autopilot/session.d.ts +84 -0
  39. package/dist/autopilot/session.d.ts.map +1 -0
  40. package/dist/autopilot/session.js +248 -0
  41. package/dist/autopilot/session.js.map +1 -0
  42. package/dist/autopilot/state.d.ts +26 -0
  43. package/dist/autopilot/state.d.ts.map +1 -0
  44. package/dist/autopilot/state.js +398 -0
  45. package/dist/autopilot/state.js.map +1 -0
  46. package/dist/autopilot/story-so-far.d.ts +51 -0
  47. package/dist/autopilot/story-so-far.d.ts.map +1 -0
  48. package/dist/autopilot/story-so-far.js +137 -0
  49. package/dist/autopilot/story-so-far.js.map +1 -0
  50. package/dist/autopilot/tasks.d.ts +42 -0
  51. package/dist/autopilot/tasks.d.ts.map +1 -0
  52. package/dist/autopilot/tasks.js +1354 -0
  53. package/dist/autopilot/tasks.js.map +1 -0
  54. package/dist/autopilot/types.d.ts +373 -0
  55. package/dist/autopilot/types.d.ts.map +1 -0
  56. package/dist/autopilot/types.js +2 -0
  57. package/dist/autopilot/types.js.map +1 -0
  58. package/dist/book/context.d.ts +55 -0
  59. package/dist/book/context.d.ts.map +1 -0
  60. package/dist/book/context.js +163 -0
  61. package/dist/book/context.js.map +1 -0
  62. package/dist/book/paths.d.ts +57 -0
  63. package/dist/book/paths.d.ts.map +1 -0
  64. package/dist/book/paths.js +92 -0
  65. package/dist/book/paths.js.map +1 -0
  66. package/dist/book/snapshot.d.ts +69 -0
  67. package/dist/book/snapshot.d.ts.map +1 -0
  68. package/dist/book/snapshot.js +139 -0
  69. package/dist/book/snapshot.js.map +1 -0
  70. package/dist/book/store.d.ts +39 -0
  71. package/dist/book/store.d.ts.map +1 -0
  72. package/dist/book/store.js +28 -0
  73. package/dist/book/store.js.map +1 -0
  74. package/dist/director/opinion.d.ts +80 -0
  75. package/dist/director/opinion.d.ts.map +1 -0
  76. package/dist/director/opinion.js +302 -0
  77. package/dist/director/opinion.js.map +1 -0
  78. package/dist/index.d.ts +33 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +33 -0
  81. package/dist/index.js.map +1 -0
  82. package/dist/markdown/frontmatter.d.ts +17 -0
  83. package/dist/markdown/frontmatter.d.ts.map +1 -0
  84. package/dist/markdown/frontmatter.js +67 -0
  85. package/dist/markdown/frontmatter.js.map +1 -0
  86. package/dist/profiles/director.d.ts +35 -0
  87. package/dist/profiles/director.d.ts.map +1 -0
  88. package/dist/profiles/director.js +169 -0
  89. package/dist/profiles/director.js.map +1 -0
  90. package/dist/profiles/ghostwriter.d.ts +30 -0
  91. package/dist/profiles/ghostwriter.d.ts.map +1 -0
  92. package/dist/profiles/ghostwriter.js +140 -0
  93. package/dist/profiles/ghostwriter.js.map +1 -0
  94. package/dist/profiles/readers.d.ts +35 -0
  95. package/dist/profiles/readers.d.ts.map +1 -0
  96. package/dist/profiles/readers.js +189 -0
  97. package/dist/profiles/readers.js.map +1 -0
  98. package/dist/prompt/trust.d.ts +6 -0
  99. package/dist/prompt/trust.d.ts.map +1 -0
  100. package/dist/prompt/trust.js +12 -0
  101. package/dist/prompt/trust.js.map +1 -0
  102. package/dist/readers/evaluation.d.ts +26 -0
  103. package/dist/readers/evaluation.d.ts.map +1 -0
  104. package/dist/readers/evaluation.js +92 -0
  105. package/dist/readers/evaluation.js.map +1 -0
  106. package/dist/server/client.d.ts +90 -0
  107. package/dist/server/client.d.ts.map +1 -0
  108. package/dist/server/client.js +231 -0
  109. package/dist/server/client.js.map +1 -0
  110. package/dist/server/protocol.d.ts +225 -0
  111. package/dist/server/protocol.d.ts.map +1 -0
  112. package/dist/server/protocol.js +120 -0
  113. package/dist/server/protocol.js.map +1 -0
  114. package/dist/sync/files.d.ts +43 -0
  115. package/dist/sync/files.d.ts.map +1 -0
  116. package/dist/sync/files.js +88 -0
  117. package/dist/sync/files.js.map +1 -0
  118. package/dist/testing/index.d.ts +46 -0
  119. package/dist/testing/index.d.ts.map +1 -0
  120. package/dist/testing/index.js +202 -0
  121. package/dist/testing/index.js.map +1 -0
  122. package/dist/util/abort.d.ts +11 -0
  123. package/dist/util/abort.d.ts.map +1 -0
  124. package/dist/util/abort.js +53 -0
  125. package/dist/util/abort.js.map +1 -0
  126. package/dist/util/hash.d.ts +4 -0
  127. package/dist/util/hash.d.ts.map +1 -0
  128. package/dist/util/hash.js +11 -0
  129. package/dist/util/hash.js.map +1 -0
  130. package/dist/util/json.d.ts +20 -0
  131. package/dist/util/json.d.ts.map +1 -0
  132. package/dist/util/json.js +133 -0
  133. package/dist/util/json.js.map +1 -0
  134. package/dist/util/text.d.ts +17 -0
  135. package/dist/util/text.d.ts.map +1 -0
  136. package/dist/util/text.js +99 -0
  137. package/dist/util/text.js.map +1 -0
  138. package/dist/version.d.ts +3 -0
  139. package/dist/version.d.ts.map +1 -0
  140. package/dist/version.js +3 -0
  141. package/dist/version.js.map +1 -0
  142. package/package.json +51 -4
@@ -0,0 +1,1354 @@
1
+ import { requireStructuredFields, splitReasoningBlock } from "../ai/structured.js";
2
+ import { AI_CAPABILITIES, AiReplyRejectedError } from "../ai/types.js";
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, chapterFilePath, chapterResumePath, chapterSlug, directorOpinionPath, formatOrdinal, paragraphFilePath, paragraphId, paragraphSlug, readerEvaluationPath, readerSummaryPath, slugify, } from "../book/paths.js";
5
+ import { askDirector, directorSystemPrompt, renderDirectorOpinion } from "../director/opinion.js";
6
+ import { frontmatterString, parseMarkdown, renderMarkdown } from "../markdown/frontmatter.js";
7
+ import { readerPersonaSystemPrompt } from "../profiles/readers.js";
8
+ import { currentRequest, untrustedData } from "../prompt/trust.js";
9
+ import { READER_EVALUATION_TOOL, READER_SUMMARY_TOOL, chapterReaderText, normalizeReaderEvaluationOutput, renderReaderEvaluationBody, renderReaderSummaryBody, } from "../readers/evaluation.js";
10
+ import { sha256Hex } from "../util/hash.js";
11
+ import { asArray, asInteger, asNumber, asOneOf, asRecord, asString, asStringList } from "../util/json.js";
12
+ import { bulletList, countWords, isItalian, languageName, tail, truncate } from "../util/text.js";
13
+ import { importedChapters } from "./planner.js";
14
+ import { CHAPTER_REVIEW_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";
15
+ import { MAX_DIRECTOR_NOTES } from "./state.js";
16
+ import { STORY_SO_FAR_MAX_WORDS, STORY_SO_FAR_TARGET_WORDS, pruneStorySnapshots, readStorySoFar, renderTotalResumeBody, storySoFarExcess } from "./story-so-far.js";
17
+ // ─── Shared prompt fragments ────────────────────────────────────────────────
18
+ function bookHeader(ctx) {
19
+ const brief = ctx.state.brief;
20
+ return [
21
+ `BOOK: ${ctx.snapshot.book.title}`,
22
+ `LANGUAGE: ${languageName(ctx.language)}`,
23
+ brief.genre ? `GENRE: ${brief.genre}` : "",
24
+ brief.audience ? `AUDIENCE: ${brief.audience}` : "",
25
+ ].filter(Boolean).join("\n");
26
+ }
27
+ function briefBlock(ctx) {
28
+ const brief = ctx.state.brief;
29
+ return [
30
+ brief.idea ? `AUTHOR'S IDEA:\n${brief.idea}` : "",
31
+ brief.synopsis ? `AUTHOR'S CHAPTER-BY-CHAPTER SYNOPSIS (binding):\n${brief.synopsis}` : "",
32
+ `TARGET: ${brief.targetChapters} chapters, ${brief.scenesPerChapter} scenes per chapter, about ${brief.wordsPerScene} words per scene.`,
33
+ ].filter(Boolean).join("\n\n");
34
+ }
35
+ /** Author rules travel as instructions (they come from the author), never as repository data. */
36
+ function authorRules(ctx, includeNotes = true) {
37
+ const blocks = [];
38
+ if (ctx.state.constraints.length)
39
+ blocks.push(`Binding author rules:\n${bulletList(ctx.state.constraints)}`);
40
+ if (includeNotes && ctx.notes.length)
41
+ blocks.push(`Author notes for this step (they override your own choices):\n${bulletList(ctx.notes.map((note) => note.text))}`);
42
+ return blocks.join("\n\n");
43
+ }
44
+ function directorGuidance(ctx) {
45
+ return ctx.state.directorNotes.length ? `DIRECTOR'S STANDING GUIDANCE:\n${bulletList(ctx.state.directorNotes)}` : "";
46
+ }
47
+ function directorTaste(profile) {
48
+ return [
49
+ profile.priorities.length ? `Priorities:\n${bulletList(profile.priorities)}` : "",
50
+ profile.taste.length ? `Taste:\n${bulletList(profile.taste)}` : "",
51
+ profile.redLines.length ? `Red lines (never allowed):\n${bulletList(profile.redLines)}` : "",
52
+ profile.body.trim() ? `Vision:\n${truncate(profile.body.trim(), 2500)}` : "",
53
+ ].filter(Boolean).join("\n\n");
54
+ }
55
+ function planOutline(plan, options = {}) {
56
+ if (!plan?.chapters.length)
57
+ return "No plan yet.";
58
+ return plan.chapters
59
+ .filter((chapter) => options.upTo === undefined || chapter.number <= options.upTo)
60
+ .map((chapter) => {
61
+ const lines = [`${chapter.number}. ${chapter.title}${chapter.imported ? " (already written by the author)" : ""}${chapter.status === "done" ? " [done]" : ""}`];
62
+ if (chapter.summary)
63
+ lines.push(` ${chapter.summary}`);
64
+ if (chapter.reveals.length)
65
+ lines.push(` Reveals: ${chapter.reveals.join("; ")}`);
66
+ if (options.scenes)
67
+ for (const scene of chapter.scenes)
68
+ lines.push(` - Scene ${scene.number}: ${scene.title}${scene.summary ? ` — ${scene.summary}` : scene.goal ? ` — ${scene.goal}` : ""}`);
69
+ return lines.join("\n");
70
+ })
71
+ .join("\n");
72
+ }
73
+ function chapterPlanBlock(chapter) {
74
+ return [
75
+ `CHAPTER ${chapter.number}: ${chapter.title}`,
76
+ chapter.summary ? `Summary: ${chapter.summary}` : "",
77
+ chapter.goal ? `Purpose: ${chapter.goal}` : "",
78
+ chapter.pov.length ? `Point of view: ${chapter.pov.join(", ")}` : "",
79
+ chapter.keyEvents.length ? `Key events:\n${bulletList(chapter.keyEvents)}` : "",
80
+ chapter.reveals.length ? `Reveals:\n${bulletList(chapter.reveals)}` : "",
81
+ ].filter(Boolean).join("\n");
82
+ }
83
+ function scenePlanBlock(scene, label = "THIS SCENE") {
84
+ return [
85
+ `${label} — Scene ${scene.number}: ${scene.title}`,
86
+ scene.goal ? `Goal: ${scene.goal}` : "",
87
+ scene.pov ? `Point of view: ${scene.pov}` : "",
88
+ scene.location ? `Location: ${scene.location}` : "",
89
+ scene.characters.length ? `Characters: ${scene.characters.join(", ")}` : "",
90
+ scene.beats.length ? `Beats:\n${scene.beats.map((beat, index) => `${index + 1}. ${beat}`).join("\n")}` : "",
91
+ scene.summary ? `Planned outcome: ${scene.summary}` : "",
92
+ ].filter(Boolean).join("\n");
93
+ }
94
+ function data(sections) {
95
+ return untrustedData("repository_content", sections.filter((section) => Boolean(section && section.trim())).join("\n\n"));
96
+ }
97
+ function request(lines) {
98
+ return currentRequest(lines.filter((line) => Boolean(line && line.trim())).join("\n\n"));
99
+ }
100
+ const MAX_NOTE_CHARACTERS = 400;
101
+ /** Same note despite case, punctuation, quotes or spacing. */
102
+ function noteKey(note) {
103
+ return normalizeForMatch(note).replace(/[^\p{L}\p{N}]+/gu, " ").trim();
104
+ }
105
+ function mergeNotes(existing, incoming) {
106
+ const merged = [...existing];
107
+ const keys = new Set(merged.map(noteKey));
108
+ for (const raw of incoming) {
109
+ const note = truncate(raw.replace(/\s+/g, " ").trim(), MAX_NOTE_CHARACTERS);
110
+ const key = noteKey(note);
111
+ if (!key || keys.has(key))
112
+ continue;
113
+ keys.add(key);
114
+ merged.push(note);
115
+ }
116
+ return merged.slice(-MAX_DIRECTOR_NOTES);
117
+ }
118
+ function chapterOf(ctx) {
119
+ const chapter = ctx.state.plan?.chapters.find((entry) => entry.number === ctx.task.chapterNumber);
120
+ if (!chapter)
121
+ throw new Error(`Chapter ${ctx.task.chapterNumber} is not in the plan.`);
122
+ return chapter;
123
+ }
124
+ /** The director's verdict, tolerant of "approved"/"revision" variants; anything else rejects the reply. */
125
+ function verdictOf(value, subject) {
126
+ const text = asString(value).toLowerCase();
127
+ if (/^approv/.test(text))
128
+ return "approve";
129
+ if (/^(?:revis|rived|rivist|rework|rewrite|riscriv|reject|respin)/.test(text))
130
+ return "revise";
131
+ throw new AiReplyRejectedError(`${subject} was rejected: the field "verdict" must be "approve" or "revise".`);
132
+ }
133
+ /** The story before a chapter (the whole book without one), keeping its most recent part. */
134
+ function storySoFar(ctx, beforeChapter, max) {
135
+ return readStorySoFar(ctx.store, { chapters: ctx.state.plan?.chapters ?? importedChapters(ctx.snapshot), beforeChapter, max });
136
+ }
137
+ function sceneOf(chapter, number) {
138
+ const scene = chapter.scenes.find((entry) => entry.number === number);
139
+ if (!scene)
140
+ throw new Error(`Scene ${number} is not in the plan of chapter ${chapter.number}.`);
141
+ return scene;
142
+ }
143
+ function chapterFiles(ctx, chapter) {
144
+ return ctx.snapshot.chapters.find((entry) => entry.slug === chapter.slug)
145
+ ?? { slug: chapter.slug, number: chapter.number, title: chapter.title, pov: chapter.pov, path: chapterFilePath(chapter.slug), paragraphs: [] };
146
+ }
147
+ /** Strip wrappers models sometimes add around prose, including a leading reasoning block. */
148
+ export function cleanProse(text) {
149
+ let value = splitReasoningBlock((text ?? "").trim()).reply;
150
+ value = value.replace(/^```[a-z]*\s*\n?/i, "").replace(/\n?```\s*$/i, "").trim();
151
+ const lines = value.split(/\r?\n/);
152
+ while (lines.length && (/^#{1,6}\s/.test(lines[0].trim()) || /^(?:scene|scena)\s+\d+\s*[:.—-]/i.test(lines[0].trim()) || !lines[0].trim()))
153
+ lines.shift();
154
+ return lines.join("\n").trim();
155
+ }
156
+ /** Prose that cannot become a scene is rejected (and the step retried with the reason). */
157
+ function assertProse(text, minimumWords) {
158
+ if (!text.trim())
159
+ throw new AiReplyRejectedError("The model returned an empty scene.");
160
+ if (/^[{[]/.test(text.trim()))
161
+ throw new AiReplyRejectedError("The model returned data instead of prose.");
162
+ const words = countWords(text);
163
+ if (words < minimumWords)
164
+ throw new AiReplyRejectedError(`The scene is too short: ${words} words, at least ${minimumWords} expected.`);
165
+ }
166
+ function normalizeForMatch(text) {
167
+ return text.replace(/[«»“”„"]/g, "\"").replace(/[‘’`]/g, "'").replace(/[–—]/g, "-").replace(/\s+/g, " ").trim().toLowerCase();
168
+ }
169
+ async function changeFor(store, path, render) {
170
+ const file = await store.read(path);
171
+ const existing = file ? parseMarkdown(file.content) : null;
172
+ const content = render(existing ? { frontmatter: existing.frontmatter, body: existing.body } : null);
173
+ if (content === null)
174
+ return null;
175
+ if (file && file.content === content)
176
+ return null;
177
+ return { path, content, expectedHash: file?.hash ?? null };
178
+ }
179
+ function chapterDocument(chapter) {
180
+ 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 || ""}`);
181
+ }
182
+ function ensureChapterFile(ctx, chapter) {
183
+ const path = chapterFilePath(chapter.slug);
184
+ return ctx.snapshot.files.has(path) ? null : { path, content: chapterDocument(chapter), expectedHash: null };
185
+ }
186
+ /** Human-readable mirror of the plan, refreshed whenever the plan changes. */
187
+ export function renderPlanMarkdown(state, language) {
188
+ const italian = isItalian(language);
189
+ const plan = state.plan;
190
+ const status = (chapter) => {
191
+ const labels = italian
192
+ ? { planned: "pianificato", writing: "in scrittura", review: "in revisione", done: "approvato" }
193
+ : { planned: "planned", writing: "writing", review: "in review", done: "approved" };
194
+ return chapter.imported ? (italian ? "scritto dall'autore" : "written by the author") : labels[chapter.status];
195
+ };
196
+ const lines = [
197
+ `# ${italian ? "Piano dell'autopilot" : "Autopilot plan"}`,
198
+ "",
199
+ italian ? "File generato dall'autopilot: lo stato completo è in `autopilot/state.json`." : "Generated by the autopilot: the full state lives in `autopilot/state.json`.",
200
+ "",
201
+ `- ${italian ? "Approvato dal direttore" : "Approved by the director"}: ${plan?.approved ? (italian ? "sì" : "yes") : (italian ? "no" : "no")}`,
202
+ `- ${italian ? "Capitoli" : "Chapters"}: ${plan?.chapters.length ?? 0}`,
203
+ ];
204
+ for (const chapter of plan?.chapters ?? []) {
205
+ lines.push("", `## ${formatOrdinal(chapter.number)} ${chapter.title} (${status(chapter)}${chapter.score ? ` · ${chapter.score}/10` : ""})`, "");
206
+ if (chapter.summary)
207
+ lines.push(chapter.summary, "");
208
+ for (const scene of chapter.scenes)
209
+ lines.push(`- ${scene.number}. ${scene.title}${scene.summary ? ` — ${scene.summary}` : scene.goal ? ` — ${scene.goal}` : ""}`);
210
+ }
211
+ if (state.directorNotes.length)
212
+ lines.push("", `## ${italian ? "Indicazioni del direttore" : "Director's guidance"}`, "", bulletList(state.directorNotes));
213
+ return `${lines.join("\n").trim()}\n`;
214
+ }
215
+ async function planFileChange(ctx) {
216
+ const content = renderPlanMarkdown(ctx.state, ctx.language);
217
+ const file = await ctx.store.read(AUTOPILOT_PLAN_FILE);
218
+ if (file?.content === content)
219
+ return null;
220
+ return { path: AUTOPILOT_PLAN_FILE, content, expectedHash: file?.hash ?? null };
221
+ }
222
+ async function renderPlot(ctx) {
223
+ const plan = ctx.state.plan;
224
+ if (!plan)
225
+ return null;
226
+ const secrets = ctx.snapshot.canon.filter((entry) => entry.kind === "secret");
227
+ const sections = [];
228
+ for (const chapter of plan.chapters) {
229
+ const sceneLines = chapter.scenes.map((scene) => scene.summary || scene.goal).filter((line) => Boolean(line)).slice(0, 6);
230
+ const revealed = secrets.filter((secret) => secret.revealIn === `chapter:${chapter.slug}`).map((secret) => secret.name);
231
+ sections.push([
232
+ `## Chapter ${formatOrdinal(chapter.number)} ${chapter.title}`,
233
+ "",
234
+ chapter.summary || "Add chapter summary here.",
235
+ "",
236
+ "### What Happens",
237
+ "",
238
+ bulletList(sceneLines.length ? sceneLines : chapter.keyEvents.length ? chapter.keyEvents : ["Not written yet."]),
239
+ "",
240
+ "### Secrets Revealed",
241
+ "",
242
+ bulletList(revealed.length ? revealed : chapter.reveals.length ? chapter.reveals : ["No secret reveal is explicitly tied to this chapter yet."]),
243
+ "",
244
+ ].join("\n"));
245
+ }
246
+ const placed = new Set(plan.chapters.map((chapter) => `chapter:${chapter.slug}`));
247
+ const pending = secrets.filter((secret) => !secret.revealIn || !placed.has(secret.revealIn)).map((secret) => secret.name);
248
+ const body = [
249
+ "# Plot Overview",
250
+ "",
251
+ `- Book: ${ctx.snapshot.book.title}`,
252
+ `- Chapters tracked: ${plan.chapters.length}`,
253
+ `- Chapters approved: ${plan.chapters.filter((chapter) => chapter.status === "done").length}`,
254
+ `- Secrets tracked: ${secrets.length}`,
255
+ "",
256
+ "# Chapter Map",
257
+ "",
258
+ ...sections,
259
+ "# Pending Or Unplaced Reveals",
260
+ "",
261
+ bulletList(pending.length ? pending : ["All current secrets are tied to a chapter reveal, or no secrets exist yet."]),
262
+ ].join("\n");
263
+ return changeFor(ctx.store, PLOT_FILE, (existing) => renderMarkdown({ ...(existing?.frontmatter ?? {}), type: "plot", id: "plot:main", title: `${ctx.snapshot.book.title} Plot` }, body));
264
+ }
265
+ function compact(changes) {
266
+ return changes.filter((change) => Boolean(change));
267
+ }
268
+ // ─── Concept ────────────────────────────────────────────────────────────────
269
+ async function runConcept(ctx) {
270
+ const [bookBody, design, context] = await Promise.all([
271
+ readBody(ctx.store, BOOK_FILE, 2500),
272
+ readDocument(ctx.store, STORY_DESIGN_FILE),
273
+ readDocument(ctx.store, CONTEXT_FILE),
274
+ ]);
275
+ const response = await ctx.ai({
276
+ capability: AI_CAPABILITIES.writer,
277
+ label: "autopilot:concept",
278
+ system: architectSystemPrompt(ctx.language),
279
+ user: `${request([
280
+ `Design the foundation of this novel from the author's brief, for about ${ctx.state.brief.targetChapters} chapters.`,
281
+ "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.",
282
+ ctx.state.brief.synopsis ? "The author's chapter-by-chapter synopsis is binding: the concept must make it possible exactly as written." : "",
283
+ "Reuse the existing canon names instead of duplicating them.",
284
+ authorRules(ctx),
285
+ ])}\n\n${data([
286
+ bookHeader(ctx),
287
+ briefBlock(ctx),
288
+ bookBody ? `BOOK DESCRIPTION:\n${bookBody}` : "",
289
+ design?.document.body ? `CURRENT STORY DESIGN:\n${truncate(design.document.body, 4000)}` : "",
290
+ context?.document.body ? `CURRENT WORLD CONTEXT:\n${truncate(context.document.body, 3000)}` : "",
291
+ ctx.snapshot.canon.length ? `EXISTING CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true })}` : "",
292
+ `DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
293
+ ])}`,
294
+ json: CONCEPT_TOOL,
295
+ maxOutputTokens: 9000,
296
+ temperature: 0.8,
297
+ });
298
+ const output = requireStructuredFields(response.json, { storyDesign: "text" }, "The concept");
299
+ const storyDesign = asString(output.storyDesign);
300
+ const logline = asString(output.logline);
301
+ const changes = [];
302
+ changes.push({
303
+ path: STORY_DESIGN_FILE,
304
+ content: renderMarkdown(design?.document.frontmatter && Object.keys(design.document.frontmatter).length ? design.document.frontmatter : { type: "note", id: "note:story-design", title: "Story Design", scope: "story-design", bucket: "story-design" }, `${storyDesign.startsWith("#") ? "" : "# Story Design\n\n"}${logline && !storyDesign.includes(logline) ? `> ${logline}\n\n` : ""}${storyDesign}`),
305
+ expectedHash: design?.file.hash ?? null,
306
+ });
307
+ const contextText = asString(output.context);
308
+ if (contextText && (!context || isThinDocument(context.document.body))) {
309
+ changes.push({
310
+ path: CONTEXT_FILE,
311
+ content: renderMarkdown(context?.document.frontmatter && Object.keys(context.document.frontmatter).length ? context.document.frontmatter : { type: "context", id: "context:book", title: "Book Context" }, contextText),
312
+ expectedHash: context?.file.hash ?? null,
313
+ });
314
+ }
315
+ const created = new Set();
316
+ const known = ctx.snapshot.canon.map((entry) => ({ kind: entry.kind, slug: entry.slug, names: [entry.name, ...entry.aliases] }));
317
+ const counts = { character: 0, other: 0 };
318
+ const create = (kind, name, frontmatter, body) => {
319
+ // An entity that already exists under this name, an alias or (for characters) a first name is reused, never duplicated.
320
+ const existing = known.find((entry) => entry.kind === kind && sameCanonEntity(kind, name, entry.names));
321
+ if (existing)
322
+ return existing.slug;
323
+ const slug = slugify(name);
324
+ const path = canonPath(kind, slug);
325
+ if (!slug || created.has(path) || ctx.snapshot.files.has(path))
326
+ return slug || null;
327
+ created.add(path);
328
+ known.push({ kind, slug, names: [name] });
329
+ if (kind === "character")
330
+ counts.character += 1;
331
+ else
332
+ counts.other += 1;
333
+ const label = kind === "secret" ? { title: name } : { name };
334
+ changes.push({ path, content: renderMarkdown({ type: kind, id: `${kind}:${slug}`, ...label, ...frontmatter, canon: "draft" }, body), expectedHash: null });
335
+ return slug;
336
+ };
337
+ const characterSlug = (name) => known.find((entry) => entry.kind === "character" && sameCanonEntity("character", name, entry.names))?.slug ?? slugify(name);
338
+ const characters = asArray(output.characters).slice(0, 10).map(asRecord);
339
+ for (const character of characters) {
340
+ const name = asString(character.name);
341
+ if (!name)
342
+ continue;
343
+ create("character", name, {
344
+ role_tier: asOneOf(character.roleTier, ["main", "supporting", "secondary", "minor"], "supporting"),
345
+ story_role: asOneOf(character.storyRole, ["protagonist", "deuteragonist", "antagonist", "mentor", "ally", "love-interest", "foil", "comic-relief", "other"], "other"),
346
+ speaking_style: asString(character.voice) || undefined,
347
+ function_in_book: truncate(asString(character.description), 300) || undefined,
348
+ arc: asString(character.arc) || undefined,
349
+ desires: asString(character.desire) ? [asString(character.desire)] : undefined,
350
+ fears: asString(character.fear) ? [asString(character.fear)] : undefined,
351
+ }, `# ${name}\n\n${asString(character.description)}`);
352
+ }
353
+ for (const location of asArray(output.locations).slice(0, 10).map(asRecord)) {
354
+ const name = asString(location.name);
355
+ if (name)
356
+ create("location", name, { atmosphere: asString(location.atmosphere) || undefined }, `# ${name}\n\n${asString(location.description)}`);
357
+ }
358
+ for (const faction of asArray(output.factions).slice(0, 6).map(asRecord)) {
359
+ const name = asString(faction.name);
360
+ if (name)
361
+ create("faction", name, { mission: asString(faction.mission) || undefined }, `# ${name}\n\n${asString(faction.description)}`);
362
+ }
363
+ const secrets = [];
364
+ for (const secret of asArray(output.secrets).slice(0, 8).map(asRecord)) {
365
+ const title = asString(secret.title);
366
+ if (!title)
367
+ continue;
368
+ const holders = asStringList(secret.holders, 10).map((holder) => `character:${characterSlug(holder)}`);
369
+ const slug = create("secret", title, { holders, stakes: asString(secret.stakes) || undefined, status: "hidden" }, `# ${title}\n\n${asString(secret.truth)}`) ?? slugify(title);
370
+ const revealChapter = asInteger(secret.revealChapter, 0, 0, 999);
371
+ secrets.push({ slug, title, revealChapter: revealChapter || undefined });
372
+ }
373
+ ctx.state.concept = { done: true, generated: true, secrets };
374
+ if (logline)
375
+ ctx.insight("ok", logline);
376
+ const summary = isItalian(ctx.language)
377
+ ? `${counts.character} personaggi, ${counts.other} altri elementi di canone, ${secrets.length} segreti.`
378
+ : `${counts.character} characters, ${counts.other} other canon entries, ${secrets.length} secrets.`;
379
+ return { changes: compact(changes), summary: logline ? `${logline} — ${summary}` : summary };
380
+ }
381
+ function normalizeName(name) {
382
+ return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
383
+ }
384
+ /**
385
+ * Whether a proposed canon name is an entity that already exists: same name or alias once
386
+ * normalized, or, for characters, a lone first name matching the first word of a fuller name
387
+ * ("Mara" and "Mara Venturi"; not "Mara Rossi" and "Mara Venturi", nor a lone surname).
388
+ */
389
+ export function sameCanonEntity(kind, name, existingNames) {
390
+ const candidate = normalizeName(name);
391
+ if (!candidate)
392
+ return false;
393
+ const names = existingNames.map(normalizeName).filter(Boolean);
394
+ if (names.includes(candidate))
395
+ return true;
396
+ if (kind !== "character")
397
+ return false;
398
+ const firstWord = (value) => value.split(" ")[0];
399
+ return names.some((existing) => (!candidate.includes(" ") && firstWord(existing) === candidate) || (!existing.includes(" ") && firstWord(candidate) === existing));
400
+ }
401
+ // ─── Plan ───────────────────────────────────────────────────────────────────
402
+ async function runPlan(ctx) {
403
+ const previous = ctx.state.plan;
404
+ // Chapters already in the book keep what the autopilot knew about them (the synopsis saved when they closed).
405
+ const imported = importedChapters(ctx.snapshot).map((chapter) => {
406
+ const known = previous?.chapters.find((entry) => entry.slug === chapter.slug);
407
+ return known?.storySoFarAtClose ? { ...chapter, storySoFarAtClose: known.storySoFarAtClose, ...(known.score !== undefined ? { score: known.score } : {}) } : chapter;
408
+ });
409
+ const startNumber = imported.length ? Math.max(...imported.map((chapter) => chapter.number)) + 1 : 1;
410
+ const count = Math.max(1, ctx.state.brief.targetChapters - imported.length);
411
+ const [design, context, resume] = await Promise.all([
412
+ readBody(ctx.store, STORY_DESIGN_FILE, 6000),
413
+ readBody(ctx.store, CONTEXT_FILE, 2500),
414
+ readStorySoFar(ctx.store, { chapters: imported, beforeChapter: startNumber, max: 4000 }),
415
+ ]);
416
+ const revising = Boolean(previous && previous.revisionNotes.length);
417
+ const secretsPlan = ctx.state.concept.secrets.filter((secret) => secret.revealChapter).map((secret) => `- ${secret.title}: reveal in chapter ${secret.revealChapter}`).join("\n");
418
+ const response = await ctx.ai({
419
+ capability: AI_CAPABILITIES.writer,
420
+ label: "autopilot:plan",
421
+ system: architectSystemPrompt(ctx.language),
422
+ user: `${request([
423
+ revising
424
+ ? `Revise the chapter plan (chapters ${startNumber}-${startNumber + count - 1}) applying the director's changes:\n${bulletList(previous.revisionNotes)}`
425
+ : `Plan the next ${count} chapters of the novel, numbered ${startNumber} to ${startNumber + count - 1}.`,
426
+ ctx.state.brief.synopsis ? "Follow the author's chapter-by-chapter synopsis exactly: same chapters, same order, same events. Enrich, never change." : "",
427
+ imported.length ? `Chapters 1-${startNumber - 1} are already written by the author: continue from them without changing them.` : "",
428
+ "Every chapter must change something and raise the stakes; place every secret reveal in a specific chapter; vary the shape of chapters.",
429
+ authorRules(ctx),
430
+ ])}\n\n${data([
431
+ bookHeader(ctx),
432
+ briefBlock(ctx),
433
+ design ? `STORY DESIGN:\n${design}` : "",
434
+ context ? `WORLD CONTEXT:\n${context}` : "",
435
+ `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
436
+ secretsPlan ? `PLANNED REVEALS:\n${secretsPlan}` : "",
437
+ imported.length ? `CHAPTERS ALREADY WRITTEN:\n${imported.map((chapter) => `${chapter.number}. ${chapter.title}${chapter.summary ? ` — ${chapter.summary}` : ""}`).join("\n")}` : "",
438
+ resume ? `STORY SO FAR (before chapter ${startNumber}):\n${resume}` : "",
439
+ revising ? `CURRENT PLAN:\n${planOutline(previous)}` : "",
440
+ `DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
441
+ ])}`,
442
+ json: PLAN_TOOL,
443
+ maxOutputTokens: 9000,
444
+ temperature: 0.7,
445
+ });
446
+ const output = requireStructuredFields(response.json, { chapters: "list" }, "The chapter plan");
447
+ const proposed = asArray(output.chapters).map(asRecord).filter((chapter) => asString(chapter.title)).slice(0, count);
448
+ if (proposed.length < count)
449
+ throw new AiReplyRejectedError(`The chapter plan has ${proposed.length} chapters with a title, but ${count} were requested (chapters ${startNumber}-${startNumber + count - 1}).`);
450
+ const planned = proposed.map((chapter, index) => {
451
+ const number = startNumber + index;
452
+ const title = asString(chapter.title);
453
+ return {
454
+ number,
455
+ title,
456
+ slug: chapterSlug(number, title),
457
+ summary: asString(chapter.summary),
458
+ goal: asString(chapter.goal),
459
+ pov: asStringList(chapter.pov, 6),
460
+ keyEvents: asStringList(chapter.keyEvents, 12),
461
+ reveals: asStringList(chapter.reveals, 8),
462
+ status: "planned",
463
+ scenes: [],
464
+ };
465
+ });
466
+ const changes = [];
467
+ if (previous) {
468
+ const keep = new Set(planned.map((chapter) => chapter.slug));
469
+ for (const old of previous.chapters) {
470
+ if (old.imported || keep.has(old.slug))
471
+ continue;
472
+ const files = ctx.snapshot.chapters.find((chapter) => chapter.slug === old.slug);
473
+ const hash = ctx.snapshot.files.get(chapterFilePath(old.slug));
474
+ if (hash && (!files || files.paragraphs.length === 0))
475
+ changes.push({ path: chapterFilePath(old.slug), content: null, expectedHash: hash });
476
+ }
477
+ }
478
+ ctx.state.plan = {
479
+ chapters: [...imported, ...planned],
480
+ approved: false,
481
+ rounds: previous?.rounds ?? 0,
482
+ revisionNotes: [],
483
+ readerReactions: previous?.readerReactions ?? [],
484
+ readersDone: previous?.readersDone ?? false,
485
+ awaitingAuthor: false,
486
+ };
487
+ changes.push(await planFileChange(ctx));
488
+ ctx.insight("info", isItalian(ctx.language) ? `${planned.length} capitoli pianificati` : `${planned.length} chapters planned`, planned.slice(0, 8).map((chapter) => `${chapter.number}. ${chapter.title}`).join(" · "));
489
+ return {
490
+ changes: compact(changes),
491
+ summary: planned.map((chapter) => `${chapter.number}. ${chapter.title}`).join("; "),
492
+ };
493
+ }
494
+ async function runPlanReader(ctx) {
495
+ const plan = ctx.state.plan;
496
+ const reader = ctx.readerPanel.find((entry) => entry.slug === ctx.task.reader);
497
+ if (!reader) {
498
+ plan.readersDone = true;
499
+ return { changes: [], summary: "Reader not available." };
500
+ }
501
+ const design = await readBody(ctx.store, STORY_DESIGN_FILE, 2500);
502
+ const response = await ctx.ai({
503
+ capability: AI_CAPABILITIES.reader,
504
+ label: `autopilot:plan-reader:${reader.slug}`,
505
+ system: `${readerPersonaSystemPrompt(reader, languageName(ctx.language), "brief")}\n\nYou are reading the pitch and the chapter plan of a novel that is not written yet. React honestly as this reader would.`,
506
+ user: `${request(["React as this reader: would you read this book? What excites you, what worries you, what would you wish for?"])}\n\n${data([
507
+ bookHeader(ctx),
508
+ ctx.state.brief.idea ? `PITCH:\n${ctx.state.brief.idea}` : "",
509
+ design ? `PREMISE:\n${design}` : "",
510
+ `CHAPTER PLAN:\n${planOutline(plan)}`,
511
+ ])}`,
512
+ json: PLAN_REACTION_TOOL,
513
+ maxOutputTokens: 1500,
514
+ });
515
+ const output = requireStructuredFields(response.json, { interest: "number" }, "The reader's reaction");
516
+ const reaction = {
517
+ slug: reader.slug,
518
+ name: reader.name,
519
+ interest: Math.round(asNumber(output.interest, 5, 1, 10)),
520
+ reaction: asString(output.reaction),
521
+ concerns: asStringList(output.concerns, 8),
522
+ wishes: asStringList(output.wishes, 8),
523
+ };
524
+ plan.readerReactions = [...plan.readerReactions.filter((entry) => entry.slug !== reader.slug), reaction];
525
+ ctx.insight(reaction.interest >= 7 ? "ok" : reaction.interest >= 5 ? "info" : "warning", `${reader.name}: ${reaction.interest}/10`, reaction.reaction);
526
+ return { changes: [], summary: `${reaction.interest}/10 — ${truncate(reaction.reaction, 240)}` };
527
+ }
528
+ async function runPlanReview(ctx) {
529
+ const plan = ctx.state.plan;
530
+ const design = await readBody(ctx.store, STORY_DESIGN_FILE, 5000);
531
+ const lastRound = plan.rounds >= 2;
532
+ const response = await ctx.ai({
533
+ capability: AI_CAPABILITIES.director,
534
+ label: "autopilot:plan-review",
535
+ system: directorSystemPrompt(ctx.director, ctx.language),
536
+ user: `${request([
537
+ `Review the concept and the chapter plan before any prose is written (review ${plan.rounds + 1}).`,
538
+ "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.",
539
+ lastRound ? "This is the final plan review: approve it and turn anything still imperfect into standing guidance." : "",
540
+ 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.",
541
+ authorRules(ctx, false),
542
+ ])}\n\n${data([
543
+ bookHeader(ctx),
544
+ briefBlock(ctx),
545
+ design ? `STORY DESIGN:\n${design}` : "",
546
+ `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
547
+ `CHAPTER PLAN:\n${planOutline(plan)}`,
548
+ plan.readerReactions.length
549
+ ? `SIMULATED READERS:\n${plan.readerReactions.map((reaction) => `- ${reaction.name} (weight ${ctx.director.readerWeights[reaction.slug] ?? 1}): ${reaction.interest}/10 — ${reaction.reaction}${reaction.concerns.length ? ` Concerns: ${reaction.concerns.join("; ")}.` : ""}${reaction.wishes.length ? ` Wishes: ${reaction.wishes.join("; ")}.` : ""}`).join("\n")}`
550
+ : "",
551
+ ])}`,
552
+ json: PLAN_REVIEW_TOOL,
553
+ maxOutputTokens: 4000,
554
+ });
555
+ // Without a verdict the plan is never approved by default.
556
+ const output = requireStructuredFields(response.json, { verdict: "text" }, "The director's plan review");
557
+ const verdict = verdictOf(output.verdict, "The director's plan review");
558
+ const score = Math.round(asNumber(output.score, 7, 1, 10));
559
+ const summaryText = asString(output.summary);
560
+ const changesRequested = asArray(output.changes).map(asRecord)
561
+ .map((change) => {
562
+ const instruction = asString(change.instruction);
563
+ const chapterNumber = asInteger(change.chapterNumber, 0, 0, 999);
564
+ return instruction ? `${chapterNumber ? `Chapter ${chapterNumber}: ` : ""}${instruction}` : "";
565
+ })
566
+ .filter(Boolean);
567
+ const guidance = asStringList(output.guidance, 10);
568
+ const changes = [];
569
+ const approved = verdict === "approve" || lastRound || changesRequested.length === 0;
570
+ if (!approved) {
571
+ plan.rounds += 1;
572
+ plan.revisionNotes = changesRequested;
573
+ 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(" · "));
574
+ }
575
+ else {
576
+ plan.approved = true;
577
+ plan.revisionNotes = [];
578
+ plan.awaitingAuthor = ctx.state.options.pauseAfterPlan || ctx.director.autonomy === "ask-always";
579
+ ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, [...guidance, ...(lastRound ? changesRequested : [])]);
580
+ for (const chapter of plan.chapters)
581
+ if (!chapter.imported)
582
+ changes.push(ensureChapterFile(ctx, chapter));
583
+ for (const secret of ctx.state.concept.secrets) {
584
+ const chapter = plan.chapters.find((entry) => entry.number === secret.revealChapter);
585
+ const path = canonPath("secret", secret.slug);
586
+ if (!chapter || !ctx.snapshot.files.has(path))
587
+ continue;
588
+ changes.push(await changeFor(ctx.store, path, (existing) => {
589
+ if (!existing || frontmatterString(existing.frontmatter, "reveal_in"))
590
+ return null;
591
+ return renderMarkdown({ ...existing.frontmatter, reveal_in: `chapter:${chapter.slug}`, known_from: `chapter:${chapter.slug}` }, existing.body);
592
+ }));
593
+ }
594
+ ctx.insight("ok", isItalian(ctx.language) ? `Piano approvato dal direttore (${score}/10)` : `Plan approved by the director (${score}/10)`, summaryText);
595
+ }
596
+ const question = asRecord(output.questionForAuthor);
597
+ if (ctx.director.autonomy !== "full" && asString(question.question)) {
598
+ ctx.state.question = {
599
+ id: `question-${ctx.now().getTime()}`,
600
+ kind: "director",
601
+ question: asString(question.question),
602
+ context: summaryText,
603
+ options: asStringList(question.options, 5),
604
+ askedAt: ctx.now().toISOString(),
605
+ };
606
+ }
607
+ changes.push(await planFileChange(ctx));
608
+ return { changes: compact(changes), summary: `${approved ? "approve" : "revise"} ${score}/10 — ${summaryText}` };
609
+ }
610
+ // ─── Scenes and prose ───────────────────────────────────────────────────────
611
+ async function runScenes(ctx) {
612
+ const chapter = chapterOf(ctx);
613
+ const plan = ctx.state.plan;
614
+ const previous = plan.chapters.find((entry) => entry.number === chapter.number - 1);
615
+ const next = plan.chapters.find((entry) => entry.number === chapter.number + 1);
616
+ const target = ctx.state.brief.scenesPerChapter;
617
+ const [resume, design, secrets] = await Promise.all([
618
+ storySoFar(ctx, chapter.number, 5000),
619
+ readBody(ctx.store, STORY_DESIGN_FILE, 2500),
620
+ secretRules(ctx.store, ctx.snapshot, chapter.number),
621
+ ]);
622
+ const response = await ctx.ai({
623
+ capability: AI_CAPABILITIES.writer,
624
+ label: `autopilot:scenes:${chapter.number}`,
625
+ system: architectSystemPrompt(ctx.language),
626
+ user: `${request([
627
+ `Break chapter ${chapter.number} «${chapter.title}» into ${target} scenes (one more or one fewer only if the chapter truly needs it).`,
628
+ "Each scene has a goal and a turn, and leads into the next. Respect the reveal rules and the director's guidance.",
629
+ authorRules(ctx),
630
+ ])}\n\n${data([
631
+ bookHeader(ctx),
632
+ directorGuidance(ctx),
633
+ chapterPlanBlock(chapter),
634
+ previous ? `PREVIOUS CHAPTER: ${previous.number}. ${previous.title}${previous.summary ? ` — ${previous.summary}` : ""}` : "",
635
+ next ? `NEXT CHAPTER (to set up): ${next.number}. ${next.title}${next.summary ? ` — ${next.summary}` : ""}` : "",
636
+ resume ? `STORY SO FAR (before this chapter):\n${resume}` : "",
637
+ design ? `STORY DESIGN (excerpt):\n${design}` : "",
638
+ `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: false }) || "-"}`,
639
+ secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
640
+ ])}`,
641
+ json: SCENES_TOOL,
642
+ maxOutputTokens: 5000,
643
+ temperature: 0.7,
644
+ });
645
+ const output = requireStructuredFields(response.json, { scenes: "list" }, "The scene plan");
646
+ const scenes = asArray(output.scenes).map(asRecord).filter((scene) => asString(scene.title)).slice(0, target + 2);
647
+ if (!scenes.length)
648
+ throw new AiReplyRejectedError("The scene plan has no scene with a title.");
649
+ chapter.scenes = scenes.map((scene, index) => ({
650
+ number: index + 1,
651
+ title: asString(scene.title),
652
+ goal: asString(scene.goal),
653
+ beats: asStringList(scene.beats, 12),
654
+ pov: asString(scene.pov) || undefined,
655
+ location: asString(scene.location) || undefined,
656
+ characters: asStringList(scene.characters, 12),
657
+ summary: asString(scene.summary) || undefined,
658
+ status: "planned",
659
+ revisions: 0,
660
+ }));
661
+ chapter.status = "writing";
662
+ 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(" · "));
663
+ return { changes: compact([ensureChapterFile(ctx, chapter), await planFileChange(ctx)]), summary: chapter.scenes.map((scene) => `${scene.number}. ${scene.title}`).join("; ") };
664
+ }
665
+ /** One or two sentences on what a scene does, for continuity; `null` when the summary call fails. */
666
+ async function summarizeScene(ctx, chapter, scene, prose) {
667
+ try {
668
+ const response = await ctx.ai({
669
+ capability: AI_CAPABILITIES.summary,
670
+ label: `autopilot:scene-summary:${chapter.number}.${scene.number}`,
671
+ system: continuitySystemPrompt(ctx.language),
672
+ user: `${request(["Summarize this scene in one or two sentences: what happens and what changes."])}\n\n${data([prose])}`,
673
+ json: SCENE_SUMMARY_TOOL,
674
+ maxOutputTokens: 400,
675
+ });
676
+ return asString(asRecord(response.json).summary) || null;
677
+ }
678
+ catch (error) {
679
+ if (ctx.signal.aborted)
680
+ throw error;
681
+ return null;
682
+ }
683
+ }
684
+ async function sceneNeighbors(ctx, chapter, scene) {
685
+ const previousScene = chapter.scenes.find((entry) => entry.number === scene.number - 1);
686
+ const nextScene = chapter.scenes.find((entry) => entry.number === scene.number + 1);
687
+ let previousEnding = "";
688
+ if (previousScene?.path) {
689
+ previousEnding = tail(await readBody(ctx.store, previousScene.path, 100000), 2400);
690
+ }
691
+ else if (scene.number === 1) {
692
+ const previousChapter = ctx.state.plan?.chapters.find((entry) => entry.number === chapter.number - 1);
693
+ const last = previousChapter?.scenes.filter((entry) => entry.path).at(-1);
694
+ if (last?.path)
695
+ previousEnding = tail(await readBody(ctx.store, last.path, 100000), 1500);
696
+ }
697
+ const nextOpening = nextScene?.path ? truncate(await readBody(ctx.store, nextScene.path, 100000), 900) : "";
698
+ const writtenSummaries = chapter.scenes
699
+ .filter((entry) => entry.number < scene.number && entry.status !== "planned")
700
+ .map((entry) => `- Scene ${entry.number} «${entry.title}»: ${entry.summary ?? entry.goal}`)
701
+ .join("\n");
702
+ return { previousEnding, nextOpening, writtenSummaries };
703
+ }
704
+ async function runWrite(ctx) {
705
+ const chapter = chapterOf(ctx);
706
+ const scene = sceneOf(chapter, ctx.task.sceneNumber);
707
+ const nextScene = chapter.scenes.find((entry) => entry.number === scene.number + 1);
708
+ const info = chapterFiles(ctx, chapter);
709
+ const [ghostwriter, context, resume, secrets, neighbors] = await Promise.all([
710
+ loadGhostwriter(ctx.store, ctx.snapshot, info),
711
+ readBody(ctx.store, CONTEXT_FILE, 2000),
712
+ storySoFar(ctx, chapter.number, 5000),
713
+ secretRules(ctx.store, ctx.snapshot, chapter.number),
714
+ sceneNeighbors(ctx, chapter, scene),
715
+ ]);
716
+ const relevant = mentionedCanon(ctx.snapshot, [scene.beats.join(" "), scene.goal, scene.summary ?? ""].join(" "), 12, [...scene.characters, scene.location ?? "", scene.pov ?? ""]);
717
+ const words = ctx.state.brief.wordsPerScene;
718
+ const response = await ctx.ai({
719
+ capability: AI_CAPABILITIES.writer,
720
+ label: `autopilot:write:${chapter.number}.${scene.number}`,
721
+ system: writerSystemPrompt(ctx.language),
722
+ user: `${request([
723
+ `Write scene ${scene.number} of chapter ${chapter.number} «${chapter.title}»: «${scene.title}». Target length: about ${words} words.`,
724
+ "Follow the beats in order, start in motion, and end on a turn that leads into the next scene.",
725
+ authorRules(ctx),
726
+ ])}\n\n${data([
727
+ bookHeader(ctx),
728
+ `GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
729
+ `DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
730
+ directorGuidance(ctx),
731
+ context ? `WORLD CONTEXT:\n${context}` : "",
732
+ resume ? `STORY SO FAR (before this chapter):\n${resume}` : "",
733
+ chapterPlanBlock(chapter),
734
+ neighbors.writtenSummaries ? `SCENES ALREADY WRITTEN IN THIS CHAPTER:\n${neighbors.writtenSummaries}` : "",
735
+ neighbors.previousEnding ? `PREVIOUS SCENE ENDING (continue seamlessly):\n${neighbors.previousEnding}` : "",
736
+ scenePlanBlock(scene),
737
+ nextScene ? scenePlanBlock(nextScene, "NEXT SCENE (set it up, do not write it)") : "",
738
+ relevant.length ? `RELEVANT CANON:\n${await canonDetails(ctx.store, relevant)}` : "",
739
+ secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
740
+ ])}`,
741
+ maxOutputTokens: Math.min(16000, Math.ceil(words * 2.4) + 800),
742
+ temperature: ghostwriter?.temperature ?? 0.8,
743
+ });
744
+ const prose = cleanProse(response.text);
745
+ assertProse(prose, Math.min(150, Math.floor(words * 0.25)));
746
+ const summary = await summarizeScene(ctx, chapter, scene, prose) ?? scene.summary ?? scene.goal;
747
+ const slug = paragraphSlug(scene.number, scene.title);
748
+ const path = paragraphFilePath(chapter.slug, slug);
749
+ const content = renderMarkdown({ type: "paragraph", id: paragraphId(chapter.slug, slug), chapter: `chapter:${chapter.slug}`, number: scene.number, title: scene.title, summary, viewpoint: scene.pov, canon: "draft" }, prose);
750
+ scene.status = "written";
751
+ scene.slug = slug;
752
+ scene.path = path;
753
+ scene.summary = summary;
754
+ scene.words = countWords(prose);
755
+ if (chapter.scenes.every((entry) => entry.status !== "planned"))
756
+ chapter.status = "review";
757
+ ctx.insight("ok", isItalian(ctx.language) ? `Scena ${chapter.number}.${scene.number} scritta: ${scene.words} parole` : `Scene ${chapter.number}.${scene.number} written: ${scene.words} words`, summary);
758
+ return {
759
+ changes: compact([{ path, content, expectedHash: ctx.snapshot.files.get(path) ?? null }, ensureChapterFile(ctx, chapter), await planFileChange(ctx)]),
760
+ summary: `${scene.words} words — ${summary}`,
761
+ };
762
+ }
763
+ // ─── Chapter review ─────────────────────────────────────────────────────────
764
+ async function chapterSource(ctx, chapter) {
765
+ const paragraphs = await loadChapterParagraphs(ctx.store, chapterFiles(ctx, chapter));
766
+ if (!paragraphs.length)
767
+ throw new Error(`Chapter ${chapter.number} has no written scenes.`);
768
+ const readerText = chapterReaderText(paragraphs.map((paragraph) => ({ title: paragraph.title, raw: paragraph.raw })));
769
+ return { paragraphs, readerText, sourceHash: await sha256Hex(readerText), sourceVersion: paragraphs.map((paragraph) => paragraph.hash).join(":") };
770
+ }
771
+ async function runReader(ctx) {
772
+ const chapter = chapterOf(ctx);
773
+ const review = ctx.state.review;
774
+ const slug = ctx.task.reader;
775
+ review.readersPending = review.readersPending.filter((entry) => entry !== slug);
776
+ const reader = ctx.readerPanel.find((entry) => entry.slug === slug);
777
+ if (!reader)
778
+ return { changes: [], summary: "Reader not available." };
779
+ const source = await chapterSource(ctx, chapter);
780
+ const resume = await storySoFar(ctx, chapter.number, 3000);
781
+ const response = await ctx.ai({
782
+ capability: AI_CAPABILITIES.reader,
783
+ label: `reader-evaluation:${reader.slug}`,
784
+ system: readerPersonaSystemPrompt(reader, languageName(ctx.language), "normal"),
785
+ user: `${currentRequest("Evaluate the target as the configured simulated reader.")}\n\n${untrustedData("repository_content", [
786
+ `TARGET: chapter — ${chapter.title}`,
787
+ resume ? `STORY SO FAR (before this chapter):\n${resume}` : "",
788
+ source.readerText,
789
+ ].filter(Boolean).join("\n\n"))}`,
790
+ json: READER_EVALUATION_TOOL,
791
+ maxOutputTokens: 2500,
792
+ });
793
+ const output = normalizeReaderEvaluationOutput(requireStructuredFields(response.json, { score: "number" }, "The reader evaluation"));
794
+ const path = readerEvaluationPath({ kind: "chapter", chapter: chapter.slug }, reader.slug);
795
+ const updatedAt = ctx.now().toISOString();
796
+ const change = await changeFor(ctx.store, path, (existing) => renderMarkdown({
797
+ ...(existing?.frontmatter ?? {}),
798
+ id: `reader-evaluation:chapter:${chapter.slug}:chapter:${reader.slug}`,
799
+ type: "readerEvaluation",
800
+ createdAt: frontmatterString(existing?.frontmatter ?? {}, "createdAt") ?? updatedAt,
801
+ updatedAt,
802
+ targetType: "chapter",
803
+ targetId: `chapter:${chapter.slug}`,
804
+ bookId: ctx.bookId,
805
+ chapterId: chapter.slug,
806
+ readerId: reader.id,
807
+ readerName: reader.name,
808
+ readerType: reader.readerType,
809
+ readerVersion: reader.version,
810
+ language: ctx.language,
811
+ evaluationDepth: "normal",
812
+ sourceContentHash: source.sourceHash,
813
+ sourceContentVersion: source.sourceVersion,
814
+ sourceUpdatedAt: updatedAt,
815
+ routerTask: "reader-evaluation",
816
+ model: response.model,
817
+ provider: response.provider,
818
+ integrationId: response.integrationId,
819
+ inputTokens: response.usage?.inputTokens,
820
+ outputTokens: response.usage?.outputTokens,
821
+ estimatedCost: response.cost,
822
+ finalCost: response.cost,
823
+ currency: response.currency,
824
+ score: output.score,
825
+ status: "completed",
826
+ generatedBy: "autopilot",
827
+ }, renderReaderEvaluationBody(output, ctx.language)));
828
+ review.readerScores = [...review.readerScores.filter((entry) => entry.slug !== slug), { slug, name: reader.name, score: output.score, mainProblem: output.mainProblem, prioritySuggestion: output.prioritySuggestion, path }];
829
+ ctx.insight(output.score >= 7 ? "ok" : output.score >= 5 ? "info" : "warning", `${reader.name}: ${output.score}/10`, output.mainProblem || output.generalImpression);
830
+ return { changes: compact([change]), summary: `${output.score}/10 — ${truncate(output.generalImpression, 220)}` };
831
+ }
832
+ async function runReadersSummary(ctx) {
833
+ const chapter = chapterOf(ctx);
834
+ const review = ctx.state.review;
835
+ const evaluations = await Promise.all(review.readerScores.map(async (score) => `READER: ${score.name}\nSCORE: ${score.score}\n${await readBody(ctx.store, score.path, 5000)}`));
836
+ const source = await chapterSource(ctx, chapter);
837
+ const response = await ctx.ai({
838
+ capability: AI_CAPABILITIES.readerSummary,
839
+ label: "reader-evaluation-summary",
840
+ system: `Compare the separate simulated-reader evaluations. Preserve disagreements rather than flattening them. Return the summary in ${languageName(ctx.language)}.`,
841
+ user: `${currentRequest("Summarize and compare these reader evaluations.")}\n\n${untrustedData("repository_content", evaluations.join("\n\n---\n\n"))}`,
842
+ json: READER_SUMMARY_TOOL,
843
+ maxOutputTokens: 2500,
844
+ });
845
+ const output = requireStructuredFields(response.json, { overallScore: "number" }, "The readers' summary");
846
+ const overall = Math.round(asNumber(output.overallScore, 6, 1, 10) * 10) / 10;
847
+ const path = readerSummaryPath({ kind: "chapter", chapter: chapter.slug });
848
+ const updatedAt = ctx.now().toISOString();
849
+ const change = await changeFor(ctx.store, path, (existing) => renderMarkdown({
850
+ ...(existing?.frontmatter ?? {}),
851
+ id: `reader-evaluation-summary:chapter:${chapter.slug}:chapter`,
852
+ type: "readerEvaluationSummary",
853
+ createdAt: frontmatterString(existing?.frontmatter ?? {}, "createdAt") ?? updatedAt,
854
+ updatedAt,
855
+ targetType: "chapter",
856
+ targetId: `chapter:${chapter.slug}`,
857
+ bookId: ctx.bookId,
858
+ chapterId: chapter.slug,
859
+ readerIds: review.readerScores.map((score) => ctx.readerPanel.find((reader) => reader.slug === score.slug)?.id ?? score.slug),
860
+ readerCount: review.readerScores.length,
861
+ language: ctx.language,
862
+ sourceContentHash: source.sourceHash,
863
+ sourceContentVersion: source.sourceVersion,
864
+ routerTask: "reader-evaluation-summary",
865
+ model: response.model,
866
+ provider: response.provider,
867
+ integrationId: response.integrationId,
868
+ inputTokens: response.usage?.inputTokens,
869
+ outputTokens: response.usage?.outputTokens,
870
+ finalCost: response.cost,
871
+ currency: response.currency,
872
+ score: overall,
873
+ status: "completed",
874
+ refs: review.readerScores.map((score) => `reader-evaluation:chapter:${chapter.slug}:chapter:${score.slug}`),
875
+ generatedBy: "autopilot",
876
+ }, renderReaderSummaryBody(output, ctx.language)));
877
+ const proposals = [...asStringList(output.revisionPriorities, 5), ...asStringList(output.recurringProblems, 3)]
878
+ .filter((entry, index, list) => list.findIndex((other) => normalizeForMatch(other) === normalizeForMatch(entry)) === index)
879
+ .slice(0, 6);
880
+ const findings = proposals.map((problem, index) => ({
881
+ id: `R${review.round}-${index + 1}`,
882
+ source: "reader",
883
+ category: "readers",
884
+ severity: "major",
885
+ anchored: false,
886
+ problem,
887
+ remediation: "",
888
+ }));
889
+ review.findings = [...review.findings.filter((finding) => finding.source !== "reader"), ...findings];
890
+ review.readersSummaryDone = true;
891
+ ctx.insight(overall >= 7 ? "ok" : overall >= 5 ? "info" : "warning", isItalian(ctx.language) ? `Lettori: ${overall}/10` : `Readers: ${overall}/10`, asStringList(output.consensus, 2).join(" · "));
892
+ return { changes: compact([change]), summary: `${overall}/10 — ${findings.length} proposals for the director` };
893
+ }
894
+ async function runSpecialists(ctx) {
895
+ const chapter = chapterOf(ctx);
896
+ const review = ctx.state.review;
897
+ const source = await chapterSource(ctx, chapter);
898
+ const info = chapterFiles(ctx, chapter);
899
+ const text = source.paragraphs.map((paragraph) => paragraph.body).join("\n");
900
+ const [ghostwriter, secrets] = await Promise.all([loadGhostwriter(ctx.store, ctx.snapshot, info), secretRules(ctx.store, ctx.snapshot, chapter.number)]);
901
+ const relevant = mentionedCanon(ctx.snapshot, text, 16);
902
+ const previousChapters = ctx.state.plan.chapters.filter((entry) => entry.number < chapter.number).map((entry) => `${entry.number}. ${entry.title}${entry.summary ? ` — ${entry.summary}` : ""}`).join("\n");
903
+ const response = await ctx.ai({
904
+ capability: AI_CAPABILITIES.specialist,
905
+ label: `autopilot:specialists:${chapter.number}`,
906
+ system: specialistsSystemPrompt(ctx.language),
907
+ user: `${request([
908
+ `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.`,
909
+ 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)}` : "",
910
+ authorRules(ctx, false),
911
+ ])}\n\n${data([
912
+ bookHeader(ctx),
913
+ `GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
914
+ previousChapters ? `PREVIOUS CHAPTERS:\n${previousChapters}` : "",
915
+ chapterPlanBlock(chapter),
916
+ `SCENE PLANS:\n${chapter.scenes.map((scene) => `- Scene ${scene.number} «${scene.title}»: ${scene.goal}`).join("\n")}`,
917
+ `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: false }) || "-"}`,
918
+ relevant.length ? `CANON DETAILS:\n${await canonDetails(ctx.store, relevant, 600)}` : "",
919
+ secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
920
+ `CHAPTER TEXT:\n${markedChapterText(source.paragraphs)}`,
921
+ ])}`,
922
+ json: FINDINGS_TOOL,
923
+ maxOutputTokens: 5000,
924
+ });
925
+ // A reply without the findings list is not "no problems": it is rejected.
926
+ const output = requireStructuredFields(response.json, { findings: "list" }, "The specialists' review");
927
+ const scenesByNumber = new Map(source.paragraphs.map((paragraph) => [paragraph.number, normalizeForMatch(paragraph.body)]));
928
+ const whole = normalizeForMatch(text);
929
+ const findings = asArray(output.findings).map(asRecord).slice(0, 12).map((finding, index) => {
930
+ const sceneNumber = asInteger(finding.sceneNumber, 0, 0, 999);
931
+ const evidence = asString(finding.evidence);
932
+ const needle = normalizeForMatch(evidence);
933
+ const anchored = needle.length >= 8 && ((scenesByNumber.get(sceneNumber) ?? whole).includes(needle) || whole.includes(needle));
934
+ return {
935
+ id: `S${review.round}-${index + 1}`,
936
+ source: "specialist",
937
+ category: asString(finding.category) || "other",
938
+ severity: asOneOf(finding.severity, ["critical", "major", "minor"], "minor"),
939
+ sceneNumber: sceneNumber || undefined,
940
+ evidence: evidence || undefined,
941
+ anchored,
942
+ problem: asString(finding.problem),
943
+ remediation: asString(finding.remediation),
944
+ };
945
+ }).filter((finding) => finding.problem);
946
+ review.findings = [...review.findings.filter((finding) => finding.source !== "specialist"), ...findings];
947
+ review.specialistsDone = true;
948
+ const critical = findings.filter((finding) => finding.severity === "critical").length;
949
+ const major = findings.filter((finding) => finding.severity === "major").length;
950
+ for (const finding of findings.filter((entry) => entry.severity !== "minor").slice(0, 4)) {
951
+ ctx.insight(finding.severity === "critical" ? "critical" : "warning", `${finding.category}${finding.sceneNumber ? ` · ${isItalian(ctx.language) ? "scena" : "scene"} ${finding.sceneNumber}` : ""}: ${truncate(finding.problem, 160)}`, finding.remediation);
952
+ }
953
+ if (!findings.length)
954
+ ctx.insight("ok", isItalian(ctx.language) ? "Gli specialisti non trovano problemi" : "The specialists found no problems");
955
+ return { changes: [], summary: `${findings.length} findings (${critical} critical, ${major} major) — ${asString(output.summary)}` };
956
+ }
957
+ function findingLine(finding) {
958
+ return [
959
+ `[${finding.id}] ${finding.source}${finding.reader ? ` (${finding.reader})` : ""} · ${finding.severity} · ${finding.category}${finding.sceneNumber ? ` · scene ${finding.sceneNumber}` : ""}${finding.source === "specialist" && !finding.anchored ? " · UNANCHORED (evidence not found verbatim)" : ""}`,
960
+ `Problem: ${finding.problem}`,
961
+ finding.evidence ? `Evidence: «${finding.evidence}»` : "",
962
+ finding.remediation ? `Proposed fix: ${finding.remediation}` : "",
963
+ ].filter(Boolean).join("\n");
964
+ }
965
+ async function runDirectorReview(ctx) {
966
+ const chapter = chapterOf(ctx);
967
+ const review = ctx.state.review;
968
+ const source = await chapterSource(ctx, chapter);
969
+ const [resume, secrets, readersSummary] = await Promise.all([
970
+ storySoFar(ctx, chapter.number, 4000),
971
+ secretRules(ctx.store, ctx.snapshot, chapter.number),
972
+ review.readerScores.length ? readBody(ctx.store, readerSummaryPath({ kind: "chapter", chapter: chapter.slug }), 2500) : Promise.resolve(""),
973
+ ]);
974
+ const maxRounds = ctx.director.maxReviewRounds;
975
+ const last = review.round >= maxRounds;
976
+ const perScene = Math.max(3000, Math.floor(60000 / Math.max(1, source.paragraphs.length)));
977
+ const response = await ctx.ai({
978
+ capability: AI_CAPABILITIES.director,
979
+ label: `autopilot:director-review:${chapter.number}`,
980
+ system: directorSystemPrompt(ctx.director, ctx.language),
981
+ user: `${request([
982
+ `Decide on chapter ${chapter.number} «${chapter.title}» (review round ${review.round} of ${maxRounds}).`,
983
+ "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.",
984
+ `Score the chapter from 1 to 10. Verdict "approve" when it deserves at least ${ctx.director.approvalScore}/10 and nothing critical remains; otherwise "revise".`,
985
+ 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." : "",
986
+ "Add standing guidance for the next chapters when this chapter taught you something.",
987
+ ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical matter you must not settle alone.",
988
+ authorRules(ctx, false),
989
+ ])}\n\n${data([
990
+ bookHeader(ctx),
991
+ directorGuidance(ctx),
992
+ chapterPlanBlock(chapter),
993
+ `SCENE PLANS:\n${chapter.scenes.map((scene) => `- Scene ${scene.number} «${scene.title}»: ${scene.goal}`).join("\n")}`,
994
+ resume ? `STORY SO FAR (before this chapter):\n${resume}` : "",
995
+ secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
996
+ review.readerScores.length
997
+ ? `SIMULATED READERS:\n${review.readerScores.map((score) => `- ${score.name} (weight ${ctx.director.readerWeights[score.slug] ?? 1}): ${score.score}/10. Main problem: ${score.mainProblem}. Priority: ${score.prioritySuggestion}`).join("\n")}`
998
+ : "",
999
+ readersSummary ? `READERS PANEL SUMMARY:\n${readersSummary}` : "",
1000
+ review.previousFixes.length ? `FIXES APPLIED AFTER THE PREVIOUS ROUND:\n${bulletList(review.previousFixes)}` : "",
1001
+ `FINDINGS TO DECIDE:\n${review.findings.length ? review.findings.map(findingLine).join("\n\n") : "None."}`,
1002
+ `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, perScene)}`,
1003
+ ])}`,
1004
+ json: CHAPTER_REVIEW_TOOL,
1005
+ maxOutputTokens: 6000,
1006
+ });
1007
+ const subject = "The director's chapter review";
1008
+ const output = requireStructuredFields(response.json, { verdict: "text" }, subject);
1009
+ const italian = isItalian(ctx.language);
1010
+ const rawDecisions = asArray(output.decisions).map(asRecord);
1011
+ const findingIds = review.findings.map((finding) => finding.id);
1012
+ // Findings without decisions must never turn into a silent "all rejected, approved".
1013
+ if (findingIds.length && !rawDecisions.length) {
1014
+ throw new AiReplyRejectedError(`${subject} was rejected: the field "decisions" is missing or empty, but ${findingIds.length} findings need a decision (${findingIds.slice(0, 12).join(", ")}).`);
1015
+ }
1016
+ const idKey = (value) => asString(value).replace(/^\[|\]$/g, "").trim().toUpperCase();
1017
+ const byId = new Map(rawDecisions.map((decision) => [idKey(decision.findingId), decision]));
1018
+ if (findingIds.length && !findingIds.some((id) => byId.has(idKey(id)))) {
1019
+ throw new AiReplyRejectedError(`${subject} was rejected: no decision refers to a finding id. Use the ids ${findingIds.slice(0, 12).join(", ")}.`);
1020
+ }
1021
+ const verdictGiven = verdictOf(output.verdict, subject);
1022
+ const writtenScenes = new Set(chapter.scenes.filter((scene) => scene.status !== "planned").map((scene) => scene.number));
1023
+ const undecided = [];
1024
+ const unusable = [];
1025
+ const decisions = review.findings.map((finding) => {
1026
+ const decision = byId.get(idKey(finding.id));
1027
+ if (!decision)
1028
+ undecided.push(finding.id);
1029
+ const action = decision ? asOneOf(decision.action, ["accept", "reject"], "reject") : "reject";
1030
+ const remediation = asString(decision?.remediation) || (action === "accept" ? finding.remediation : "");
1031
+ const sceneNumber = asInteger(decision?.sceneNumber, 0, 0, 999) || finding.sceneNumber;
1032
+ const applicable = action === "accept" && Boolean(remediation) && Boolean(sceneNumber) && writtenScenes.has(sceneNumber);
1033
+ if (action === "accept" && !applicable)
1034
+ unusable.push(finding.id);
1035
+ return {
1036
+ findingId: finding.id,
1037
+ action: applicable ? "accept" : "reject",
1038
+ rationale: asString(decision?.rationale)
1039
+ || (!decision ? "No decision from the director: rejected by default." : action === "accept" && !applicable ? "Accepted without an applicable fix (remediation or written scene missing): not applied." : ""),
1040
+ remediation,
1041
+ sceneNumber: sceneNumber || undefined,
1042
+ };
1043
+ });
1044
+ asArray(output.extraFixes).map(asRecord).slice(0, 5).forEach((fix, index) => {
1045
+ const sceneNumber = asInteger(fix.sceneNumber, 0, 0, 999);
1046
+ const remediation = asString(fix.remediation);
1047
+ if (!remediation || !writtenScenes.has(sceneNumber))
1048
+ return;
1049
+ decisions.push({ findingId: `D${review.round}-${index + 1}`, action: "accept", rationale: asString(fix.rationale), remediation, sceneNumber });
1050
+ });
1051
+ const accepted = decisions.filter((decision) => decision.action === "accept");
1052
+ const rejected = decisions.filter((decision) => decision.action === "reject");
1053
+ const score = Math.round(asNumber(output.score, 6, 1, 10) * 10) / 10;
1054
+ let verdict = verdictGiven;
1055
+ if (verdict === "revise" && !accepted.length) {
1056
+ verdict = "approve";
1057
+ ctx.insight("warning", italian
1058
+ ? "Il direttore chiede una revisione senza correzioni applicabili: il capitolo è approvato così com'è."
1059
+ : "The director asked for a revision without any applicable fix: the chapter is approved as it is.");
1060
+ }
1061
+ if (undecided.length) {
1062
+ ctx.insight("warning", italian ? `Rilievi senza decisione del direttore, respinti: ${undecided.join(", ")}` : `Findings the director did not decide, rejected: ${undecided.join(", ")}`);
1063
+ }
1064
+ if (unusable.length) {
1065
+ ctx.insight("warning", italian
1066
+ ? `Correzioni accettate ma non applicabili (manca la correzione o la scena scritta), respinte: ${unusable.join(", ")}`
1067
+ : `Fixes accepted without an applicable remediation or written scene, rejected: ${unusable.join(", ")}`);
1068
+ }
1069
+ const summaryText = asString(output.summary);
1070
+ review.decisions = decisions;
1071
+ review.directorDone = true;
1072
+ review.verdict = verdict;
1073
+ review.score = score;
1074
+ review.summary = summaryText;
1075
+ review.repairQueue = [...new Set(accepted.map((decision) => decision.sceneNumber))].sort((left, right) => left - right);
1076
+ review.history = [...review.history, { round: review.round, verdict, score, accepted: accepted.length, rejected: rejected.length }];
1077
+ ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, asStringList(output.guidance, 6));
1078
+ const question = asRecord(output.questionForAuthor);
1079
+ if (ctx.director.autonomy !== "full" && asString(question.question)) {
1080
+ ctx.state.question = {
1081
+ id: `question-${ctx.now().getTime()}`,
1082
+ kind: "director",
1083
+ question: asString(question.question),
1084
+ context: summaryText,
1085
+ options: asStringList(question.options, 5),
1086
+ chapterNumber: chapter.number,
1087
+ askedAt: ctx.now().toISOString(),
1088
+ };
1089
+ }
1090
+ const findingFor = (decision) => review.findings.find((finding) => finding.id === decision.findingId);
1091
+ const opinion = {
1092
+ target: { kind: "chapter", chapter: chapter.slug },
1093
+ targetTitle: `${chapter.number}. ${chapter.title}`,
1094
+ verdict,
1095
+ score,
1096
+ summary: summaryText,
1097
+ strengths: asStringList(output.strengths, 8),
1098
+ concerns: accepted.map((decision) => {
1099
+ const finding = findingFor(decision);
1100
+ return {
1101
+ severity: finding?.severity ?? "major",
1102
+ issue: finding?.problem ?? decision.rationale,
1103
+ ...(finding?.evidence ? { evidence: finding.evidence } : {}),
1104
+ suggestion: `${decision.sceneNumber ? `${italian ? "Scena" : "Scene"} ${decision.sceneNumber}: ` : ""}${decision.remediation}`,
1105
+ };
1106
+ }),
1107
+ decisions: decisions.map((decision) => `${decision.action === "accept" ? (italian ? "Accettato" : "Accepted") : (italian ? "Respinto" : "Rejected")} ${decision.findingId}: ${decision.rationale || decision.remediation}`),
1108
+ nextSteps: asStringList(output.guidance, 6),
1109
+ questionsForAuthor: asString(question.question) ? [asString(question.question)] : [],
1110
+ createdAt: ctx.now().toISOString(),
1111
+ source: "autopilot",
1112
+ directorName: ctx.director.name,
1113
+ model: response.model,
1114
+ provider: response.provider,
1115
+ usage: response.usage,
1116
+ cost: response.cost,
1117
+ currency: response.currency,
1118
+ sourceHash: source.sourceHash,
1119
+ };
1120
+ const opinionPath = directorOpinionPath({ kind: "chapter", chapter: chapter.slug });
1121
+ const opinionChange = await changeFor(ctx.store, opinionPath, () => renderDirectorOpinion(opinion, ctx.language));
1122
+ ctx.insight(verdict === "approve" ? "ok" : "warning", italian
1123
+ ? `Il direttore: ${verdict === "approve" ? "approvato" : "da rivedere"} (${score}/10), ${accepted.length} correzioni accettate, ${rejected.length} respinte`
1124
+ : `Director: ${verdict === "approve" ? "approved" : "revise"} (${score}/10), ${accepted.length} fixes accepted, ${rejected.length} rejected`, summaryText);
1125
+ for (const decision of accepted.slice(0, 4))
1126
+ ctx.insight("info", `${italian ? "Correzione" : "Fix"} ${italian ? "scena" : "scene"} ${decision.sceneNumber}: ${truncate(decision.remediation, 160)}`, decision.rationale);
1127
+ return { changes: compact([opinionChange]), summary: `${verdict} ${score}/10 — ${accepted.length} accepted, ${rejected.length} rejected. ${summaryText}` };
1128
+ }
1129
+ async function rewriteScene(ctx, chapter, scene, instructions, mode) {
1130
+ if (!scene.path)
1131
+ throw new Error(`Scene ${chapter.number}.${scene.number} has no file.`);
1132
+ const loaded = await readDocument(ctx.store, scene.path);
1133
+ if (!loaded)
1134
+ throw new Error(`Scene file not found: ${scene.path}`);
1135
+ const info = chapterFiles(ctx, chapter);
1136
+ const [ghostwriter, secrets, neighbors] = await Promise.all([
1137
+ loadGhostwriter(ctx.store, ctx.snapshot, info),
1138
+ secretRules(ctx.store, ctx.snapshot, chapter.number),
1139
+ sceneNeighbors(ctx, chapter, scene),
1140
+ ]);
1141
+ const originalWords = countWords(loaded.document.body);
1142
+ const relevant = mentionedCanon(ctx.snapshot, loaded.document.body, 10, [...scene.characters, scene.location ?? "", scene.pov ?? ""]);
1143
+ const response = await ctx.ai({
1144
+ capability: AI_CAPABILITIES.writer,
1145
+ label: `autopilot:${mode}:${chapter.number}.${scene.number}`,
1146
+ system: writerSystemPrompt(ctx.language),
1147
+ user: `${request([
1148
+ mode === "repair"
1149
+ ? `Revise scene ${scene.number} of chapter ${chapter.number} «${scene.title}» applying ONLY these fixes approved by the director:`
1150
+ : `Rewrite scene ${scene.number} of chapter ${chapter.number} «${scene.title}» to honor the author's revision:`,
1151
+ instructions.map((instruction, index) => `${index + 1}. ${instruction}`).join("\n"),
1152
+ "Keep everything else as it is: events, facts, voice, rhythm, secrets and approximate length, unless an instruction requires otherwise. Return the complete revised scene.",
1153
+ authorRules(ctx),
1154
+ ])}\n\n${data([
1155
+ bookHeader(ctx),
1156
+ `GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
1157
+ directorGuidance(ctx),
1158
+ scenePlanBlock(scene),
1159
+ relevant.length ? `RELEVANT CANON:\n${await canonDetails(ctx.store, relevant)}` : "",
1160
+ secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
1161
+ neighbors.previousEnding ? `PREVIOUS SCENE ENDING:\n${neighbors.previousEnding}` : "",
1162
+ neighbors.nextOpening ? `NEXT SCENE OPENING (keep it consistent):\n${neighbors.nextOpening}` : "",
1163
+ `CURRENT SCENE:\n${loaded.document.body}`,
1164
+ ])}`,
1165
+ maxOutputTokens: Math.min(16000, Math.ceil(Math.max(originalWords, 300) * 2.4) + 800),
1166
+ temperature: Math.min(0.7, ghostwriter?.temperature ?? 0.7),
1167
+ });
1168
+ const prose = cleanProse(response.text);
1169
+ assertProse(prose, Math.max(60, Math.floor(originalWords * 0.5)));
1170
+ // The summary must describe the scene as it is now: later chapters and reviews rely on it.
1171
+ const summary = await summarizeScene(ctx, chapter, scene, prose);
1172
+ const frontmatter = summary ? { ...loaded.document.frontmatter, summary } : loaded.document.frontmatter;
1173
+ return {
1174
+ change: { path: scene.path, content: renderMarkdown(frontmatter, prose), expectedHash: loaded.file.hash },
1175
+ words: countWords(prose),
1176
+ summary,
1177
+ };
1178
+ }
1179
+ async function runRepair(ctx) {
1180
+ const chapter = chapterOf(ctx);
1181
+ const scene = sceneOf(chapter, ctx.task.sceneNumber);
1182
+ const review = ctx.state.review;
1183
+ const instructions = review.decisions.filter((decision) => decision.action === "accept" && decision.sceneNumber === scene.number).map((decision) => decision.remediation);
1184
+ review.repairQueue = review.repairQueue.filter((number) => number !== scene.number);
1185
+ if (!instructions.length)
1186
+ return { changes: [], summary: "No fix to apply." };
1187
+ const { change, words, summary } = await rewriteScene(ctx, chapter, scene, [...instructions, ...ctx.notes.map((note) => note.text)], "repair");
1188
+ scene.revisions += 1;
1189
+ scene.words = words;
1190
+ if (summary)
1191
+ scene.summary = summary;
1192
+ ctx.insight("ok", isItalian(ctx.language) ? `Scena ${chapter.number}.${scene.number} corretta (${instructions.length})` : `Scene ${chapter.number}.${scene.number} revised (${instructions.length})`, instructions.join(" · "));
1193
+ return { changes: [change], summary: `${instructions.length} fixes applied, ${words} words.` };
1194
+ }
1195
+ async function runConsolidate(ctx) {
1196
+ const chapter = chapterOf(ctx);
1197
+ const plan = ctx.state.plan;
1198
+ const review = ctx.state.review;
1199
+ const source = await chapterSource(ctx, chapter);
1200
+ // Built from the chapters before this one only: never from a resume that already covers this chapter or later ones.
1201
+ const resume = await storySoFar(ctx, chapter.number, 7000);
1202
+ const firstChapter = !plan.chapters.some((entry) => entry.number < chapter.number);
1203
+ const response = await ctx.ai({
1204
+ capability: AI_CAPABILITIES.writer,
1205
+ label: `autopilot:consolidate:${chapter.number}`,
1206
+ system: continuitySystemPrompt(ctx.language),
1207
+ user: `${request([
1208
+ `Close chapter ${chapter.number} «${chapter.title}»: write its summary, its recap (one bullet per scene, in order), the continuity delta, and the updated story so far including this chapter.`,
1209
+ `Keep the story so far under ${STORY_SO_FAR_TARGET_WORDS} words (hard limit: ${STORY_SO_FAR_MAX_WORDS}): compress the oldest chapters and keep the most recent ones more detailed.`,
1210
+ ])}\n\n${data([
1211
+ bookHeader(ctx),
1212
+ chapterPlanBlock(chapter),
1213
+ resume
1214
+ ? `STORY SO FAR (before this chapter):\n${resume}`
1215
+ : firstChapter ? "STORY SO FAR: this is the first chapter." : "STORY SO FAR (before this chapter): not available.",
1216
+ `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, 9000)}`,
1217
+ ])}`,
1218
+ json: CONSOLIDATION_TOOL,
1219
+ maxOutputTokens: 5000,
1220
+ temperature: 0.3,
1221
+ });
1222
+ const subject = "The chapter consolidation";
1223
+ const output = requireStructuredFields(response.json, { summary: "text", storySoFar: "text" }, subject);
1224
+ const summary = asString(output.summary);
1225
+ const recap = asString(output.recap) || summary;
1226
+ const storySoFarText = asString(output.storySoFar);
1227
+ const excess = storySoFarExcess(storySoFarText);
1228
+ if (excess) {
1229
+ throw new AiReplyRejectedError(`${subject} was rejected: "storySoFar" is ${excess.words} words long, ${excess.over} words over the ${STORY_SO_FAR_MAX_WORDS}-word limit. Rewrite it under ${STORY_SO_FAR_TARGET_WORDS} words.`);
1230
+ }
1231
+ const stateChanges = asRecord(output.stateChanges);
1232
+ const changes = [];
1233
+ changes.push(await changeFor(ctx.store, chapterFilePath(chapter.slug), (existing) => existing
1234
+ ? renderMarkdown({ ...existing.frontmatter, summary }, existing.body)
1235
+ : renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary, canon: "draft" }, `# ${chapter.title}`)));
1236
+ changes.push(await changeFor(ctx.store, chapterResumePath(chapter.slug), (existing) => renderMarkdown({
1237
+ ...(existing?.frontmatter ?? {}),
1238
+ type: "resume",
1239
+ id: `resume:chapter:${chapter.slug}`,
1240
+ title: `Resume ${chapter.slug}`,
1241
+ chapter: `chapter:${chapter.slug}`,
1242
+ state_changes: Object.keys(stateChanges).length ? stateChanges : undefined,
1243
+ }, `# Chapter Summary\n\n${recap}`)));
1244
+ // One section per chapter, like Narrarium core: closing this chapter replaces only its own section.
1245
+ changes.push(await changeFor(ctx.store, TOTAL_RESUME_FILE, (existing) => renderMarkdown({ ...(existing?.frontmatter ?? {}), type: "resume", id: "resume:total", title: "Total Resume" }, renderTotalResumeBody(existing?.body ?? "", plan.chapters, { number: chapter.number, title: chapter.title, summary }))));
1246
+ chapter.summary = summary;
1247
+ chapter.status = "done";
1248
+ chapter.score = review?.score;
1249
+ chapter.skipReaders = undefined;
1250
+ chapter.storySoFarAtClose = storySoFarText;
1251
+ // Synopses saved by later chapters include the previous version of this one: they no longer apply.
1252
+ for (const later of plan.chapters)
1253
+ if (later.number > chapter.number)
1254
+ later.storySoFarAtClose = undefined;
1255
+ pruneStorySnapshots(plan.chapters);
1256
+ for (const scene of chapter.scenes)
1257
+ if (scene.status === "written")
1258
+ scene.status = "reviewed";
1259
+ ctx.state.review = null;
1260
+ changes.push(await renderPlot(ctx));
1261
+ changes.push(await planFileChange(ctx));
1262
+ ctx.insight("ok", isItalian(ctx.language) ? `Capitolo ${chapter.number} approvato${review?.score ? ` (${review.score}/10)` : ""}` : `Chapter ${chapter.number} approved${review?.score ? ` (${review.score}/10)` : ""}`, summary);
1263
+ return { changes: compact(changes), summary };
1264
+ }
1265
+ // ─── Author revision and final review ───────────────────────────────────────
1266
+ async function runImpact(ctx) {
1267
+ const revision = ctx.state.revision;
1268
+ const plan = ctx.state.plan;
1269
+ const written = (plan?.chapters ?? []).flatMap((chapter) => chapter.scenes.filter((scene) => scene.status !== "planned" && scene.path).map((scene) => ({ chapter, scene })));
1270
+ if (!written.length) {
1271
+ revision.targets = [];
1272
+ return { changes: [], summary: "Nothing written yet: the instruction becomes a permanent rule." };
1273
+ }
1274
+ const design = await readBody(ctx.store, STORY_DESIGN_FILE, 3000);
1275
+ const response = await ctx.ai({
1276
+ capability: AI_CAPABILITIES.director,
1277
+ label: "autopilot:impact",
1278
+ system: directorSystemPrompt(ctx.director, ctx.language),
1279
+ user: `${request([
1280
+ `The author asked to revise what is already written: «${revision.instruction}».`,
1281
+ "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.",
1282
+ ])}\n\n${data([
1283
+ bookHeader(ctx),
1284
+ design ? `STORY DESIGN:\n${design}` : "",
1285
+ `WRITTEN SCENES:\n${written.map(({ chapter, scene }) => `- Chapter ${chapter.number}, scene ${scene.number} «${scene.title}»: ${scene.summary ?? scene.goal}`).join("\n")}`,
1286
+ ])}`,
1287
+ json: IMPACT_TOOL,
1288
+ maxOutputTokens: 3000,
1289
+ });
1290
+ const subject = "The revision impact";
1291
+ // Without the targets list the author's revision would be silently ignored.
1292
+ const output = requireStructuredFields(response.json, { targets: "list" }, subject);
1293
+ const proposedTargets = asArray(output.targets).map(asRecord);
1294
+ const valid = new Set(written.map(({ chapter, scene }) => `${chapter.number}:${scene.number}`));
1295
+ revision.targets = proposedTargets
1296
+ .map((target) => ({ chapterNumber: asInteger(target.chapterNumber, 0, 0, 999), sceneNumber: asInteger(target.sceneNumber, 0, 0, 999), instruction: asString(target.instruction) || revision.instruction }))
1297
+ .filter((target, index, list) => valid.has(`${target.chapterNumber}:${target.sceneNumber}`) && list.findIndex((other) => other.chapterNumber === target.chapterNumber && other.sceneNumber === target.sceneNumber) === index)
1298
+ .sort((left, right) => left.chapterNumber - right.chapterNumber || left.sceneNumber - right.sceneNumber)
1299
+ .slice(0, 40);
1300
+ if (proposedTargets.length && !revision.targets.length) {
1301
+ throw new AiReplyRejectedError(`${subject} was rejected: none of its ${proposedTargets.length} targets is a written scene. Use the chapter and scene numbers of the WRITTEN SCENES list.`);
1302
+ }
1303
+ revision.cursor = 0;
1304
+ ctx.insight(revision.targets.length ? "warning" : "info", isItalian(ctx.language) ? `${revision.targets.length} scene da riscrivere` : `${revision.targets.length} scenes to rewrite`, asString(output.summary));
1305
+ return { changes: [], summary: `${revision.targets.length} scenes — ${asString(output.summary)}` };
1306
+ }
1307
+ async function runRevise(ctx) {
1308
+ const revision = ctx.state.revision;
1309
+ const target = revision.targets[revision.cursor];
1310
+ const chapter = chapterOf(ctx);
1311
+ const scene = sceneOf(chapter, ctx.task.sceneNumber);
1312
+ const { change, words, summary } = await rewriteScene(ctx, chapter, scene, [target.instruction, ...ctx.notes.map((note) => note.text)], "revise");
1313
+ scene.revisions += 1;
1314
+ scene.words = words;
1315
+ if (summary)
1316
+ scene.summary = summary;
1317
+ revision.cursor += 1;
1318
+ ctx.insight("ok", isItalian(ctx.language) ? `Scena ${chapter.number}.${scene.number} riscritta` : `Scene ${chapter.number}.${scene.number} rewritten`, target.instruction);
1319
+ return { changes: [change], summary: `${words} words — ${target.instruction}` };
1320
+ }
1321
+ async function runFinal(ctx) {
1322
+ const result = await askDirector({
1323
+ store: ctx.store,
1324
+ ai: { complete: (aiRequest) => ctx.ai(aiRequest) },
1325
+ target: { kind: "book" },
1326
+ snapshot: ctx.snapshot,
1327
+ signal: ctx.signal,
1328
+ now: ctx.now,
1329
+ source: "autopilot",
1330
+ 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.",
1331
+ });
1332
+ ctx.state.finalDone = true;
1333
+ const change = await changeFor(ctx.store, result.path, () => renderDirectorOpinion(result.opinion, ctx.language));
1334
+ 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);
1335
+ return { changes: compact([change]), summary: `${result.opinion.verdict} ${result.opinion.score}/10 — ${result.opinion.summary}` };
1336
+ }
1337
+ export const TASK_EXECUTORS = {
1338
+ concept: runConcept,
1339
+ plan: runPlan,
1340
+ "plan-reader": runPlanReader,
1341
+ "plan-review": runPlanReview,
1342
+ scenes: runScenes,
1343
+ write: runWrite,
1344
+ reader: runReader,
1345
+ "readers-summary": runReadersSummary,
1346
+ specialists: runSpecialists,
1347
+ "director-review": runDirectorReview,
1348
+ repair: runRepair,
1349
+ consolidate: runConsolidate,
1350
+ impact: runImpact,
1351
+ revise: runRevise,
1352
+ final: runFinal,
1353
+ };
1354
+ //# sourceMappingURL=tasks.js.map