narrarium-engine 0.1.3 → 0.1.4

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 (133) hide show
  1. package/README.md +130 -10
  2. package/dist/ai/budget.d.ts +26 -0
  3. package/dist/ai/budget.d.ts.map +1 -0
  4. package/dist/ai/budget.js +35 -0
  5. package/dist/ai/budget.js.map +1 -0
  6. package/dist/ai/config.d.ts +26 -0
  7. package/dist/ai/config.d.ts.map +1 -1
  8. package/dist/ai/config.js +33 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/ai/fetch-client.d.ts +80 -9
  11. package/dist/ai/fetch-client.d.ts.map +1 -1
  12. package/dist/ai/fetch-client.js +287 -114
  13. package/dist/ai/fetch-client.js.map +1 -1
  14. package/dist/ai/redact.d.ts +7 -0
  15. package/dist/ai/redact.d.ts.map +1 -0
  16. package/dist/ai/redact.js +34 -0
  17. package/dist/ai/redact.js.map +1 -0
  18. package/dist/ai/request.d.ts +34 -0
  19. package/dist/ai/request.d.ts.map +1 -0
  20. package/dist/ai/request.js +86 -0
  21. package/dist/ai/request.js.map +1 -0
  22. package/dist/ai/router.js +1 -1
  23. package/dist/ai/router.js.map +1 -1
  24. package/dist/ai/routing.d.ts +47 -0
  25. package/dist/ai/routing.d.ts.map +1 -0
  26. package/dist/ai/routing.js +83 -0
  27. package/dist/ai/routing.js.map +1 -0
  28. package/dist/ai/structured.d.ts +13 -4
  29. package/dist/ai/structured.d.ts.map +1 -1
  30. package/dist/ai/structured.js +58 -8
  31. package/dist/ai/structured.js.map +1 -1
  32. package/dist/ai/token-limit.d.ts +21 -2
  33. package/dist/ai/token-limit.d.ts.map +1 -1
  34. package/dist/ai/token-limit.js +48 -4
  35. package/dist/ai/token-limit.js.map +1 -1
  36. package/dist/ai/types.d.ts +40 -0
  37. package/dist/ai/types.d.ts.map +1 -1
  38. package/dist/ai/types.js +32 -0
  39. package/dist/ai/types.js.map +1 -1
  40. package/dist/autopilot/planner.d.ts +22 -1
  41. package/dist/autopilot/planner.d.ts.map +1 -1
  42. package/dist/autopilot/planner.js +166 -14
  43. package/dist/autopilot/planner.js.map +1 -1
  44. package/dist/autopilot/profile-check.d.ts +24 -0
  45. package/dist/autopilot/profile-check.d.ts.map +1 -0
  46. package/dist/autopilot/profile-check.js +38 -0
  47. package/dist/autopilot/profile-check.js.map +1 -0
  48. package/dist/autopilot/prompts.d.ts +1 -0
  49. package/dist/autopilot/prompts.d.ts.map +1 -1
  50. package/dist/autopilot/prompts.js +9 -0
  51. package/dist/autopilot/prompts.js.map +1 -1
  52. package/dist/autopilot/runner.d.ts +75 -8
  53. package/dist/autopilot/runner.d.ts.map +1 -1
  54. package/dist/autopilot/runner.js +425 -84
  55. package/dist/autopilot/runner.js.map +1 -1
  56. package/dist/autopilot/session.d.ts +44 -2
  57. package/dist/autopilot/session.d.ts.map +1 -1
  58. package/dist/autopilot/session.js +115 -18
  59. package/dist/autopilot/session.js.map +1 -1
  60. package/dist/autopilot/state.d.ts +11 -0
  61. package/dist/autopilot/state.d.ts.map +1 -1
  62. package/dist/autopilot/state.js +31 -0
  63. package/dist/autopilot/state.js.map +1 -1
  64. package/dist/autopilot/tasks.d.ts +2 -0
  65. package/dist/autopilot/tasks.d.ts.map +1 -1
  66. package/dist/autopilot/tasks.js +233 -59
  67. package/dist/autopilot/tasks.js.map +1 -1
  68. package/dist/autopilot/types.d.ts +20 -2
  69. package/dist/autopilot/types.d.ts.map +1 -1
  70. package/dist/book/context.d.ts +20 -3
  71. package/dist/book/context.d.ts.map +1 -1
  72. package/dist/book/context.js +120 -20
  73. package/dist/book/context.js.map +1 -1
  74. package/dist/book/store.d.ts +5 -0
  75. package/dist/book/store.d.ts.map +1 -1
  76. package/dist/book/store.js.map +1 -1
  77. package/dist/director/opinion.d.ts +10 -0
  78. package/dist/director/opinion.d.ts.map +1 -1
  79. package/dist/director/opinion.js +43 -13
  80. package/dist/director/opinion.js.map +1 -1
  81. package/dist/index.d.ts +4 -0
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +4 -0
  84. package/dist/index.js.map +1 -1
  85. package/dist/markdown/frontmatter.d.ts +22 -1
  86. package/dist/markdown/frontmatter.d.ts.map +1 -1
  87. package/dist/markdown/frontmatter.js +67 -11
  88. package/dist/markdown/frontmatter.js.map +1 -1
  89. package/dist/profiles/director.d.ts +15 -0
  90. package/dist/profiles/director.d.ts.map +1 -1
  91. package/dist/profiles/director.js +98 -37
  92. package/dist/profiles/director.js.map +1 -1
  93. package/dist/profiles/ghostwriter.d.ts +7 -0
  94. package/dist/profiles/ghostwriter.d.ts.map +1 -1
  95. package/dist/profiles/ghostwriter.js +54 -16
  96. package/dist/profiles/ghostwriter.js.map +1 -1
  97. package/dist/profiles/read.d.ts +33 -0
  98. package/dist/profiles/read.d.ts.map +1 -0
  99. package/dist/profiles/read.js +96 -0
  100. package/dist/profiles/read.js.map +1 -0
  101. package/dist/profiles/readers.d.ts +8 -0
  102. package/dist/profiles/readers.d.ts.map +1 -1
  103. package/dist/profiles/readers.js +82 -12
  104. package/dist/profiles/readers.js.map +1 -1
  105. package/dist/prompt/trust.d.ts +11 -0
  106. package/dist/prompt/trust.d.ts.map +1 -1
  107. package/dist/prompt/trust.js +26 -0
  108. package/dist/prompt/trust.js.map +1 -1
  109. package/dist/readers/evaluation.d.ts.map +1 -1
  110. package/dist/readers/evaluation.js +3 -2
  111. package/dist/readers/evaluation.js.map +1 -1
  112. package/dist/server/client.d.ts +38 -4
  113. package/dist/server/client.d.ts.map +1 -1
  114. package/dist/server/client.js +43 -9
  115. package/dist/server/client.js.map +1 -1
  116. package/dist/server/protocol.d.ts +25 -0
  117. package/dist/server/protocol.d.ts.map +1 -1
  118. package/dist/server/protocol.js +23 -2
  119. package/dist/server/protocol.js.map +1 -1
  120. package/dist/sync/files.d.ts +21 -1
  121. package/dist/sync/files.d.ts.map +1 -1
  122. package/dist/sync/files.js +84 -15
  123. package/dist/sync/files.js.map +1 -1
  124. package/dist/testing/index.d.ts.map +1 -1
  125. package/dist/testing/index.js +2 -0
  126. package/dist/testing/index.js.map +1 -1
  127. package/dist/util/text.d.ts +28 -0
  128. package/dist/util/text.d.ts.map +1 -1
  129. package/dist/util/text.js +80 -1
  130. package/dist/util/text.js.map +1 -1
  131. package/dist/version.d.ts +1 -1
  132. package/dist/version.js +1 -1
  133. package/package.json +1 -1
