narrarium-engine 0.1.23 → 0.1.25

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 (86) hide show
  1. package/README.md +21 -2
  2. package/dist/autopilot/campaign.d.ts +9 -2
  3. package/dist/autopilot/campaign.d.ts.map +1 -1
  4. package/dist/autopilot/campaign.js +84 -14
  5. package/dist/autopilot/campaign.js.map +1 -1
  6. package/dist/autopilot/design.d.ts +77 -0
  7. package/dist/autopilot/design.d.ts.map +1 -0
  8. package/dist/autopilot/design.js +234 -0
  9. package/dist/autopilot/design.js.map +1 -0
  10. package/dist/autopilot/estimate-texts.d.ts +6 -0
  11. package/dist/autopilot/estimate-texts.d.ts.map +1 -1
  12. package/dist/autopilot/estimate-texts.js +20 -7
  13. package/dist/autopilot/estimate-texts.js.map +1 -1
  14. package/dist/autopilot/estimate.d.ts +29 -1
  15. package/dist/autopilot/estimate.d.ts.map +1 -1
  16. package/dist/autopilot/estimate.js +98 -32
  17. package/dist/autopilot/estimate.js.map +1 -1
  18. package/dist/autopilot/frozen.d.ts +2 -0
  19. package/dist/autopilot/frozen.d.ts.map +1 -1
  20. package/dist/autopilot/frozen.js.map +1 -1
  21. package/dist/autopilot/outline-check.d.ts +9 -0
  22. package/dist/autopilot/outline-check.d.ts.map +1 -1
  23. package/dist/autopilot/outline-check.js +16 -0
  24. package/dist/autopilot/outline-check.js.map +1 -1
  25. package/dist/autopilot/outline-compose.d.ts +3 -3
  26. package/dist/autopilot/outline-compose.d.ts.map +1 -1
  27. package/dist/autopilot/outline-compose.js +4 -4
  28. package/dist/autopilot/outline-compose.js.map +1 -1
  29. package/dist/autopilot/planner.d.ts +10 -10
  30. package/dist/autopilot/planner.d.ts.map +1 -1
  31. package/dist/autopilot/planner.js +220 -37
  32. package/dist/autopilot/planner.js.map +1 -1
  33. package/dist/autopilot/prompts.d.ts +18 -0
  34. package/dist/autopilot/prompts.d.ts.map +1 -1
  35. package/dist/autopilot/prompts.js +163 -0
  36. package/dist/autopilot/prompts.js.map +1 -1
  37. package/dist/autopilot/review-policy.d.ts +25 -5
  38. package/dist/autopilot/review-policy.d.ts.map +1 -1
  39. package/dist/autopilot/review-policy.js +84 -2
  40. package/dist/autopilot/review-policy.js.map +1 -1
  41. package/dist/autopilot/review-readers.d.ts +69 -0
  42. package/dist/autopilot/review-readers.d.ts.map +1 -0
  43. package/dist/autopilot/review-readers.js +79 -0
  44. package/dist/autopilot/review-readers.js.map +1 -0
  45. package/dist/autopilot/runner.d.ts.map +1 -1
  46. package/dist/autopilot/runner.js +22 -3
  47. package/dist/autopilot/runner.js.map +1 -1
  48. package/dist/autopilot/state.d.ts +20 -1
  49. package/dist/autopilot/state.d.ts.map +1 -1
  50. package/dist/autopilot/state.js +139 -5
  51. package/dist/autopilot/state.js.map +1 -1
  52. package/dist/autopilot/tasks.d.ts +3 -1
  53. package/dist/autopilot/tasks.d.ts.map +1 -1
  54. package/dist/autopilot/tasks.js +509 -67
  55. package/dist/autopilot/tasks.js.map +1 -1
  56. package/dist/autopilot/types.d.ts +164 -8
  57. package/dist/autopilot/types.d.ts.map +1 -1
  58. package/dist/autopilot/types.js +6 -0
  59. package/dist/autopilot/types.js.map +1 -1
  60. package/dist/book/design.d.ts +265 -0
  61. package/dist/book/design.d.ts.map +1 -0
  62. package/dist/book/design.js +632 -0
  63. package/dist/book/design.js.map +1 -0
  64. package/dist/book/outline.d.ts +20 -4
  65. package/dist/book/outline.d.ts.map +1 -1
  66. package/dist/book/outline.js +46 -9
  67. package/dist/book/outline.js.map +1 -1
  68. package/dist/index.d.ts +3 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +3 -0
  71. package/dist/index.js.map +1 -1
  72. package/dist/server/client.d.ts +2 -1
  73. package/dist/server/client.d.ts.map +1 -1
  74. package/dist/server/client.js +15 -3
  75. package/dist/server/client.js.map +1 -1
  76. package/dist/server/protocol.d.ts +28 -0
  77. package/dist/server/protocol.d.ts.map +1 -1
  78. package/dist/server/protocol.js +34 -0
  79. package/dist/server/protocol.js.map +1 -1
  80. package/dist/testing/index.d.ts +2 -0
  81. package/dist/testing/index.d.ts.map +1 -1
  82. package/dist/testing/index.js +67 -0
  83. package/dist/testing/index.js.map +1 -1
  84. package/dist/version.d.ts +1 -1
  85. package/dist/version.js +1 -1
  86. package/package.json +1 -1
@@ -1,9 +1,10 @@
1
1
  import { normalizeScore, requireStructuredFields, splitReasoningBlock } from "../ai/structured.js";
2
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";
3
+ import { canonDetails, activeReaders, canonManifest, ghostwriterBlock, isThinDocument, loadChapterParagraphs, loadGhostwriter, markedChapterText, mentionedCanon, readBody, readDocument, referencedChapterNumber, secretRules, } from "../book/context.js";
4
4
  import { AUTOPILOT_PLAN_FILE, BOOK_FILE, CONTEXT_FILE, OUTLINE_BOOK_FILE, OUTLINE_CHANGES_FILE, PLOT_FILE, STORY_DESIGN_FILE, TOTAL_RESUME_FILE, canonPath, canonSlug, chapterFilePath, chapterResumePath, chapterSlug, directorOpinionPath, formatOrdinal, isValidGhostwriterSlug, outlineChapterPath, paragraphFilePath, paragraphId, paragraphSlug, readerEvaluationPath, readerSummaryPath, } from "../book/paths.js";
5
5
  import { chapterFreezeRecord, freezeChapterChanges, frozenChanges, markReviewedChanges } from "../book/freeze.js";
6
- import { OUTLINE_TITLE_MAX_CHARS, OutlineReader, outlineBookDigest, outlineEntryDigest, serializeOutlineBook, serializeOutlineChapter } from "../book/outline.js";
6
+ import { OUTLINE_TITLE_MAX_CHARS, OutlineReader, outlineBookDigest, outlineDesignOf, outlineEntryDigest, serializeOutlineBook, serializeOutlineChapter, wholeDesignPatch } from "../book/outline.js";
7
+ import { BIBLE_THEMES_FILE, BIBLE_WORLD_FILE, designChecks, designFindingText, designText, mergeSecretLedger, normalizeDesignPatch, readBibleThemes, readBibleWorld, readSecretLedger, secretLedgerDigest, secretLedgerFrontmatter, serializeBibleThemes, serializeBibleWorld, } from "../book/design.js";
7
8
  import { appendOutlineJournal, outlineJournalChaptersOf } from "../book/outline-journal.js";
8
9
  import { askDirector, directorSystemPrompt, parseDirectorVerdict, renderDirectorOpinion, withheldApprovalNote } from "../director/opinion.js";
9
10
  import { assertFrontmatterReadable, frontmatterString, parseMarkdown, renderMarkdown } from "../markdown/frontmatter.js";
@@ -16,10 +17,13 @@ import { asArray, asInteger, asOneOf, asRecord, asString, asStringList } from ".
16
17
  import { bulletList, clipText, countWords, isItalian, languageName, OUTPUT_TOKENS_CEILING, sceneCharacterLimit, scaleOutputTokens, tokensPerWord, truncate } from "../util/text.js";
17
18
  import { chapterLines, layoutChapters, listSection, outlineList } from "./outline.js";
18
19
  import { legacyChapters, queuedMarkReviewed, startedReview } from "./frozen.js";