@@ -1,18 +1,18 @@
1
- import { requireStructuredFields, splitReasoningBlock } from "../ai/structured.js";
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
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";
5
- import { askDirector, directorSystemPrompt, renderDirectorOpinion } from "../director/opinion.js";
6
- import { frontmatterString, parseMarkdown, renderMarkdown } from "../markdown/frontmatter.js";
5
+ import { askDirector, directorSystemPrompt, parseDirectorVerdict, renderDirectorOpinion, withheldApprovalNote } from "../director/opinion.js";
6
+ import { assertFrontmatterReadable, frontmatterString, parseMarkdown, renderMarkdown } from "../markdown/frontmatter.js";
7
7
  import { readerPersonaSystemPrompt } from "../profiles/readers.js";
8
- import { currentRequest, untrustedData } from "../prompt/trust.js";
8
+ import { currentRequest, unescapePromptData, untrustedData } from "../prompt/trust.js";
9
9
  import { READER_EVALUATION_TOOL, READER_SUMMARY_TOOL, chapterReaderText, normalizeReaderEvaluationOutput, renderReaderEvaluationBody, renderReaderSummaryBody, } from "../readers/evaluation.js";
10
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, OUTPUT_TOKENS_CEILING, scaleOutputTokens, tail, tokensPerWord, truncate } from "../util/text.js";
11
+ 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";
13
13
  import { chapterLines, layoutChapters, listSection, outlineList } from "./outline.js";
14
- import { batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts } from "./planner.js";
15
- 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";
14
+ import { batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts, sceneFile } from "./planner.js";
15
+ 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
16
  import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES } from "./state.js";
17
17
  import { STORY_SO_FAR_MAX_WORDS, STORY_SO_FAR_TARGET_WORDS, pruneStorySnapshots, readStorySoFar, renderTotalResumeBody, storySoFarExcess } from "./story-so-far.js";
18
18
  // ─── Shared prompt fragments ────────────────────────────────────────────────
@@ -88,6 +88,14 @@ function outputLimit(ctx, tokens) {
88
88
  function sceneOutputLimit(ctx, words) {
89
89
  return Math.min(OUTPUT_TOKENS_CEILING, Math.ceil(words * tokensPerWord(ctx.snapshot.book.language)) + 800);
90
90
  }
91
+ /**
92
+ * Characters of a scene a prompt that judges or summarizes it keeps: what the book asks of a scene, with room for one that
93
+ * runs over (`wordsPerScene`), and never less than `floor`, the limit these prompts had before (so nothing is cut that was not).
94
+ * A scene over it keeps its start and its end.
95
+ */
96
+ function sceneLimit(ctx, floor) {
97
+ return Math.max(floor, sceneCharacterLimit(ctx.state.brief.wordsPerScene));
98
+ }
91
99
  /** The ghostwriter of a chapter. One the book names that is not a file name is skipped, and the author is told. */
92
100
  function ghostwriterOf(ctx, chapter) {
93
101
  return loadGhostwriter(ctx.store, ctx.snapshot, chapter, undefined, {
@@ -118,15 +126,20 @@ function chapterOf(ctx) {
118
126
  throw new Error(`Chapter ${ctx.task.chapterNumber} is not in the plan.`);
119
127
  return chapter;
120
128
  }
121
- /** The director's verdict, tolerant of "approved"/"revision" variants; anything else rejects the reply. */
129
+ /** The director's verdict, tolerant of case, spacing and "approved"/"revision" variants; anything else rejects the reply. */
122
130
  function verdictOf(value, subject) {
123
- const text = asString(value).toLowerCase();
124
- if (/^approv/.test(text))
125
- return "approve";
126
- if (/^(?:revis|rived|rivist|rework|rewrite|riscriv|reject|respin)/.test(text))
127
- return "revise";
131
+ const verdict = parseDirectorVerdict(value);
132
+ if (verdict)
133
+ return verdict === "approve" ? "approve" : "revise";
128
134
  throw new AiReplyRejectedError(`${subject} was rejected: the field "verdict" must be "approve" or "revise".`);
129
135
  }
136
+ /** Why an approval is not accepted as it was given, in the book's language. */
137
+ function withheldApproval(ctx, score, outcome) {
138
+ const needed = ctx.director.approvalScore;
139
+ return isItalian(ctx.language)
140
+ ? `Il direttore ha approvato con ${score}/10, sotto il punteggio di approvazione (${needed}/10): ${outcome}`
141
+ : `The director approved with ${score}/10, below the approval score of ${needed}/10: ${outcome}`;
142
+ }
130
143
  /** The story before a chapter (the whole book without one), keeping its most recent part. */
131
144
  function storySoFar(ctx, beforeChapter, max) {
132
145
  return readStorySoFar(ctx.store, { chapters: ctx.state.plan?.chapters ?? importedChapters(ctx.snapshot), beforeChapter, max });
@@ -152,7 +165,8 @@ export function cleanProse(text) {
152
165
  const lines = value.split(/\r?\n/);
153
166
  while (lines.length && (/^#{1,6}\s/.test(lines[0].trim()) || LATIN_SCENE_HEADING.test(lines[0].trim()) || OTHER_SCENE_HEADING.test(lines[0].trim()) || !lines[0].trim()))
154
167
  lines.shift();
155
- return lines.join("\n").trim();
168
+ // The model repeats what it read, and what it read was escaped.
169
+ return unescapePromptData(lines.join("\n").trim());
156
170
  }
157
171
  /** Prose that cannot become a scene is rejected (and the step retried with the reason). */
158
172
  function assertProse(text, minimumWords) {
@@ -167,16 +181,34 @@ function assertProse(text, minimumWords) {
167
181
  function normalizeForMatch(text) {
168
182
  return text.replace(/[«»“”„"]/g, "\"").replace(/[‘’`]/g, "'").replace(/[–—]/g, "-").replace(/\s+/g, " ").trim().toLowerCase();
169
183
  }
170
- async function changeFor(store, path, render) {
171
- const file = await store.read(path);
184
+ /**
185
+ * The change that rewrites `path` as `render` says (it receives the file as it is now, or `null`), or `null` when nothing changes.
186
+ * A rewrite of a file whose frontmatter cannot be read is refused (`FrontmatterError`, naming the file and the line): it would
187
+ * drop the keys that could not be read.
188
+ */
189
+ async function changeFor(ctx, path, render) {
190
+ const file = await ctx.store.read(path);
172
191
  const existing = file ? parseMarkdown(file.content) : null;
173
192
  const content = render(existing ? { frontmatter: existing.frontmatter, body: existing.body } : null);
174
193
  if (content === null)
175
194
  return null;
176
195
  if (file && file.content === content)
177
196
  return null;
197
+ if (existing)
198
+ assertFrontmatterReadable(path, existing, ctx.language);
178
199
  return { path, content, expectedHash: file?.hash ?? null };
179
200
  }
201
+ /**
202
+ * A step that is going to rewrite these files checks them before it asks the model anything: when the frontmatter of one cannot
203
+ * be read it is refused here (`FrontmatterError`), not after a call that was paid for and cannot be saved.
204
+ */
205
+ async function assertRewritable(ctx, paths) {
206
+ for (const path of paths) {
207
+ const file = await ctx.store.read(path);
208
+ if (file)
209
+ assertFrontmatterReadable(path, parseMarkdown(file.content), ctx.language);
210
+ }
211
+ }
180
212
  function chapterDocument(chapter) {
181
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 || ""}`);
182
214
  }
@@ -261,7 +293,7 @@ async function renderPlot(ctx) {
261
293
  "",
262
294
  bulletList(pending.length ? pending : ["All current secrets are tied to a chapter reveal, or no secrets exist yet."]),
263
295
  ].join("\n");
264
- return changeFor(ctx.store, PLOT_FILE, (existing) => renderMarkdown({ ...(existing?.frontmatter ?? {}), type: "plot", id: "plot:main", title: `${ctx.snapshot.book.title} Plot` }, body));
296
+ return changeFor(ctx, PLOT_FILE, (existing) => renderMarkdown({ ...(existing?.frontmatter ?? {}), type: "plot", id: "plot:main", title: `${ctx.snapshot.book.title} Plot` }, body));
265
297
  }
266
298
  function compact(changes) {
267
299
  return changes.filter((change) => Boolean(change));
@@ -273,6 +305,11 @@ async function runConcept(ctx) {
273
305
  readDocument(ctx.store, STORY_DESIGN_FILE),
274
306
  readDocument(ctx.store, CONTEXT_FILE),
275
307
  ]);
308
+ // Both files are rewritten from what the model says: one whose frontmatter cannot be read is refused before the call.
309
+ if (design)
310
+ assertFrontmatterReadable(STORY_DESIGN_FILE, design.document, ctx.language);
311
+ if (context && isThinDocument(context.document.body))
312
+ assertFrontmatterReadable(CONTEXT_FILE, context.document, ctx.language);
276
313
  const response = await ctx.ai({
277
314
  capability: AI_CAPABILITIES.writer,
278
315
  label: "autopilot:concept",
@@ -386,6 +423,57 @@ async function runConcept(ctx) {
386
423
  : `${counts.character} characters, ${counts.other} other canon entries, ${secrets.length} secrets.`;
387
424
  return { changes: compact(changes), summary: logline ? `${logline} — ${summary}` : summary };
388
425
  }
426
+ // ─── Summaries of the chapters the author wrote ─────────────────────────────
427
+ /** What a summary keeps of the scenes of one chapter at the least, shared among them (as the director's review does); `sceneLimit` raises it for scenes of the length the book asks for. */
428
+ const IMPORTED_CHAPTER_CHARACTERS = 60000;
429
+ /**
430
+ * One chapter the author wrote before the autopilot took over, summarized by the model of the simple tasks and saved in its
431
+ * `chapter.md` (and in its resume, when it has none). The story so far of every chapter written after it is made of these
432
+ * summaries, so the first chapter the autopilot writes no longer starts blind. One chapter a step, one commit a step: the step can
433
+ * be repeated, and a run that stops goes on with the chapters that are left.
434
+ */
435
+ async function runSummarizeImported(ctx) {
436
+ const same = (entry) => entry.number === ctx.task.chapterNumber && (!ctx.task.chapterSlug || entry.slug === ctx.task.chapterSlug);
437
+ const planned = ctx.state.plan?.chapters.find((entry) => entry.imported && same(entry));
438
+ const chapter = planned ?? importedChapters(ctx.snapshot).find(same);
439
+ if (!chapter)
440
+ throw new Error(`Chapter ${ctx.task.chapterNumber} is not a chapter written by the author.`);
441
+ const path = chapterFilePath(chapter.slug);
442
+ const resumePath = chapterResumePath(chapter.slug);
443
+ await assertRewritable(ctx, [path]);
444
+ const paragraphs = await loadChapterParagraphs(ctx.store, chapterFiles(ctx, chapter));
445
+ if (!paragraphs.length)
446
+ throw new Error(`Chapter ${chapter.number} has no scenes to summarize.`);
447
+ const response = await ctx.ai({
448
+ capability: AI_CAPABILITIES.summary,
449
+ label: `autopilot:summarize-imported:${chapter.number}`,
450
+ system: continuitySystemPrompt(ctx.language),
451
+ user: `${request([
452
+ `Summarize chapter ${chapter.number}${chapter.title ? ` «${chapter.title}»` : ""} in two to four sentences: what happens and what changes.`,
453
+ "The author wrote this chapter before the autopilot took over: summarize faithfully what the text contains and never invent events.",
454
+ ])}\n\n${data([
455
+ bookHeader(ctx),
456
+ `CHAPTER TEXT:\n${markedChapterText(paragraphs, sceneLimit(ctx, Math.max(3000, Math.floor(IMPORTED_CHAPTER_CHARACTERS / paragraphs.length))))}`,
457
+ ])}`,
458
+ json: CHAPTER_SUMMARY_TOOL,
459
+ maxOutputTokens: outputLimit(ctx, 600),
460
+ temperature: 0.3,
461
+ });
462
+ const output = requireStructuredFields(response.json, { summary: "text" }, "The chapter summary");
463
+ const summary = asString(output.summary);
464
+ const changes = [];
465
+ changes.push(await changeFor(ctx, path, (existing) => existing
466
+ ? renderMarkdown({ ...existing.frontmatter, summary }, existing.body)
467
+ : renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary, canon: "draft" }, `# ${chapter.title}`)));
468
+ // A resume the author or the core already made is left alone: only a chapter without one gets it.
469
+ if (!(await ctx.store.read(resumePath))) {
470
+ changes.push({ path: resumePath, content: renderMarkdown({ type: "resume", id: `resume:chapter:${chapter.slug}`, title: `Resume ${chapter.slug}`, chapter: `chapter:${chapter.slug}` }, `# Chapter Summary\n\n${summary}`), expectedHash: null });
471
+ }
472
+ if (planned)
473
+ planned.summary = summary;
474
+ ctx.insight("ok", isItalian(ctx.language) ? `Capitolo ${chapter.number} riassunto` : `Chapter ${chapter.number} summarized`, summary);
475
+ return { changes: compact(changes), summary };
476
+ }
389
477
  function normalizeName(name) {
390
478
  return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
391
479
  }
@@ -529,6 +617,7 @@ async function runPlan(ctx) {
529
617
  ...(revisionBatches ? { revisionBatches } : {}),
530
618
  readerReactions: previous?.readerReactions ?? [],
531
619
  readersDone: previous?.readersDone ?? false,
620
+ ...(previous?.skippedReaders?.length ? { skippedReaders: previous.skippedReaders } : {}),
532
621
  awaitingAuthor: false,
533
622
  };
534
623
  changes.push(await planFileChange(ctx));
@@ -550,6 +639,27 @@ async function runPlan(ctx) {
550
639
  function planFocus(plan) {
551
640
  return plan.chapters.find((chapter) => !chapter.imported)?.number;
552
641
  }
642
+ /**
643
+ * A reader's reply read by `read`, or the rejection that ended it when this is already the repeat of a rejected reply:
644
+ * a reader whose reply stays incomplete does not hold the book up, it is skipped (see `skipReader`).
645
+ */
646
+ async function readerReply(ctx, reply, read) {
647
+ try {
648
+ const response = await reply;
649
+ return { response, value: read(response) };
650
+ }
651
+ catch (error) {
652
+ if (ctx.rejectedBefore && error instanceof AiReplyRejectedError)
653
+ return { skipped: error };
654
+ throw error;
655
+ }
656
+ }
657
+ /** The reader is left out and the author is told; the review goes on with the readers who answered. */
658
+ function skipReader(ctx, name, error) {
659
+ const italian = isItalian(ctx.language);
660
+ ctx.insight("warning", italian ? `${name} saltato: la risposta è rimasta incompleta anche dopo un nuovo tentativo.` : `${name} skipped: the reply stayed incomplete after a retry.`, error.message);
661
+ return { changes: [], summary: italian ? `${name} saltato (risposta incompleta).` : `${name} skipped (incomplete reply).` };
662
+ }
553
663
  async function runPlanReader(ctx) {
554
664
  const plan = ctx.state.plan;
555
665
  const reader = ctx.readerPanel.find((entry) => entry.slug === ctx.task.reader);
@@ -558,7 +668,7 @@ async function runPlanReader(ctx) {
558
668
  return { changes: [], summary: "Reader not available." };
559
669
  }
560
670
  const design = await readBody(ctx.store, STORY_DESIGN_FILE, 2500);
561
- const response = await ctx.ai({
671
+ const asked = await readerReply(ctx, ctx.ai({
562
672
  capability: AI_CAPABILITIES.reader,
563
673
  label: `autopilot:plan-reader:${reader.slug}`,
564
674
  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.`,
@@ -570,12 +680,16 @@ async function runPlanReader(ctx) {
570
680
  ])}`,
571
681
  json: PLAN_REACTION_TOOL,
572
682
  maxOutputTokens: outputLimit(ctx, 1500),
573
- });
574
- const output = requireStructuredFields(response.json, { interest: "number" }, "The reader's reaction");
683
+ }), (response) => requireStructuredFields(response.json, { interest: "score", reaction: "text" }, "The reader's reaction"));
684
+ if ("skipped" in asked) {
685
+ plan.skippedReaders = [...new Set([...(plan.skippedReaders ?? []), reader.slug])];
686
+ return skipReader(ctx, reader.name, asked.skipped);
687
+ }
688
+ const output = asked.value;
575
689
  const reaction = {
576
690
  slug: reader.slug,
577
691
  name: reader.name,
578
- interest: Math.round(asNumber(output.interest, 5, 1, 10)),
692
+ interest: Math.round(Math.max(1, normalizeScore(output.interest) ?? 5)),
579
693
  reaction: asString(output.reaction),
580
694
  concerns: asStringList(output.concerns, 8),
581
695
  wishes: asStringList(output.wishes, 8),
@@ -586,6 +700,17 @@ async function runPlanReader(ctx) {
586
700
  }
587
701
  async function runPlanReview(ctx) {
588
702
  const plan = ctx.state.plan;
703
+ // Approving the plan puts the chapter of its reveal into the secrets the concept made that have none: those must be readable first.
704
+ const toRewrite = [];
705
+ for (const secret of ctx.state.concept.secrets) {
706
+ const path = canonPath("secret", secret.slug);
707
+ if (!plan.chapters.some((entry) => entry.number === secret.revealChapter) || !ctx.snapshot.files.has(path))
708
+ continue;
709
+ const file = await ctx.store.read(path);
710
+ if (file && !frontmatterString(parseMarkdown(file.content).frontmatter, "reveal_in"))
711
+ toRewrite.push(path);
712
+ }
713
+ await assertRewritable(ctx, toRewrite);
589
714
  const design = await readBody(ctx.store, STORY_DESIGN_FILE, 5000);
590
715
  const lastRound = plan.rounds >= 2;
591
716
  const response = await ctx.ai({
@@ -611,10 +736,13 @@ async function runPlanReview(ctx) {
611
736
  json: PLAN_REVIEW_TOOL,
612
737
  maxOutputTokens: outputLimit(ctx, 4000),
613
738
  });
614
- // Without a verdict the plan is never approved by default.
615
- const output = requireStructuredFields(response.json, { verdict: "text" }, "The director's plan review");
616
- const verdict = verdictOf(output.verdict, "The director's plan review");
617
- const score = Math.round(asNumber(output.score, 7, 1, 10));
739
+ // Without a verdict and a score the plan is never approved by default.
740
+ const output = requireStructuredFields(response.json, { verdict: "text", score: "score" }, "The director's plan review");
741
+ const verdictGiven = verdictOf(output.verdict, "The director's plan review");
742
+ const score = Math.round(normalizeScore(output.score));
743
+ // The approval score is a rule of the director's profile, not only a line of the prompt.
744
+ const withheld = verdictGiven === "approve" && score < ctx.director.approvalScore;
745
+ const verdict = withheld ? "revise" : verdictGiven;
618
746
  const summaryText = asString(output.summary);
619
747
  const requested = asArray(output.changes).map(asRecord)
620
748
  .map((change) => ({ instruction: asString(change.instruction), chapterNumber: asInteger(change.chapterNumber, 0, 0, MAX_BOOK_CHAPTERS) }))
@@ -623,6 +751,11 @@ async function runPlanReview(ctx) {
623
751
  const guidance = asStringList(output.guidance, 10);
624
752
  const changes = [];
625
753
  const approved = verdict === "approve" || lastRound || changesRequested.length === 0;
754
+ if (withheld) {
755
+ ctx.insight("warning", withheldApproval(ctx, score, approved
756
+ ? (isItalian(ctx.language) ? (lastRound ? "è l'ultima revisione del piano, che è approvato." : "non chiede modifiche, quindi il piano è approvato così com'è.") : (lastRound ? "this is the final plan review, so the plan is approved." : "no change is asked, so the plan is approved as it is."))
757
+ : (isItalian(ctx.language) ? "il piano viene rivisto." : "the plan is revised.")));
758
+ }
626
759
  if (!approved) {
627
760
  plan.rounds += 1;
628
761
  plan.revisionNotes = changesRequested;
@@ -644,7 +777,7 @@ async function runPlanReview(ctx) {
644
777
  const path = canonPath("secret", secret.slug);
645
778
  if (!chapter || !ctx.snapshot.files.has(path))
646
779
  continue;
647
- changes.push(await changeFor(ctx.store, path, (existing) => {
780
+ changes.push(await changeFor(ctx, path, (existing) => {
648
781
  if (!existing || frontmatterString(existing.frontmatter, "reveal_in"))
649
782
  return null;
650
783
  return renderMarkdown({ ...existing.frontmatter, reveal_in: `chapter:${chapter.slug}`, known_from: `chapter:${chapter.slug}` }, existing.body);
@@ -745,13 +878,13 @@ async function sceneNeighbors(ctx, chapter, scene) {
745
878
  const nextScene = chapter.scenes.find((entry) => entry.number === scene.number + 1);
746
879
  let previousEnding = "";
747
880
  if (previousScene?.path) {
748
- previousEnding = tail(await readBody(ctx.store, previousScene.path, 100000), 2400);
881
+ previousEnding = await readBody(ctx.store, previousScene.path, 2400, "end");
749
882
  }
750
883
  else if (scene.number === 1) {
751
884
  const previousChapter = ctx.state.plan?.chapters.find((entry) => entry.number === chapter.number - 1);
752
885
  const last = previousChapter?.scenes.filter((entry) => entry.path).at(-1);
753
886
  if (last?.path)
754
- previousEnding = tail(await readBody(ctx.store, last.path, 100000), 1500);
887
+ previousEnding = await readBody(ctx.store, last.path, 1500, "end");
755
888
  }
756
889
  const nextOpening = nextScene?.path ? truncate(await readBody(ctx.store, nextScene.path, 100000), 900) : "";
757
890
  const writtenSummaries = chapter.scenes
@@ -835,9 +968,11 @@ async function runReader(ctx) {
835
968
  const reader = ctx.readerPanel.find((entry) => entry.slug === slug);
836
969
  if (!reader)
837
970
  return { changes: [], summary: "Reader not available." };
971
+ const path = readerEvaluationPath({ kind: "chapter", chapter: chapter.slug }, reader.slug);
972
+ await assertRewritable(ctx, [path]);
838
973
  const source = await chapterSource(ctx, chapter);
839
974
  const resume = await storySoFar(ctx, chapter.number, 3000);
840
- const response = await ctx.ai({
975
+ const asked = await readerReply(ctx, ctx.ai({
841
976
  capability: AI_CAPABILITIES.reader,
842
977
  label: `reader-evaluation:${reader.slug}`,
843
978
  system: readerPersonaSystemPrompt(reader, languageName(ctx.language), "normal"),
@@ -848,11 +983,17 @@ async function runReader(ctx) {
848
983
  ].filter(Boolean).join("\n\n"))}`,
849
984
  json: READER_EVALUATION_TOOL,
850
985
  maxOutputTokens: outputLimit(ctx, 2500),
851
- });
852
- const output = normalizeReaderEvaluationOutput(requireStructuredFields(response.json, { score: "number" }, "The reader evaluation"));
853
- const path = readerEvaluationPath({ kind: "chapter", chapter: chapter.slug }, reader.slug);
986
+ }), (reply) => normalizeReaderEvaluationOutput(requireStructuredFields(reply.json, { score: "score", generalImpression: "text" }, "The reader evaluation")));
987
+ if ("skipped" in asked) {
988
+ const skipped = skipReader(ctx, reader.name, asked.skipped);
989
+ if (!review.readerScores.length && !review.readersPending.length) {
990
+ ctx.insight("warning", isItalian(ctx.language) ? "Nessun lettore simulato ha risposto: la revisione prosegue senza." : "No simulated reader answered: the review goes on without them.");
991
+ }
992
+ return skipped;
993
+ }
994
+ const { response, value: output } = asked;
854
995
  const updatedAt = ctx.now().toISOString();
855
- const change = await changeFor(ctx.store, path, (existing) => renderMarkdown({
996
+ const change = await changeFor(ctx, path, (existing) => renderMarkdown({
856
997
  ...(existing?.frontmatter ?? {}),
857
998
  id: `reader-evaluation:chapter:${chapter.slug}:chapter:${reader.slug}`,
858
999
  type: "readerEvaluation",
@@ -891,6 +1032,8 @@ async function runReader(ctx) {
891
1032
  async function runReadersSummary(ctx) {
892
1033
  const chapter = chapterOf(ctx);
893
1034
  const review = ctx.state.review;
1035
+ const path = readerSummaryPath({ kind: "chapter", chapter: chapter.slug });
1036
+ await assertRewritable(ctx, [path]);
894
1037
  const evaluations = await Promise.all(review.readerScores.map(async (score) => `READER: ${score.name}\nSCORE: ${score.score}\n${await readBody(ctx.store, score.path, 5000)}`));
895
1038
  const source = await chapterSource(ctx, chapter);
896
1039
  const response = await ctx.ai({
@@ -901,11 +1044,10 @@ async function runReadersSummary(ctx) {
901
1044
  json: READER_SUMMARY_TOOL,
902
1045
  maxOutputTokens: outputLimit(ctx, 2500),
903
1046
  });
904
- const output = requireStructuredFields(response.json, { overallScore: "number" }, "The readers' summary");
905
- const overall = Math.round(asNumber(output.overallScore, 6, 1, 10) * 10) / 10;
906
- const path = readerSummaryPath({ kind: "chapter", chapter: chapter.slug });
1047
+ const output = requireStructuredFields(response.json, { overallScore: "score" }, "The readers' summary");
1048
+ const overall = Math.round(Math.max(1, normalizeScore(output.overallScore) ?? 6) * 10) / 10;
907
1049
  const updatedAt = ctx.now().toISOString();
908
- const change = await changeFor(ctx.store, path, (existing) => renderMarkdown({
1050
+ const change = await changeFor(ctx, path, (existing) => renderMarkdown({
909
1051
  ...(existing?.frontmatter ?? {}),
910
1052
  id: `reader-evaluation-summary:chapter:${chapter.slug}:chapter`,
911
1053
  type: "readerEvaluationSummary",
@@ -976,7 +1118,7 @@ async function runSpecialists(ctx) {
976
1118
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: false }) || "-"}`,
977
1119
  relevant.length ? `CANON DETAILS:\n${await canonDetails(ctx.store, relevant, 600)}` : "",
978
1120
  secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
979
- `CHAPTER TEXT:\n${markedChapterText(source.paragraphs)}`,
1121
+ `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, sceneLimit(ctx, 14000))}`,
980
1122
  ])}`,
981
1123
  json: FINDINGS_TOOL,
982
1124
  maxOutputTokens: outputLimit(ctx, 5000),
@@ -1024,6 +1166,7 @@ function findingLine(finding) {
1024
1166
  async function runDirectorReview(ctx) {
1025
1167
  const chapter = chapterOf(ctx);
1026
1168
  const review = ctx.state.review;
1169
+ await assertRewritable(ctx, [directorOpinionPath({ kind: "chapter", chapter: chapter.slug })]);
1027
1170
  const source = await chapterSource(ctx, chapter);
1028
1171
  const [resume, secrets, readersSummary] = await Promise.all([
1029
1172
  storySoFar(ctx, chapter.number, 4000),
@@ -1032,7 +1175,7 @@ async function runDirectorReview(ctx) {
1032
1175
  ]);
1033
1176
  const maxRounds = ctx.director.maxReviewRounds;
1034
1177
  const last = review.round >= maxRounds;
1035
- const perScene = Math.max(3000, Math.floor(60000 / Math.max(1, source.paragraphs.length)));
1178
+ const perScene = sceneLimit(ctx, Math.max(3000, Math.floor(60000 / Math.max(1, source.paragraphs.length))));
1036
1179
  const response = await ctx.ai({
1037
1180
  capability: AI_CAPABILITIES.director,
1038
1181
  label: `autopilot:director-review:${chapter.number}`,
@@ -1064,7 +1207,7 @@ async function runDirectorReview(ctx) {
1064
1207
  maxOutputTokens: outputLimit(ctx, 6000),
1065
1208
  });
1066
1209
  const subject = "The director's chapter review";
1067
- const output = requireStructuredFields(response.json, { verdict: "text" }, subject);
1210
+ const output = requireStructuredFields(response.json, { verdict: "text", score: "score" }, subject);
1068
1211
  const italian = isItalian(ctx.language);
1069
1212
  const rawDecisions = asArray(output.decisions).map(asRecord);
1070
1213
  const findingIds = review.findings.map((finding) => finding.id);
@@ -1109,13 +1252,27 @@ async function runDirectorReview(ctx) {
1109
1252
  });
1110
1253
  const accepted = decisions.filter((decision) => decision.action === "accept");
1111
1254
  const rejected = decisions.filter((decision) => decision.action === "reject");
1112
- const score = Math.round(asNumber(output.score, 6, 1, 10) * 10) / 10;
1255
+ const score = Math.round(normalizeScore(output.score) * 10) / 10;
1113
1256
  let verdict = verdictGiven;
1257
+ // The approval score is a rule of the director's profile, not only a line of the prompt.
1258
+ const withheld = verdict === "approve" && score < ctx.director.approvalScore;
1259
+ if (withheld)
1260
+ verdict = "revise";
1261
+ let withheldNote = withheld ? withheldApprovalNote(score, ctx.director.approvalScore, ctx.language) : "";
1114
1262
  if (verdict === "revise" && !accepted.length) {
1115
1263
  verdict = "approve";
1116
- ctx.insight("warning", italian
1117
- ? "Il direttore chiede una revisione senza correzioni applicabili: il capitolo è approvato così com'è."
1118
- : "The director asked for a revision without any applicable fix: the chapter is approved as it is.");
1264
+ if (withheld) {
1265
+ withheldNote = withheldApproval(ctx, score, italian ? "non c'è alcuna correzione applicabile, quindi il capitolo è approvato così com'è." : "no fix could be applied, so the chapter is approved as it is.");
1266
+ ctx.insight("warning", withheldNote);
1267
+ }
1268
+ else {
1269
+ ctx.insight("warning", italian
1270
+ ? "Il direttore chiede una revisione senza correzioni applicabili: il capitolo è approvato così com'è."
1271
+ : "The director asked for a revision without any applicable fix: the chapter is approved as it is.");
1272
+ }
1273
+ }
1274
+ else if (withheld) {
1275
+ ctx.insight("warning", withheldApproval(ctx, score, italian ? "il capitolo è trattato come da rivedere." : "the chapter is treated as a revision."));
1119
1276
  }
1120
1277
  if (undecided.length) {
1121
1278
  ctx.insight("warning", italian ? `Rilievi senza decisione del direttore, respinti: ${undecided.join(", ")}` : `Findings the director did not decide, rejected: ${undecided.join(", ")}`);
@@ -1163,7 +1320,7 @@ async function runDirectorReview(ctx) {
1163
1320
  suggestion: `${decision.sceneNumber ? `${italian ? "Scena" : "Scene"} ${decision.sceneNumber}: ` : ""}${decision.remediation}`,
1164
1321
  };
1165
1322
  }),
1166
- decisions: decisions.map((decision) => `${decision.action === "accept" ? (italian ? "Accettato" : "Accepted") : (italian ? "Respinto" : "Rejected")} ${decision.findingId}: ${decision.rationale || decision.remediation}`),
1323
+ decisions: [...(withheldNote ? [withheldNote] : []), ...decisions.map((decision) => `${decision.action === "accept" ? (italian ? "Accettato" : "Accepted") : (italian ? "Respinto" : "Rejected")} ${decision.findingId}: ${decision.rationale || decision.remediation}`)],
1167
1324
  nextSteps: asStringList(output.guidance, 6),
1168
1325
  questionsForAuthor: asString(question.question) ? [asString(question.question)] : [],
1169
1326
  createdAt: ctx.now().toISOString(),
@@ -1177,7 +1334,7 @@ async function runDirectorReview(ctx) {
1177
1334
  sourceHash: source.sourceHash,
1178
1335
  };
1179
1336
  const opinionPath = directorOpinionPath({ kind: "chapter", chapter: chapter.slug });
1180
- const opinionChange = await changeFor(ctx.store, opinionPath, () => renderDirectorOpinion(opinion, ctx.language));
1337
+ const opinionChange = await changeFor(ctx, opinionPath, () => renderDirectorOpinion(opinion, ctx.language));
1181
1338
  ctx.insight(verdict === "approve" ? "ok" : "warning", italian
1182
1339
  ? `Il direttore: ${verdict === "approve" ? "approvato" : "da rivedere"} (${score}/10), ${accepted.length} correzioni accettate, ${rejected.length} respinte`
1183
1340
  : `Director: ${verdict === "approve" ? "approved" : "revise"} (${score}/10), ${accepted.length} fixes accepted, ${rejected.length} rejected`, summaryText);
@@ -1185,12 +1342,18 @@ async function runDirectorReview(ctx) {
1185
1342
  ctx.insight("info", `${italian ? "Correzione" : "Fix"} ${italian ? "scena" : "scene"} ${decision.sceneNumber}: ${truncate(decision.remediation, 160)}`, decision.rationale);
1186
1343
  return { changes: compact([opinionChange]), summary: `${verdict} ${score}/10 — ${accepted.length} accepted, ${rejected.length} rejected. ${summaryText}` };
1187
1344
  }
1345
+ /** The scene's file is gone (the author deleted it): there is nothing to rewrite, so the step is passed over and says so. */
1346
+ function sceneGone(ctx, chapter, scene) {
1347
+ const path = sceneFile(chapter, scene);
1348
+ ctx.insight("warning", isItalian(ctx.language) ? `La scena ${chapter.number}.${scene.number} non esiste più (${path}): la riscrittura viene saltata` : `Scene ${chapter.number}.${scene.number} no longer exists (${path}): its rewrite is skipped`, isItalian(ctx.language) ? "Non c'è più nulla da riscrivere: l'autopilot prosegue." : "There is nothing left to rewrite there: the autopilot goes on.");
1349
+ return { changes: [], summary: `Skipped: ${path} no longer exists.` };
1350
+ }
1188
1351
  async function rewriteScene(ctx, chapter, scene, instructions, mode) {
1189
- if (!scene.path)
1190
- throw new Error(`Scene ${chapter.number}.${scene.number} has no file.`);
1191
- const loaded = await readDocument(ctx.store, scene.path);
1192
- if (!loaded)
1193
- throw new Error(`Scene file not found: ${scene.path}`);
1352
+ const loaded = scene.path ? await readDocument(ctx.store, scene.path) : null;
1353
+ if (!scene.path || !loaded)
1354
+ return null;
1355
+ // The scene is rewritten with the keys it has now: if they cannot be read the file is refused, before the model is asked.
1356
+ assertFrontmatterReadable(scene.path, loaded.document, ctx.language);
1194
1357
  const info = chapterFiles(ctx, chapter);
1195
1358
  const [ghostwriter, secrets, neighbors] = await Promise.all([
1196
1359
  ghostwriterOf(ctx, info),
@@ -1243,7 +1406,10 @@ async function runRepair(ctx) {
1243
1406
  review.repairQueue = review.repairQueue.filter((number) => number !== scene.number);
1244
1407
  if (!instructions.length)
1245
1408
  return { changes: [], summary: "No fix to apply." };
1246
- const { change, words, summary } = await rewriteScene(ctx, chapter, scene, [...instructions, ...ctx.notes.map((note) => note.text)], "repair");
1409
+ const rewritten = await rewriteScene(ctx, chapter, scene, instructions, "repair");
1410
+ if (!rewritten)
1411
+ return sceneGone(ctx, chapter, scene);
1412
+ const { change, words, summary } = rewritten;
1247
1413
  scene.revisions += 1;
1248
1414
  scene.words = words;
1249
1415
  if (summary)
@@ -1255,6 +1421,7 @@ async function runConsolidate(ctx) {
1255
1421
  const chapter = chapterOf(ctx);
1256
1422
  const plan = ctx.state.plan;
1257
1423
  const review = ctx.state.review;
1424
+ await assertRewritable(ctx, [chapterFilePath(chapter.slug), chapterResumePath(chapter.slug), TOTAL_RESUME_FILE, PLOT_FILE]);
1258
1425
  const source = await chapterSource(ctx, chapter);
1259
1426
  // Built from the chapters before this one only: never from a resume that already covers this chapter or later ones.
1260
1427
  const resume = await storySoFar(ctx, chapter.number, 7000);
@@ -1272,7 +1439,7 @@ async function runConsolidate(ctx) {
1272
1439
  resume
1273
1440
  ? `STORY SO FAR (before this chapter):\n${resume}`
1274
1441
  : firstChapter ? "STORY SO FAR: this is the first chapter." : "STORY SO FAR (before this chapter): not available.",
1275
- `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, 9000)}`,
1442
+ `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, sceneLimit(ctx, 9000))}`,
1276
1443
  ])}`,
1277
1444
  json: CONSOLIDATION_TOOL,
1278
1445
  maxOutputTokens: outputLimit(ctx, 5000),
@@ -1289,10 +1456,10 @@ async function runConsolidate(ctx) {
1289
1456
  }
1290
1457
  const stateChanges = asRecord(output.stateChanges);
1291
1458
  const changes = [];
1292
- changes.push(await changeFor(ctx.store, chapterFilePath(chapter.slug), (existing) => existing
1459
+ changes.push(await changeFor(ctx, chapterFilePath(chapter.slug), (existing) => existing
1293
1460
  ? renderMarkdown({ ...existing.frontmatter, summary }, existing.body)
1294
1461
  : renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary, canon: "draft" }, `# ${chapter.title}`)));
1295
- changes.push(await changeFor(ctx.store, chapterResumePath(chapter.slug), (existing) => renderMarkdown({
1462
+ changes.push(await changeFor(ctx, chapterResumePath(chapter.slug), (existing) => renderMarkdown({
1296
1463
  ...(existing?.frontmatter ?? {}),
1297
1464
  type: "resume",
1298
1465
  id: `resume:chapter:${chapter.slug}`,
@@ -1301,7 +1468,7 @@ async function runConsolidate(ctx) {
1301
1468
  state_changes: Object.keys(stateChanges).length ? stateChanges : undefined,
1302
1469
  }, `# Chapter Summary\n\n${recap}`)));
1303
1470
  // One section per chapter, like Narrarium core: closing this chapter replaces only its own section.
1304
- 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 }))));
1471
+ changes.push(await changeFor(ctx, 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 }))));
1305
1472
  chapter.summary = summary;
1306
1473
  chapter.status = "done";
1307
1474
  chapter.score = review?.score;
@@ -1410,7 +1577,12 @@ async function runRevise(ctx) {
1410
1577
  const target = revision.targets[revision.cursor];
1411
1578
  const chapter = chapterOf(ctx);
1412
1579
  const scene = sceneOf(chapter, ctx.task.sceneNumber);
1413
- const { change, words, summary } = await rewriteScene(ctx, chapter, scene, [target.instruction, ...ctx.notes.map((note) => note.text)], "revise");
1580
+ const rewritten = await rewriteScene(ctx, chapter, scene, [target.instruction], "revise");
1581
+ if (!rewritten) {
1582
+ revision.cursor += 1;
1583
+ return sceneGone(ctx, chapter, scene);
1584
+ }
1585
+ const { change, words, summary } = rewritten;
1414
1586
  scene.revisions += 1;
1415
1587
  scene.words = words;
1416
1588
  if (summary)
@@ -1420,6 +1592,7 @@ async function runRevise(ctx) {
1420
1592
  return { changes: [change], summary: `${words} words — ${target.instruction}` };
1421
1593
  }
1422
1594
  async function runFinal(ctx) {
1595
+ await assertRewritable(ctx, [directorOpinionPath({ kind: "book" })]);
1423
1596
  const result = await askDirector({
1424
1597
  store: ctx.store,
1425
1598
  ai: { complete: (aiRequest) => ctx.ai(aiRequest) },
@@ -1431,12 +1604,13 @@ async function runFinal(ctx) {
1431
1604
  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.",
1432
1605
  });
1433
1606
  ctx.state.finalDone = true;
1434
- const change = await changeFor(ctx.store, result.path, () => renderDirectorOpinion(result.opinion, ctx.language));
1607
+ const change = await changeFor(ctx, result.path, () => renderDirectorOpinion(result.opinion, ctx.language));
1435
1608
  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);
1436
1609
  return { changes: compact([change]), summary: `${result.opinion.verdict} ${result.opinion.score}/10 — ${result.opinion.summary}` };
1437
1610
  }
1438
1611
  export const TASK_EXECUTORS = {
1439
1612
  concept: runConcept,
1613
+ "summarize-imported": runSummarizeImported,
1440
1614
  plan: runPlan,
1441
1615
  "plan-reader": runPlanReader,
1442
1616
  "plan-review": runPlanReview,