19
- import { reviewMaxRounds, reviewTarget } from "./review-policy.js";
20
- import { SCENES_PER_CHAPTER, batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts, sceneFile, scenesForChapter } from "./planner.js";
21
- 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";
22
- import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES, CONCEPT_LOGLINE_CHARACTERS, closedRound, normalizeFinalReview, recordChapterRound } from "./state.js";
20
+ import { readerGate, reviewMaxRounds, reviewReaderTargets, reviewTarget } from "./review-policy.js";
21
+ import { blockersText, readerStanding } from "./review-readers.js";
22
+ import { PLAN_BATCH_CHAPTERS, SCENES_PER_CHAPTER, batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts, sceneFile, scenesForChapter } from "./planner.js";
23
+ import { designFindingsInsight, designLastRound, designPlateau, designReaderRounds, designTarget, endDesign, loadDesignCheckInput, planBatchChapters } from "./design.js";
24
+ import { outlineDesignGaps } from "./outline-check.js";
25
+ import { CHAPTER_REVIEW_TOOL, CHAPTER_SUMMARY_TOOL, CONCEPT_TOOL, CONSOLIDATION_TOOL, DESIGN_ARCHITECT_ROLE, DESIGN_CHAPTER_RULE, DESIGN_CONCEPT_TOOL, DESIGN_DIRECTOR_RULES, DESIGN_LEDGER_RULE, DESIGN_PLAN_TOOL, DESIGN_REACTION_TOOL, DESIGN_READER_ROLE, DESIGN_REVIEW_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";
26
+ import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES, CONCEPT_LOGLINE_CHARACTERS, closedRound, designActive, designMaxRounds, normalizeFinalReview, readingRound, recordChapterRound } from "./state.js";
23
27
  import { STORY_SO_FAR_MAX_WORDS, STORY_SO_FAR_TARGET_WORDS, pruneStorySnapshots, readStorySoFar, renderTotalResumeBody, storySoFarExcess } from "./story-so-far.js";
24
28
  // ─── Shared prompt fragments ────────────────────────────────────────────────
25
29
  function bookHeader(ctx) {
@@ -185,8 +189,9 @@ function outlineGhostwriter(ctx, entry) {
185
189
  return undefined;
186
190
  }
187
191
  /** What the autopilot writes in the outline for a chapter: its title, then its summary and its key events as a list. */
188
- function outlineContentOf(chapter) {
189
- const body = [chapter.summary.trim(), chapter.keyEvents.length ? bulletList(chapter.keyEvents) : ""].filter(Boolean).join("\n\n");
192
+ function outlineContentOf(chapter, design) {
193
+ // A designed chapter keeps its events in its design: the text says what happens, once.
194
+ const body = [chapter.summary.trim(), chapter.keyEvents.length && !design ? bulletList(chapter.keyEvents) : ""].filter(Boolean).join("\n\n");
190
195
  return { title: chapter.title, body, ...(chapter.ghostwriter ? { ghostwriter: chapter.ghostwriter } : {}) };
191
196
  }
192
197
  /**
@@ -198,20 +203,24 @@ function outlineContentOf(chapter) {
198
203
  * written. `outline/book.md` is written once, when it is missing, with the logline of the concept. The entries it writes are a series
199
204
  * of the journal of the Synopsis (`outline/changes.yml`), by the autopilot, in the same commit.
200
205
  */
201
- async function fillOutline(ctx, planned, imported) {
202
- const fill = ctx.state.options.fillOutline !== false;
206
+ async function fillOutline(ctx, planned, imported, designs) {
207
+ // A design lives in the entries of the Synopsis: a design run writes them whatever `fillOutline` says.
208
+ const fill = ctx.state.options.fillOutline !== false || designActive(ctx.state);
203
209
  const outline = outlineOf(ctx);
204
210
  const entries = new Map((await outline.chapters()).map((entry) => [entry.number, entry]));
205
211
  const changes = [];
206
212
  const was = new Map();
207
213
  const now = new Map();
208
214
  const write = async (chapter, existing) => {
209
- const content = outlineContentOf(chapter);
210
- const digest = await outlineEntryDigest(content);
215
+ const design = designs?.get(chapter.number);
216
+ const content = outlineContentOf(chapter, design);
217
+ // The design of the plan replaces the whole design of an entry of the autopilot; without one, the entry keeps the design it has.
218
+ const patch = design ? wholeDesignPatch(design) : undefined;
219
+ const digest = await outlineEntryDigest({ ...content, design: outlineDesignOf({ design: patch, frontmatter: existing?.frontmatter }) });
211
220
  if (!existing || digest !== existing.contentDigest) {
212
221
  changes.push({
213
222
  path: existing?.path ?? outlineChapterPath(chapter.number),
214
- content: serializeOutlineChapter({ number: chapter.number, ...content, origin: "autopilot", digest, frontmatter: existing?.frontmatter }),
223
+ content: serializeOutlineChapter({ number: chapter.number, ...content, ...(patch ? { design: patch } : {}), origin: "autopilot", digest, frontmatter: existing?.frontmatter }),
215
224
  expectedHash: existing ? existing.hash : null,
216
225
  });
217
226
  if (existing)
@@ -475,13 +484,19 @@ async function runConcept(ctx) {
475
484
  assertFrontmatterReadable(STORY_DESIGN_FILE, design.document, ctx.language);
476
485
  if (context && isThinDocument(context.document.body))
477
486
  assertFrontmatterReadable(CONTEXT_FILE, context.document, ctx.language);
487
+ // A design run asks for more of the foundation: the relationships of the cast, the items that matter, the rules of the world, what each secret changes.
488
+ const designing = designActive(ctx.state);
478
489
  const response = await ctx.ai({
479
490
  capability: AI_CAPABILITIES.writer,
480
491
  label: "autopilot:concept",
481
- system: architectSystemPrompt(ctx.language),
492
+ system: designing ? `${architectSystemPrompt(ctx.language)}\n\n${DESIGN_ARCHITECT_ROLE}` : architectSystemPrompt(ctx.language),
482
493
  user: `${request([
483
- `Design the foundation of this novel from the author's brief, for about ${view.lastChapter} chapters.`,
484
- "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.",
494
+ designing
495
+ ? `Design the foundation of this novel from the author's description, for about ${view.lastChapter} chapters: no prose, only the design a writer needs.`
496
+ : `Design the foundation of this novel from the author's brief, for about ${view.lastChapter} chapters.`,
497
+ designing
498
+ ? "Create 3 to 8 characters with clear desires, fears, arcs and relationships, the key locations, factions only when useful, the items that matter, the rules of the world, and 1 to 5 secrets that drive the plot, each with its truth, who knows it, the chapter where the reader learns it and its consequences."
499
+ : "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.",
485
500
  ctx.state.brief.synopsis ? "The author's chapter-by-chapter synopsis is binding: the concept must make it possible exactly as written." : "",
486
501
  view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) is binding too, and wins over the synopsis: the concept must make it possible exactly as written." : "",
487
502
  "Reuse the existing canon names instead of duplicating them.",
@@ -497,8 +512,8 @@ async function runConcept(ctx) {
497
512
  ctx.snapshot.canon.length ? `EXISTING CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true })}` : "",
498
513
  `DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
499
514
  ])}`,
500
- json: CONCEPT_TOOL,
501
- maxOutputTokens: outputLimit(ctx, 9000),
515
+ json: designing ? DESIGN_CONCEPT_TOOL : CONCEPT_TOOL,
516
+ maxOutputTokens: outputLimit(ctx, designing ? 12000 : 9000),
502
517
  temperature: 0.8,
503
518
  });
504
519
  const output = requireStructuredFields(response.json, { storyDesign: "text" }, "The concept");
@@ -544,9 +559,13 @@ async function runConcept(ctx) {
544
559
  else
545
560
  counts.other += 1;
546
561
  const label = kind === "secret" ? { title: name } : { name };
547
- changes.push({ path, content: renderMarkdown({ type: kind, id: `${kind}:${slug}`, ...label, ...frontmatter, canon: "draft" }, body), expectedHash: null });
562
+ const content = renderMarkdown({ type: kind, id: `${kind}:${slug}`, ...label, ...frontmatter, canon: "draft" }, body);
563
+ changes.push({ path, content, expectedHash: null });
564
+ created.set(path, content);
548
565
  return slug;
549
566
  };
567
+ /** The files this step creates, by path, as it writes them. */
568
+ const created = new Map();
550
569
  const characterSlug = (name) => known.find((entry) => entry.kind === "character" && sameCanonEntity("character", name, entry.names))?.slug ?? canonSlug("character", name);
551
570
  const characters = asArray(output.characters).slice(0, 10).map(asRecord);
552
571
  for (const character of characters) {
@@ -561,6 +580,7 @@ async function runConcept(ctx) {
561
580
  arc: asString(character.arc) || undefined,
562
581
  desires: asString(character.desire) ? [asString(character.desire)] : undefined,
563
582
  fears: asString(character.fear) ? [asString(character.fear)] : undefined,
583
+ relationships: designing && asStringList(character.relationships, 12).length ? asStringList(character.relationships, 12) : undefined,
564
584
  }, `# ${name}\n\n${asString(character.description)}`);
565
585
  }
566
586
  for (const location of asArray(output.locations).slice(0, 10).map(asRecord)) {
@@ -573,16 +593,43 @@ async function runConcept(ctx) {
573
593
  if (name)
574
594
  create("faction", name, { mission: asString(faction.mission) || undefined }, `# ${name}\n\n${asString(faction.description)}`);
575
595
  }
596
+ if (designing) {
597
+ for (const item of asArray(output.items).slice(0, 8).map(asRecord)) {
598
+ const name = asString(item.name);
599
+ if (name)
600
+ create("item", name, { significance: asString(item.significance) || undefined }, `# ${name}\n\n${asString(item.description)}`);
601
+ }
602
+ }
576
603
  const secrets = [];
577
604
  for (const secret of asArray(output.secrets).slice(0, 8).map(asRecord)) {
578
605
  const title = asString(secret.title);
579
606
  if (!title)
580
607
  continue;
581
608
  const holders = asStringList(secret.holders, 10).map((holder) => `character:${characterSlug(holder)}`);
582
- const slug = create("secret", title, { holders, stakes: asString(secret.stakes) || undefined, status: "hidden" }, `# ${title}\n\n${asString(secret.truth)}`);
609
+ const consequences = designing ? asStringList(secret.consequences, 12) : [];
610
+ const slug = create("secret", title, { holders, stakes: asString(secret.stakes) || undefined, status: "hidden", ...(consequences.length ? { consequences } : {}) }, `# ${title}\n\n${asString(secret.truth)}`);
583
611
  const revealChapter = asInteger(secret.revealChapter, 0, 0, MAX_BOOK_CHAPTERS);
584
612
  secrets.push({ slug, title, revealChapter: revealChapter || undefined });
585
613
  }
614
+ if (designing) {
615
+ // The ledgers this step wrote are the design's: a later step may rewrite them while nobody changes them.
616
+ const ledgers = { ...(ctx.state.design.ledgers ?? {}) };
617
+ for (const secret of secrets) {
618
+ const path = canonPath("secret", secret.slug);
619
+ const content = created.get(path);
620
+ if (content)
621
+ ledgers[path] = await secretLedgerDigest(parseMarkdown(content).frontmatter);
622
+ }
623
+ ctx.state.design.ledgers = ledgers;
624
+ // The themes, the tone and the rules of the world have no other home: `bible/` gets them when it has none.
625
+ const themes = asStringList(output.themes, 12);
626
+ const tone = asString(output.tone);
627
+ if ((themes.length || tone) && !ctx.snapshot.files.has(BIBLE_THEMES_FILE))
628
+ changes.push({ path: BIBLE_THEMES_FILE, content: serializeBibleThemes({ themes, tone }), expectedHash: null });
629
+ const rules = asStringList(output.worldRules, 20);
630
+ if (rules.length && !ctx.snapshot.files.has(BIBLE_WORLD_FILE))
631
+ changes.push({ path: BIBLE_WORLD_FILE, content: serializeBibleWorld({ rules }), expectedHash: null });
632
+ }
586
633
  // The pitch of the book, kept for the description of the outline that the plan writes when the author has none.
587
634
  const pitch = clipText(logline || asString(output.premise), CONCEPT_LOGLINE_CHARACTERS).trim();
588
635
  ctx.state.concept = { done: true, generated: true, secrets, ...(pitch ? { logline: pitch } : {}) };
@@ -688,7 +735,10 @@ async function runPlan(ctx) {
688
735
  const view = await authorOutline(ctx);
689
736
  const target = view.lastChapter;
690
737
  const range = planRange(imported, target);
691
- const batch = nextPlanBatch(previous, range);
738
+ // A design run plans fewer chapters a call: it says much more of each.
739
+ const designing = designActive(ctx.state);
740
+ const size = planBatchChapters(ctx.state, PLAN_BATCH_CHAPTERS);
741
+ const batch = nextPlanBatch(previous, range, size);
692
742
  if (!batch)
693
743
  throw new Error("There is no chapter left to plan.");
694
744
  const { start: startNumber, last: lastNumber } = range;
@@ -710,14 +760,19 @@ async function runPlan(ctx) {
710
760
  const plannedNumbers = new Set((previous?.chapters ?? []).map((chapter) => chapter.number));
711
761
  const unlisted = view.any ? Array.from({ length: batchCount }, (_, index) => from + index).filter((number) => !view.entries.has(number)) : [];
712
762
  const ahead = [...view.entries.values()].filter((entry) => entry.number >= startNumber && (entry.number < from || entry.number > to) && !plannedNumbers.has(entry.number));
763
+ const designData = designing ? await designContext(ctx) : null;
713
764
  const response = await ctx.ai({
714
765
  capability: AI_CAPABILITIES.writer,
715
766
  label: "autopilot:plan",
716
- system: architectSystemPrompt(ctx.language),
767
+ system: designing ? `${architectSystemPrompt(ctx.language)}\n\n${DESIGN_ARCHITECT_ROLE}` : architectSystemPrompt(ctx.language),
717
768
  user: `${request([
718
- revising
719
- ? `Revise the chapter plan (chapters ${from}-${to}) applying the director's changes:\n${bulletList(notes)}`
720
- : `Plan the next ${batchCount} chapters of the novel, numbered ${from} to ${to}.`,
769
+ designing
770
+ ? (revising ? `Revise the design of chapters ${from}-${to} applying the director's changes:\n${bulletList(notes)}` : `Design the next ${batchCount} chapters of the novel, numbered ${from} to ${to}.`)
771
+ : revising
772
+ ? `Revise the chapter plan (chapters ${from}-${to}) applying the director's changes:\n${bulletList(notes)}`
773
+ : `Plan the next ${batchCount} chapters of the novel, numbered ${from} to ${to}.`,
774
+ designing ? DESIGN_CHAPTER_RULE : "",
775
+ designing ? DESIGN_LEDGER_RULE : "",
721
776
  batched ? `The novel will have ${target} chapters in all and is planned in batches: this call covers only chapters ${from} to ${to}.` : "",
722
777
  batched ? (to < lastNumber ? `The story must not end before chapter ${lastNumber}: leave room for what the following chapters have to tell.` : `These are the last chapters of the book: close its arcs and end the story in chapter ${lastNumber}.`) : "",
723
778
  batched && revising ? `Apply only the changes that concern chapters ${from} to ${to} or the whole book: the other chapters are revised in their own call. Return every chapter of the range.` : "",
@@ -742,31 +797,48 @@ async function runPlan(ctx) {
742
797
  resume ? `STORY SO FAR (before chapter ${startNumber}):\n${resume}` : "",
743
798
  batched ? (otherChapters?.chapters.length ? listSection(`PLAN SO FAR (the planned chapters outside ${from}-${to})`, outlineList(otherChapters, { around: from })) : "") : revising ? listSection("CURRENT PLAN", outlineList(previous, { around: startNumber })) : "",
744
799
  batched && revising ? `CURRENT VERSION OF CHAPTERS ${from}-${to} (revise it):\n${existing.map(chapterPlanBlock).join("\n\n")}` : "",
800
+ designing && revising ? await designedEntriesSection(ctx, from, to, `THE DESIGN OF CHAPTERS ${from}-${to} NOW (revise it)`) : "",
801
+ ...(designData ? designData.sections : []),
745
802
  `DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
746
803
  ])}`,
747
- json: PLAN_TOOL,
748
- maxOutputTokens: outputLimit(ctx, 9000),
804
+ json: designing ? DESIGN_PLAN_TOOL : PLAN_TOOL,
805
+ maxOutputTokens: outputLimit(ctx, designing ? 4000 + 1500 * batchCount : 9000),
749
806
  temperature: 0.7,
750
807
  });
751
- const output = requireStructuredFields(response.json, { chapters: "list" }, "The chapter plan");
808
+ const output = requireStructuredFields(response.json, { chapters: "list" }, designing ? "The design of the chapters" : "The chapter plan");
752
809
  const proposed = asArray(output.chapters).map(asRecord).filter((chapter) => asString(chapter.title)).slice(0, batchCount);
753
810
  if (proposed.length < batchCount)
754
811
  throw new AiReplyRejectedError(`The chapter plan has ${proposed.length} chapters with a title, but ${batchCount} were requested (chapters ${from}-${to}).`);
812
+ // A design is checked whole before anything is written: a chapter without its design, or a design over the limits, is sent back to be repaired, never cut.
813
+ const designs = new Map();
814
+ if (designing) {
815
+ proposed.forEach((chapter, index) => {
816
+ const number = from + index;
817
+ const { patch, problems } = normalizeDesignPatch(asRecord(chapter.design));
818
+ if (problems.length)
819
+ throw new AiReplyRejectedError(`The design of chapter ${number} is over the limits (${problems.join("; ")}): return it shorter, whole.`);
820
+ const design = Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== null && value !== undefined));
821
+ if (!design.goal || !design.events?.length)
822
+ throw new AiReplyRejectedError(`The design of chapter ${number} has no narrative goal or no main events: return every chapter with its whole design.`);
823
+ designs.set(number, design);
824
+ });
825
+ }
755
826
  const planned = proposed.map((chapter, index) => {
756
827
  const number = from + index;
757
828
  // The hypothetical title of the author's entry is the chapter's: the model refines a title only where the entry has none.
758
829
  const entry = view.entries.get(number);
759
830
  const title = entry?.title ? clipText(entry.title, OUTLINE_TITLE_MAX_CHARS).trim() : asString(chapter.title);
760
831
  const ghostwriter = outlineGhostwriter(ctx, entry);
832
+ const design = designs.get(number);
761
833
  return {
762
834
  number,
763
835
  title,
764
836
  slug: chapterSlug(number, title),
765
837
  summary: asString(chapter.summary),
766
- goal: asString(chapter.goal),
767
- pov: asStringList(chapter.pov, 6),
768
- keyEvents: asStringList(chapter.keyEvents, 12),
769
- reveals: asStringList(chapter.reveals, 8),
838
+ goal: design ? design.goal ?? "" : asString(chapter.goal),
839
+ pov: design ? (design.pov ?? []).slice(0, 6) : asStringList(chapter.pov, 6),
840
+ keyEvents: design ? (design.events ?? []).slice(0, 12) : asStringList(chapter.keyEvents, 12),
841
+ reveals: design ? (design.reveals ?? []).slice(0, 8) : asStringList(chapter.reveals, 8),
770
842
  status: "planned",
771
843
  scenes: [],
772
844
  ...(ghostwriter ? { ghostwriter } : {}),
@@ -794,7 +866,7 @@ async function runPlan(ctx) {
794
866
  revisionNotes = [];
795
867
  }
796
868
  else if (revising) {
797
- const pending = revisionBatchStarts(previous, range).filter((start) => start !== from);
869
+ const pending = revisionBatchStarts(previous, range, size).filter((start) => start !== from);
798
870
  if (pending.length)
799
871
  revisionBatches = pending;
800
872
  else
@@ -819,7 +891,16 @@ async function runPlan(ctx) {
819
891
  ...(previous?.removedChapters?.length ? { removedChapters: previous.removedChapters } : {}),
820
892
  };
821
893
  // The outline is filled from the plan in the same commit: what the author did not write, the author can now correct.
822
- changes.push(...await fillOutline(ctx, planned, imported));
894
+ changes.push(...await fillOutline(ctx, planned, imported, designs));
895
+ if (designing) {
896
+ changes.push(...await designLedgerChanges(ctx, asArray(output.secrets).map(asRecord), from, to));
897
+ // The entries of the author bind the design as they bind a plan: they are never rewritten, and the author is told which they are.
898
+ const yours = planned.filter((chapter) => view.entries.has(chapter.number)).map((chapter) => chapter.number);
899
+ if (yours.length) {
900
+ const italian = isItalian(ctx.language);
901
+ ctx.insight("info", italian ? `${yours.length === 1 ? "La voce" : "Le voci"} ${yours.join(", ")} della Sinossi ${yours.length === 1 ? "è tua" : "sono tue"}: il progetto le segue e non le riscrive` : `The ${yours.length === 1 ? "entry" : "entries"} ${yours.join(", ")} of the Synopsis ${yours.length === 1 ? "is" : "are"} yours: the design follows ${yours.length === 1 ? "it" : "them"} and does not rewrite ${yours.length === 1 ? "it" : "them"}`, italian ? "Per dare loro un progetto, compila la sezione «Progetto» della voce, o chiedi al Brainstorming di proporlo." : "To give them a design, fill the «Design» section of the entry, or ask the Brainstorming to propose one.", { code: "designAuthorEntries" });
902
+ }
903
+ }
823
904
  changes.push(await planFileChange(ctx));
824
905
  // A batch of a long plan is reported under the chapters it covers; a short book's only batch, as ever, under their number.
825
906
  const italian = isItalian(ctx.language);
@@ -835,6 +916,123 @@ async function runPlan(ctx) {
835
916
  summary: batched ? `${single ? "Chapter" : "Chapters"} ${covered}: ${list}` : list,
836
917
  };
837
918
  }
919
+ // ─── The design of the book (`AutopilotDesign`) ─────────────────────────────
920
+ /** Characters of the designs of the chapters a prompt quotes, in all: the neighbourhood of what is designed keeps the most. */
921
+ const DESIGN_ENTRIES_CHARS = 16_000;
922
+ /**
923
+ * What every step of a design reads besides a plan's: the themes and the tone, the rules of the world (`bible/`), the secrets with their ledger, and the ghostwriter
924
+ * who will write the book (so that the design fits a voice it can be written in).
925
+ */
926
+ async function designContext(ctx) {
927
+ const [themesFile, worldFile, secrets, ghostwriter] = await Promise.all([
928
+ ctx.store.read(BIBLE_THEMES_FILE),
929
+ ctx.store.read(BIBLE_WORLD_FILE),
930
+ secretsLedgerBlock(ctx),
931
+ loadGhostwriter(ctx.store, ctx.snapshot).catch(() => null),
932
+ ]);
933
+ const themes = readBibleThemes(themesFile?.content);
934
+ const world = readBibleWorld(worldFile?.content);
935
+ return {
936
+ sections: [
937
+ themes.themes.length || themes.tone ? `THEMES AND TONE:\n${[themes.themes.length ? `Themes: ${themes.themes.join("; ")}` : "", themes.tone ? `Tone: ${themes.tone}` : ""].filter(Boolean).join("\n")}` : "",
938
+ world.rules.length ? `RULES OF THE WORLD (never broken):\n${bulletList(world.rules)}` : "",
939
+ secrets ? `SECRETS AND THEIR LEDGER:\n${secrets}` : "",
940
+ ghostwriter ? `GHOSTWRITER WHO WILL WRITE THE BOOK (design what this voice can write well):\n${truncate(ghostwriterBlock(ghostwriter), 1500)}` : "",
941
+ ].filter(Boolean),
942
+ };
943
+ }
944
+ /** The secrets of the book with their truth and their ledger, a few lines each, for the steps of a design. */
945
+ async function secretsLedgerBlock(ctx) {
946
+ const planned = new Map(ctx.state.concept.secrets.map((secret) => [secret.slug, secret.revealChapter]));
947
+ const lines = await Promise.all(ctx.snapshot.canon.filter((entry) => entry.kind === "secret").slice(0, 20).map(async (entry) => {
948
+ const file = await ctx.store.read(entry.path);
949
+ if (!file)
950
+ return "";
951
+ const document = parseMarkdown(file.content);
952
+ const { ledger } = readSecretLedger(document.frontmatter);
953
+ const holders = Array.isArray(document.frontmatter.holders) ? document.frontmatter.holders.filter((item) => typeof item === "string") : [];
954
+ const reveal = referencedChapterNumber(entry.revealIn) ?? planned.get(entry.slug);
955
+ const notes = (label, items) => (items.length ? `${label}: ${items.map((item) => `ch. ${item.chapter} ${truncate(item.note, 120)}`).join("; ")}` : "");
956
+ return [
957
+ `- ${entry.name}: ${truncate(document.body.replace(/^#[^\n]*\n+/, "").replace(/\s+/g, " ").trim(), 300) || "(no truth written)"}`,
958
+ holders.length ? ` Known from the start by: ${holders.join(", ")}` : "",
959
+ ledger.learnedBy.length ? ` Learned by: ${ledger.learnedBy.map((item) => `${item.character} (ch. ${item.chapter})`).join(", ")}` : "",
960
+ reveal ? ` Revealed to the reader in chapter ${reveal}` : " Not placed yet: it needs a reveal chapter",
961
+ notes(" Clues", ledger.clues),
962
+ notes(" Red herrings", ledger.redHerrings),
963
+ ledger.consequences.length ? ` Consequences: ${ledger.consequences.join("; ")}` : "",
964
+ ].filter(Boolean).join("\n");
965
+ }));
966
+ return lines.filter(Boolean).join("\n");
967
+ }
968
+ /** The designs the entries of the Synopsis have for chapters `from` to `to` (all of them without a range), a block each, within the share of a prompt. */
969
+ async function designedEntriesSection(ctx, from, to, label) {
970
+ const entries = (await outlineOf(ctx).chapters()).filter((entry) => entry.design && (from === undefined || entry.number >= from) && (to === undefined || entry.number <= to));
971
+ if (!entries.length)
972
+ return "";
973
+ const share = Math.max(400, Math.floor(DESIGN_ENTRIES_CHARS / entries.length));
974
+ return `${label}:\n${entries.map((entry) => `Chapter ${entry.number}${entry.title ? ` «${entry.title}»` : ""}:\n${designText(entry.design, share)}`).join("\n\n")}`;
975
+ }
976
+ /** A ledger item of the model as the engine keeps it: a whole chapter from 0 and a note (or a character), or nothing. */
977
+ function ledgerNotes(value) {
978
+ return asArray(value).map(asRecord).map((item) => ({ chapter: asInteger(item.chapter, -1, -1, MAX_BOOK_CHAPTERS), note: asString(item.note) })).filter((item) => item.chapter >= 0 && item.note);
979
+ }
980
+ /**
981
+ * The ledgers of the secrets as the design of chapters `from` to `to` places them: the chapter that reveals each secret (in `state.concept.secrets`, which the approval
982
+ * of the plan writes as `reveal_in`), and, in the files of the secrets whose ledger the design owns (it wrote it, and nobody changed it since: `AutopilotDesign.ledgers`),
983
+ * what falls in those chapters. A secret of the author's keeps its ledger, and the author is told.
984
+ */
985
+ async function designLedgerChanges(ctx, items, from, to) {
986
+ const design = ctx.state.design;
987
+ const ledgers = { ...(design.ledgers ?? {}) };
988
+ const changes = [];
989
+ const kept = [];
990
+ const characters = ctx.snapshot.canon.filter((entry) => entry.kind === "character");
991
+ const characterRef = (name) => {
992
+ const found = characters.find((entry) => sameCanonEntity("character", name, [entry.name, ...entry.aliases]));
993
+ return found ? `character:${found.slug}` : name.trim();
994
+ };
995
+ for (const item of items) {
996
+ const title = asString(item.title);
997
+ const secret = ctx.snapshot.canon.find((entry) => entry.kind === "secret" && sameCanonEntity("secret", title, [entry.name, ...entry.aliases]));
998
+ if (!secret)
999
+ continue;
1000
+ const reveal = asInteger(item.revealChapter, 0, 0, MAX_BOOK_CHAPTERS);
1001
+ const planned = ctx.state.concept.secrets.find((entry) => entry.slug === secret.slug);
1002
+ if (planned && reveal > 0 && (reveal >= from && reveal <= to || !planned.revealChapter))
1003
+ planned.revealChapter = reveal;
1004
+ const learnedBy = asArray(item.learnedBy).map(asRecord)
1005
+ .map((entry) => ({ character: characterRef(asString(entry.character)), chapter: asInteger(entry.chapter, -1, -1, MAX_BOOK_CHAPTERS) }))
1006
+ .filter((entry) => entry.character && entry.chapter >= 0);
1007
+ const batch = { learnedBy, readerKnows: ledgerNotes(item.readerKnows), clues: ledgerNotes(item.clues), redHerrings: ledgerNotes(item.redHerrings) };
1008
+ const file = await ctx.store.read(secret.path);
1009
+ if (!file)
1010
+ continue;
1011
+ const document = parseMarkdown(file.content);
1012
+ if (document.error) {
1013
+ kept.push(secret.name);
1014
+ continue;
1015
+ }
1016
+ const owned = ledgers[secret.path] !== undefined && ledgers[secret.path] === await secretLedgerDigest(document.frontmatter);
1017
+ if (!owned) {
1018
+ kept.push(secret.name);
1019
+ continue;
1020
+ }
1021
+ const merged = mergeSecretLedger(readSecretLedger(document.frontmatter).ledger, batch, from, to);
1022
+ const frontmatter = { ...document.frontmatter, ...secretLedgerFrontmatter(merged) };
1023
+ const content = renderMarkdown(frontmatter, document.body);
1024
+ if (content === file.content)
1025
+ continue;
1026
+ changes.push({ path: secret.path, content, expectedHash: file.hash });
1027
+ ledgers[secret.path] = await secretLedgerDigest(parseMarkdown(content).frontmatter);
1028
+ }
1029
+ design.ledgers = ledgers;
1030
+ if (kept.length) {
1031
+ const italian = isItalian(ctx.language);
1032
+ ctx.insight("info", italian ? `Il registro ${kept.length === 1 ? "del segreto" : "dei segreti"} ${kept.map((name) => `«${name}»`).join(", ")} è tuo: il progetto non lo riscrive` : `The ledger of ${kept.map((name) => `«${name}»`).join(", ")} is yours: the design does not rewrite it`, italian ? "Il piano tiene conto di ciò che il progetto propone; il file resta com'è." : "The plan keeps what the design proposes; the file stays as it is.", { code: "designAuthorEntries" });
1033
+ }
1034
+ return changes;
1035
+ }
838
1036
  /** Where a review of the whole plan looks first: the start of what is being planned, not the chapters the author wrote. */
839
1037
  function planFocus(plan) {
840
1038
  return plan.chapters.find((chapter) => !chapter.imported)?.number;
@@ -868,49 +1066,52 @@ async function runPlanReader(ctx) {
868
1066
  return { changes: [], summary: "Reader not available." };
869
1067
  }
870
1068
  const design = await readBody(ctx.store, STORY_DESIGN_FILE, 2500);
1069
+ // A reader of a design reads the design of every chapter, and must contest it as well as judge it.
1070
+ const designing = designActive(ctx.state);
1071
+ const designSections = designing ? [...(await designContext(ctx)).sections.filter((section) => !section.startsWith("GHOSTWRITER")), await designedEntriesSection(ctx, undefined, undefined, "THE DESIGN OF EVERY CHAPTER")] : [];
871
1072
  const asked = await readerReply(ctx, ctx.ai({
872
1073
  capability: AI_CAPABILITIES.reader,
873
1074
  label: `autopilot:plan-reader:${reader.slug}`,
874
- 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.`,
875
- 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([
1075
+ system: designing
1076
+ ? `${readerPersonaSystemPrompt(reader, languageName(ctx.language), "brief")}\n\n${DESIGN_READER_ROLE}`
1077
+ : `${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.`,
1078
+ user: `${request([designing
1079
+ ? "React as this reader: would you read this book? What excites you, what worries you, what is predictable, inconsistent, superfluous or dull, and what would you do instead?"
1080
+ : "React as this reader: would you read this book? What excites you, what worries you, what would you wish for?"])}\n\n${data([
876
1081
  bookHeader(ctx),
877
1082
  ctx.state.brief.idea ? `PITCH:\n${ctx.state.brief.idea}` : "",
878
1083
  design ? `PREMISE:\n${design}` : "",
879
1084
  listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
1085
+ ...designSections,
880
1086
  ])}`,
881
- json: PLAN_REACTION_TOOL,
882
- maxOutputTokens: outputLimit(ctx, 1500),
883
- }), (response) => requireStructuredFields(response.json, { interest: "score", reaction: "text" }, "The reader's reaction"));
1087
+ json: designing ? DESIGN_REACTION_TOOL : PLAN_REACTION_TOOL,
1088
+ maxOutputTokens: outputLimit(ctx, designing ? 2500 : 1500),
1089
+ }), (response) => requireStructuredFields(response.json, designing ? { interest: "score", reaction: "text", counterProposal: "text" } : { interest: "score", reaction: "text" }, "The reader's reaction"));
884
1090
  if ("skipped" in asked) {
885
1091
  plan.skippedReaders = [...new Set([...(plan.skippedReaders ?? []), reader.slug])];
886
1092
  return skipReader(ctx, reader.name, asked.skipped);
887
1093
  }
888
1094
  const output = asked.value;
1095
+ const counterProposal = designing ? asString(output.counterProposal) : "";
889
1096
  const reaction = {
890
1097
  slug: reader.slug,
891
1098
  name: reader.name,
892
1099
  interest: Math.round(Math.max(1, normalizeScore(output.interest) ?? 5)),
893
1100
  reaction: asString(output.reaction),
894
- concerns: asStringList(output.concerns, 8),
895
- wishes: asStringList(output.wishes, 8),
1101
+ concerns: [...asStringList(output.concerns, 8), ...(designing ? asStringList(output.weakSpots, 8) : [])].slice(0, 12),
1102
+ // The counter-proposal of a reader of a design travels with its wishes, so that the director weighs it with the rest.
1103
+ wishes: [...asStringList(output.wishes, 8), ...(counterProposal ? [`${isItalian(ctx.language) ? "Controproposta" : "Counter-proposal"}: ${counterProposal}`] : [])],
896
1104
  };
897
1105
  plan.readerReactions = [...plan.readerReactions.filter((entry) => entry.slug !== reader.slug), reaction];
898
1106
  ctx.insight(reaction.interest >= 7 ? "ok" : reaction.interest >= 5 ? "info" : "warning", `${reader.name}: ${reaction.interest}/10`, reaction.reaction);
899
1107
  return { changes: [], summary: `${reaction.interest}/10 — ${truncate(reaction.reaction, 240)}` };
900
1108
  }
901
1109
  async function runPlanReview(ctx) {
1110
+ if (designActive(ctx.state))
1111
+ return runDesignReview(ctx);
902
1112
  const plan = ctx.state.plan;
903
1113
  // Approving the plan puts the chapter of its reveal into the secrets the concept made that have none: those must be readable first.
904
- const toRewrite = [];
905
- for (const secret of ctx.state.concept.secrets) {
906
- const path = canonPath("secret", secret.slug);
907
- if (!plan.chapters.some((entry) => entry.number === secret.revealChapter) || !ctx.snapshot.files.has(path))
908
- continue;
909
- const file = await ctx.store.read(path);
910
- if (file && !frontmatterString(parseMarkdown(file.content).frontmatter, "reveal_in"))
911
- toRewrite.push(path);
912
- }
913
- await assertRewritable(ctx, toRewrite);
1114
+ await assertRewritable(ctx, await secretsToPlace(ctx, plan));
914
1115
  const [design, view] = await Promise.all([readBody(ctx.store, STORY_DESIGN_FILE, 5000), authorOutline(ctx)]);
915
1116
  const style = evaluationStyleOf(ctx, "plan");
916
1117
  const lastRound = plan.rounds >= 2;
@@ -975,20 +1176,7 @@ async function runPlanReview(ctx) {
975
1176
  delete plan.revisionBatches;
976
1177
  plan.awaitingAuthor = ctx.state.options.pauseAfterPlan || ctx.director.autonomy === "ask-always";
977
1178
  ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, [...guidance, ...(lastRound ? changesRequested : [])]);
978
- for (const chapter of plan.chapters)
979
- if (!chapter.imported)
980
- changes.push(ensureChapterFile(ctx, chapter));
981
- for (const secret of ctx.state.concept.secrets) {
982
- const chapter = plan.chapters.find((entry) => entry.number === secret.revealChapter);
983
- const path = canonPath("secret", secret.slug);
984
- if (!chapter || !ctx.snapshot.files.has(path))
985
- continue;
986
- changes.push(await changeFor(ctx, path, (existing) => {
987
- if (!existing || frontmatterString(existing.frontmatter, "reveal_in"))
988
- return null;
989
- return renderMarkdown({ ...existing.frontmatter, reveal_in: `chapter:${chapter.slug}`, known_from: `chapter:${chapter.slug}` }, existing.body);
990
- }));
991
- }
1179
+ changes.push(...await approvedPlanChanges(ctx, plan));
992
1180
  ctx.insight("ok", isItalian(ctx.language) ? `Piano approvato dal direttore (${score}/10)` : `Plan approved by the director (${score}/10)`, summaryText);
993
1181
  }
994
1182
  const question = asRecord(output.questionForAuthor);
@@ -1005,6 +1193,203 @@ async function runPlanReview(ctx) {
1005
1193
  changes.push(await planFileChange(ctx));
1006
1194
  return { changes: compact(changes), summary: `${approved ? "approve" : "revise"} ${score}/10 — ${summaryText}` };
1007
1195
  }
1196
+ /** The secrets the concept made whose reveal the approval of the plan writes (`reveal_in`, `known_from`): their files must be readable before the review. */
1197
+ async function secretsToPlace(ctx, plan) {
1198
+ const paths = [];
1199
+ for (const secret of ctx.state.concept.secrets) {
1200
+ const path = canonPath("secret", secret.slug);
1201
+ if (!plan.chapters.some((entry) => entry.number === secret.revealChapter) || !ctx.snapshot.files.has(path))
1202
+ continue;
1203
+ const file = await ctx.store.read(path);
1204
+ if (file && !frontmatterString(parseMarkdown(file.content).frontmatter, "reveal_in"))
1205
+ paths.push(path);
1206
+ }
1207
+ return paths;
1208
+ }
1209
+ /** What the approval of a plan writes: the folders of the chapters it plans (their `chapter.md`, no scene), and the chapter of the reveal of the secrets that have none. */
1210
+ async function approvedPlanChanges(ctx, plan) {
1211
+ const changes = [];
1212
+ for (const chapter of plan.chapters)
1213
+ if (!chapter.imported)
1214
+ changes.push(ensureChapterFile(ctx, chapter));
1215
+ for (const secret of ctx.state.concept.secrets) {
1216
+ const chapter = plan.chapters.find((entry) => entry.number === secret.revealChapter);
1217
+ const path = canonPath("secret", secret.slug);
1218
+ if (!chapter || !ctx.snapshot.files.has(path))
1219
+ continue;
1220
+ changes.push(await changeFor(ctx, path, (existing) => {
1221
+ if (!existing || frontmatterString(existing.frontmatter, "reveal_in"))
1222
+ return null;
1223
+ return renderMarkdown({ ...existing.frontmatter, reveal_in: `chapter:${chapter.slug}`, known_from: `chapter:${chapter.slug}` }, existing.body);
1224
+ }));
1225
+ }
1226
+ return changes;
1227
+ }
1228
+ /**
1229
+ * The director's review of a design (`AutopilotDesign`): the plan's review, with the designs of the chapters, the ledgers of the secrets, the world and the findings of
1230
+ * the deterministic checks in the data, and the design's policy (its target, its rounds, the readers' rounds). A score alone never approves: a critical inconsistency
1231
+ * sends the design back, and one still there after the last round (or a plateau) is asked to the author, once; then the design is approved with what is left as
1232
+ * standing guidance. The approval ends the design: the run stops there, and waits for the author.
1233
+ */
1234
+ async function runDesignReview(ctx) {
1235
+ const plan = ctx.state.plan;
1236
+ const design = ctx.state.design;
1237
+ const italian = isItalian(ctx.language);
1238
+ await assertRewritable(ctx, await secretsToPlace(ctx, plan));
1239
+ const outline = outlineOf(ctx);
1240
+ const [storyDesign, view, checkInput, designData, entriesSection] = await Promise.all([
1241
+ readBody(ctx.store, STORY_DESIGN_FILE, 5000),
1242
+ authorOutline(ctx),
1243
+ loadDesignCheckInput(ctx.store, ctx.snapshot, outline, ctx.state),
1244
+ designContext(ctx),
1245
+ designedEntriesSection(ctx, undefined, undefined, "THE DESIGN OF EVERY CHAPTER"),
1246
+ ]);
1247
+ const findings = [...designChecks(checkInput), ...outlineDesignGaps(checkInput.chapters)];
1248
+ const told = designFindingsInsight(findings, ctx.language);
1249
+ if (told)
1250
+ ctx.insight(told.tone, told.title, told.detail, { code: "designChecks" });
1251
+ const style = evaluationStyleOf(ctx, "plan");
1252
+ const target = designTarget(ctx.state, ctx.director);
1253
+ const maxRounds = designMaxRounds(design);
1254
+ const roundNumber = plan.rounds + 1;
1255
+ const lastRound = designLastRound(ctx.state);
1256
+ const response = await ctx.ai({
1257
+ capability: AI_CAPABILITIES.director,
1258
+ label: "autopilot:plan-review",
1259
+ system: directorSystemPrompt(ctx.director, ctx.language),
1260
+ user: `${request([
1261
+ `Review the design of the book before any prose is written (review ${roundNumber} of at most ${Math.max(maxRounds, roundNumber)}).`,
1262
+ `Approve when the design delivers the brief and the vision with a satisfying shape and deserves ${target}/10 or more; otherwise list precise changes chapter by chapter. Weigh the simulated readers by their weights: do not chase every opinion.`,
1263
+ ...DESIGN_DIRECTOR_RULES,
1264
+ view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) binds the design: never ask to change its chapters, their order, their titles or their events; ask only for what enriches them." : "",
1265
+ style.rule,
1266
+ lastRound ? "This is the final review of the design: approve it unless a critical inconsistency is left, and turn anything still imperfect into standing guidance." : "",
1267
+ ctx.director.autonomy === "full" ? "Never ask the author a question of taste: decide." : "Ask the author (questionForAuthor) only for a critical choice you cannot settle from the vision and the author's rules.",
1268
+ authorRules(ctx, false),
1269
+ ])}\n\n${data([
1270
+ bookHeader(ctx),
1271
+ briefBlock(ctx),
1272
+ outlineBookSection(view),
1273
+ outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1274
+ style.block,
1275
+ storyDesign ? `STORY DESIGN:\n${storyDesign}` : "",
1276
+ `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
1277
+ ...designData.sections,
1278
+ listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
1279
+ entriesSection,
1280
+ findings.length ? `DESIGN CHECKS (found without a model):\n${findings.slice(0, 30).map((finding) => `- ${designFindingText(finding, "en")}`).join("\n")}${findings.length > 30 ? `\n- … and ${findings.length - 30} more` : ""}` : "DESIGN CHECKS (found without a model): nothing.",
1281
+ plan.readerReactions.length
1282
+ ? `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")}`
1283
+ : "",
1284
+ ])}`,
1285
+ json: DESIGN_REVIEW_TOOL,
1286
+ maxOutputTokens: outputLimit(ctx, 5000),
1287
+ });
1288
+ // Without a verdict and a score the design is never approved by default.
1289
+ const output = requireStructuredFields(response.json, { verdict: "text", score: "score" }, "The director's review of the design");
1290
+ const verdictGiven = verdictOf(output.verdict, "The director's review of the design");
1291
+ const score = Math.round(normalizeScore(output.score) * 10) / 10;
1292
+ const summaryText = asString(output.summary);
1293
+ const counterProposal = asString(output.counterProposal);
1294
+ const requested = asArray(output.changes).map(asRecord)
1295
+ .map((change) => ({ instruction: asString(change.instruction), chapterNumber: asInteger(change.chapterNumber, 0, 0, MAX_BOOK_CHAPTERS) }))
1296
+ .filter((change) => change.instruction);
1297
+ const critical = asArray(output.critical).map(asRecord)
1298
+ .map((item) => ({ instruction: asString(item.issue), chapterNumber: asInteger(item.chapterNumber, 0, 0, MAX_BOOK_CHAPTERS) }))
1299
+ .filter((item) => item.instruction);
1300
+ const noteOf = (change) => `${change.chapterNumber ? `Chapter ${change.chapterNumber}: ` : ""}${change.instruction}`;
1301
+ const changesRequested = requested.map(noteOf);
1302
+ const criticalNotes = critical.map((item) => `Critical — ${noteOf(item)}`);
1303
+ const guidance = asStringList(output.guidance, 10);
1304
+ const interests = plan.readerReactions.map((reaction) => reaction.interest);
1305
+ const readers = interests.length ? Math.round((interests.reduce((sum, value) => sum + value, 0) / interests.length) * 10) / 10 : undefined;
1306
+ const at = ctx.now().toISOString();
1307
+ design.rounds = [...design.rounds, { round: roundNumber, score, verdict: "revise", ...(readers !== undefined ? { readers } : {}), critical: critical.length, findings: findings.length, at }];
1308
+ const plateau = designPlateau(design);
1309
+ // A score alone never approves: the target and no critical inconsistency; or nothing left to change at all.
1310
+ let outcome = null;
1311
+ let escalate = false;
1312
+ if (!critical.length && verdictGiven === "approve" && score >= target)
1313
+ outcome = "target";
1314
+ else if (!critical.length && !changesRequested.length)
1315
+ outcome = "unchanged";
1316
+ else if (lastRound || plateau) {
1317
+ if (critical.length && !design.escalated)
1318
+ escalate = true;
1319
+ else
1320
+ outcome = lastRound ? "rounds" : "plateau";
1321
+ }
1322
+ if (verdictGiven === "approve" && score < target && !critical.length && changesRequested.length && !outcome) {
1323
+ ctx.insight("warning", withheldApproval(ctx, score, italian ? "il progetto viene rivisto." : "the design is revised.", target));
1324
+ }
1325
+ const figures = { round: roundNumber, rounds: maxRounds, score, target, critical: critical.length, findings: findings.length };
1326
+ const changes = [];
1327
+ const range = planRange(importedChapters(ctx.snapshot), view.lastChapter);
1328
+ const size = planBatchChapters(ctx.state, PLAN_BATCH_CHAPTERS);
1329
+ if (outcome) {
1330
+ plan.approved = true;
1331
+ plan.revisionNotes = [];
1332
+ delete plan.revisionBatches;
1333
+ // The design waits for the author, always: approving it, or starting to write, is the author's.
1334
+ plan.awaitingAuthor = true;
1335
+ const left = outcome === "rounds" || outcome === "plateau" ? [...criticalNotes, ...changesRequested] : [];
1336
+ ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, [...guidance, ...left]);
1337
+ design.rounds[design.rounds.length - 1].verdict = "approve";
1338
+ changes.push(...await approvedPlanChanges(ctx, plan));
1339
+ endDesign(ctx.state, outcome, at);
1340
+ const chapters = plan.chapters.filter((chapter) => !chapter.imported).length;
1341
+ const reached = outcome === "target" || outcome === "unchanged";
1342
+ const tone = critical.length ? "warning" : reached ? "ok" : "info";
1343
+ const title = italian
1344
+ ? `Progetto pronto: ${chapters} capitoli, approvato dal direttore con ${score}/10${reached ? "" : outcome === "plateau" ? " (i giri non lo miglioravano più)" : " (dopo i giri permessi)"}`
1345
+ : `Design ready: ${chapters} chapters, approved by the director with ${score}/10${reached ? "" : outcome === "plateau" ? " (the rounds stopped improving it)" : " (after the rounds allowed)"}`;
1346
+ const leftDetail = left.length ? `${italian ? "Resta come indicazione per la scrittura" : "Left as guidance for the writing"}: ${left.slice(0, 4).join(" · ")}` : "";
1347
+ ctx.insight(tone, title, [summaryText, leftDetail].filter(Boolean).join("\n"), { code: "designReady", figures: { ...figures, designOutcome: outcome, chapters } });
1348
+ }
1349
+ else {
1350
+ plan.rounds += 1;
1351
+ plan.revisionNotes = [...criticalNotes, ...changesRequested];
1352
+ plan.revisionBatches = batchesNamed(range, [...critical, ...requested].map((change) => change.chapterNumber), size);
1353
+ // The readers read the design again before the next review while the policy says so.
1354
+ if (plan.rounds < designReaderRounds(ctx.state)) {
1355
+ plan.readersDone = false;
1356
+ plan.readerReactions = [];
1357
+ delete plan.skippedReaders;
1358
+ }
1359
+ ctx.insight("warning", italian
1360
+ ? `Giro ${roundNumber} del progetto: ${score}/10 (obiettivo ${target}/10), ${plan.revisionNotes.length} modifiche${critical.length ? `, ${critical.length} incoerenze critiche` : ""}`
1361
+ : `Design round ${roundNumber}: ${score}/10 (target ${target}/10), ${plan.revisionNotes.length} changes${critical.length ? `, ${critical.length} critical inconsistencies` : ""}`, [plan.revisionNotes.slice(0, 3).join(" · "), counterProposal ? `${italian ? "Avvocato del diavolo" : "Devil's advocate"}: ${counterProposal}` : ""].filter(Boolean).join("\n"), { code: "designRound", figures });
1362
+ if (escalate) {
1363
+ design.escalated = true;
1364
+ ctx.state.question = {
1365
+ id: `question-${ctx.now().getTime()}`,
1366
+ kind: "director",
1367
+ question: italian
1368
+ ? `Il progetto ha ${critical.length === 1 ? "un'incoerenza critica" : `${critical.length} incoerenze critiche`} che il direttore non è riuscito a risolvere nei giri permessi: come vuoi procedere?`
1369
+ : `The design has ${critical.length === 1 ? "a critical inconsistency" : `${critical.length} critical inconsistencies`} the director could not resolve in the rounds allowed: how do you want to go on?`,
1370
+ context: criticalNotes.join("\n"),
1371
+ options: italian
1372
+ ? ["Correggile come ritieni meglio", "Tieni il progetto com'è: la scrittura ne terrà conto"]
1373
+ : ["Fix them as you see best", "Keep the design as it is: the writing will take them into account"],
1374
+ askedAt: at,
1375
+ };
1376
+ ctx.insight("critical", italian ? "Il progetto aspetta te: un'incoerenza critica va decisa" : "The design waits for you: a critical inconsistency needs your decision", criticalNotes.slice(0, 3).join(" · "), { code: "designEscalated", figures });
1377
+ }
1378
+ }
1379
+ const question = asRecord(output.questionForAuthor);
1380
+ if (!ctx.state.question && ctx.director.autonomy !== "full" && asString(question.question)) {
1381
+ ctx.state.question = {
1382
+ id: `question-${ctx.now().getTime()}`,
1383
+ kind: "director",
1384
+ question: asString(question.question),
1385
+ context: summaryText,
1386
+ options: asStringList(question.options, 5),
1387
+ askedAt: at,
1388
+ };
1389
+ }
1390
+ changes.push(await planFileChange(ctx));
1391
+ return { changes: compact(changes), summary: `${outcome ? "approve" : "revise"} ${score}/10 — ${summaryText}` };
1392
+ }
1008
1393
  // ─── The author changed the outline of a chapter not written yet ────────────
1009
1394
  /**
1010
1395
  * The `chapter.md` of a chapter with no text yet, made or brought up to date with its new plan: title, summary, point of view and
@@ -1293,6 +1678,32 @@ async function chapterSource(ctx, chapter) {
1293
1678
  const readerText = chapterReaderText(paragraphs.map((paragraph) => ({ title: paragraph.title, raw: paragraph.raw })));
1294
1679
  return { paragraphs, readerText, sourceHash: await sha256Hex(readerText), sourceVersion: paragraphs.map((paragraph) => paragraph.hash).join(":") };
1295
1680
  }
1681
+ /** The readers that read the book in this run, by slug: those of the panel the director listens to, as many as the run reads with (the planner's `ctx.readers`). */
1682
+ function readingSlugs(ctx) {
1683
+ return activeReaders(ctx.readerPanel, ctx.director, ctx.state.options.maxReaders).map((reader) => reader.slug);
1684
+ }
1685
+ /** The readers' targets that bind this review (they ask a vote of the readers, and one that counts reads), `undefined` for a review without any. */
1686
+ function readersGateOf(ctx) {
1687
+ return readerGate(ctx.state, readingSlugs(ctx));
1688
+ }
1689
+ /** What the readers said in the review, as a round records it: each reader's vote, the readers that do not count, the round. */
1690
+ function readingOf(ctx, review, round = review.round) {
1691
+ const targets = reviewReaderTargets(ctx.state);
1692
+ if (!targets || !review.readerScores.length)
1693
+ return undefined;
1694
+ return { votes: Object.fromEntries(review.readerScores.map((score) => [score.slug, score.score])), excluded: targets.excluded, round };
1695
+ }
1696
+ /** The readers' targets as the director reads them: what each asks and where the readers stand now (when they have read), and who does not count. */
1697
+ function readersTargetsBlock(ctx, review, targets) {
1698
+ const nameOf = (slug) => review.readerScores.find((score) => score.slug === slug)?.name ?? ctx.readerPanel.find((reader) => reader.slug === slug)?.name ?? slug;
1699
+ const standing = review.readerScores.length ? readerStanding(review.readerScores.map((score) => ({ slug: score.slug, score: score.score })), targets) : null;
1700
+ const lines = [
1701
+ targets.average !== undefined ? `- the average of the readers that count: ${standing?.average != null ? `${standing.average}/10 now, ` : ""}target ${targets.average}/10` : "",
1702
+ ...Object.entries(targets.each).filter(([slug]) => !targets.excluded.has(slug)).map(([slug, target]) => `- ${nameOf(slug)}: ${review.readerScores.find((score) => score.slug === slug) ? `${review.readerScores.find((score) => score.slug === slug).score}/10 now, ` : ""}target ${target}/10`),
1703
+ ...[...targets.excluded].map((slug) => `- ${nameOf(slug)}: does not count (left out of the average and of the targets)`),
1704
+ ].filter(Boolean);
1705
+ return `READERS' TARGETS (the chapter is closed only when the director's target and these are all reached, or the rounds run out):\n${lines.join("\n")}`;
1706
+ }
1296
1707
  async function runReader(ctx) {
1297
1708
  const chapter = chapterOf(ctx);
1298
1709
  const review = ctx.state.review;
@@ -1422,6 +1833,12 @@ async function runReadersSummary(ctx) {
1422
1833
  }));
1423
1834
  review.findings = [...review.findings.filter((finding) => finding.source !== "reader"), ...findings];
1424
1835
  review.readersSummaryDone = true;
1836
+ // A reading of their own (the closing one, or a check of their vote) is a round of the chapter: it has no director's vote, and says its round.
1837
+ const reading = review.reading && !review.readRecorded ? readingOf(ctx, review) : undefined;
1838
+ if (reading && review.reading) {
1839
+ recordChapterRound(chapter, readingRound({ ...reading, reading: review.reading }));
1840
+ review.readRecorded = true;
1841
+ }
1425
1842
  ctx.insight(overall >= 7 ? "ok" : overall >= 5 ? "info" : "warning", isItalian(ctx.language) ? `Lettori: ${overall}/10` : `Readers: ${overall}/10`, asStringList(output.consensus, 2).join(" · "));
1426
1843
  return { changes: compact([change]), summary: `${overall}/10 — ${findings.length} proposals for the director` };
1427
1844
  }
@@ -1513,6 +1930,8 @@ async function runDirectorReview(ctx) {
1513
1930
  const maxRounds = reviewMaxRounds(ctx.state, ctx.director);
1514
1931
  const target = reviewTarget(ctx.state, ctx.director);
1515
1932
  const last = review.round >= maxRounds;
1933
+ // The targets for the readers, when the review has them: the director is told they are rules too, and where the readers stand.
1934
+ const gate = review.authorEdit ? undefined : readersGateOf(ctx);
1516
1935
  const perScene = sceneLimit(ctx, Math.max(3000, Math.floor(60000 / Math.max(1, source.paragraphs.length))));
1517
1936
  const style = evaluationStyleOf(ctx, "chapter");
1518
1937
  const authorNote = review.authorEdit ? startedReview(ctx.state)?.note : undefined;
@@ -1525,6 +1944,7 @@ async function runDirectorReview(ctx) {
1525
1944
  `Decide on chapter ${chapter.number} «${chapter.title}» (review round ${review.round} of ${maxRounds}).`,
1526
1945
  "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.",
1527
1946
  `Score the chapter from 1 to 10. Verdict "approve" when it deserves at least ${target}/10 and nothing critical remains; otherwise "revise".`,
1947
+ gate ? "The readers' targets in the data are rules too: the chapter is closed only when they are reached. Accept the concrete corrections of the readers under their target that serve the book's vision, each with a precise fix and its scene." : "",
1528
1948
  style.rule,
1529
1949
  review.authorEdit
1530
1950
  ? "The author changed this chapter after it was approved: judge the chapter as it is now. The author's text stays as it is: no fix will be applied and there is no other round, so your accepted fixes are advice for the author."
@@ -1545,6 +1965,7 @@ async function runDirectorReview(ctx) {
1545
1965
  ? `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")}`
1546
1966
  : "",
1547
1967
  readersSummary ? `READERS PANEL SUMMARY:\n${readersSummary}` : "",
1968
+ gate ? readersTargetsBlock(ctx, review, gate) : "",
1548
1969
  review.previousFixes.length ? `FIXES APPLIED AFTER THE PREVIOUS ROUND:\n${bulletList(review.previousFixes)}` : "",
1549
1970
  `FINDINGS TO DECIDE:\n${review.findings.length ? review.findings.map(findingLine).join("\n\n") : "None."}`,
1550
1971
  `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, perScene)}`,
@@ -1638,8 +2059,11 @@ async function runDirectorReview(ctx) {
1638
2059
  review.repairQueue = review.authorEdit ? [] : [...new Set(accepted.map((decision) => decision.sceneNumber))].sort((left, right) => left - right);
1639
2060
  // The readers' average is in the record of the round they read the chapter in (the first, and the others the review policy says) and of no other: a state that
1640
2061
  // does not say which round they read in (an older engine) had them read in the first. The verdict is the one the plan acts on.
1641
- const readersReadNow = review.readersRound !== undefined ? review.readersRound === review.round : review.history.length === 0;
1642
- recordChapterRound(chapter, closedRound({ director: score, readers: readersReadNow ? review.readerScores.map((entry) => entry.score) : undefined, verdict, accepted: accepted.length, rejected: rejected.length }));
2062
+ // (Readers who read on their own at the end of the review have a round of their own: the votes held are not recorded twice.)
2063
+ const readersReadNow = (review.readersRound !== undefined ? review.readersRound === review.round : review.history.length === 0) && !review.readRecorded;
2064
+ // With targets for the readers the round says which round it is and how each reader voted (and the average is of the readers that count).
2065
+ const reading = readersReadNow ? readingOf(ctx, review) : undefined;
2066
+ recordChapterRound(chapter, closedRound({ director: score, readers: readersReadNow ? review.readerScores.map((entry) => entry.score) : undefined, verdict, accepted: accepted.length, rejected: rejected.length, ...(reading ? { reading } : {}) }));
1643
2067
  review.history = [...review.history, { round: review.round, verdict, score, accepted: accepted.length, rejected: rejected.length }];
1644
2068
  ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, asStringList(output.guidance, 6));
1645
2069
  const question = asRecord(output.questionForAuthor);
@@ -1765,6 +2189,9 @@ async function runRepair(ctx) {
1765
2189
  scene.words = words;
1766
2190
  if (summary)
1767
2191
  scene.summary = summary;
2192
+ // The readers' votes are of the text before this fix (counted only by a review that keeps their targets, so that no other state changes).
2193
+ if (review.readText !== undefined)
2194
+ review.repairs = (review.repairs ?? 0) + 1;
1768
2195
  ctx.insight("ok", isItalian(ctx.language) ? `Scena ${chapter.number}.${scene.number} corretta (${instructions.length})` : `Scene ${chapter.number}.${scene.number} revised (${instructions.length})`, instructions.join(" · "));
1769
2196
  return { changes: [change], summary: `${instructions.length} fixes applied, ${words} words.` };
1770
2197
  }
@@ -1844,6 +2271,21 @@ async function runConsolidate(ctx) {
1844
2271
  changes.push(await renderPlot(ctx));
1845
2272
  changes.push(await planFileChange(ctx));
1846
2273
  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);
2274
+ // Closed with a target of the readers not reached: what stood in the way, and why it was not worked on any more.
2275
+ const gate = review?.gateStop ? reviewReaderTargets(ctx.state) : undefined;
2276
+ if (review && gate) {
2277
+ const standing = readerStanding(review.readerScores.map((score) => ({ slug: score.slug, score: score.score })), gate);
2278
+ const names = (slug) => review.readerScores.find((score) => score.slug === slug)?.name ?? ctx.readerPanel.find((reader) => reader.slug === slug)?.name ?? slug;
2279
+ const italian = isItalian(ctx.language);
2280
+ const averageBlocked = standing.blockers.some((blocker) => blocker.subject === "average");
2281
+ const readersUnder = standing.blockers.filter((blocker) => blocker.subject === "reader").length;
2282
+ const why = review.gateStop === "plateau"
2283
+ ? (italian ? "le ultime correzioni non avvicinavano i lettori all'obiettivo" : "the last corrections did not bring the readers closer to their target")
2284
+ : (italian ? `i giri di revisione permessi (${review.round}) sono finiti` : `the rounds of review allowed (${review.round}) are used`);
2285
+ ctx.insight("warning", italian ? `Capitolo ${chapter.number} chiuso sotto l'obiettivo dei lettori: ${blockersText(standing.blockers, ctx.language, names)}` : `Chapter ${chapter.number} closed under the readers' target: ${blockersText(standing.blockers, ctx.language, names)}`, italian ? `Non è più lavorato perché ${why}. Per migliorarlo, rivedi di nuovo il libro.` : `It is not worked on any more because ${why}. To improve it, review the book again.`,
2286
+ // The numbers say the average and its target only when the average is what stood in the way, and how many readers were under their own target.
2287
+ { code: "readersTargetMissed", chapterNumber: chapter.number, figures: { round: review.round, ...(averageBlocked && standing.average !== null ? { readers: standing.average } : {}), ...(averageBlocked && gate.average !== undefined ? { readersTarget: gate.average } : {}), ...(readersUnder ? { readersUnder } : {}) } });
2288
+ }
1847
2289
  return { changes: compact(changes), summary };
1848
2290
  }
1849
2291
  const WRITTEN_SCENES = {