narrarium-engine 0.1.23 → 0.1.24

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 (71) hide show
  1. package/README.md +12 -1
  2. package/dist/autopilot/design.d.ts +77 -0
  3. package/dist/autopilot/design.d.ts.map +1 -0
  4. package/dist/autopilot/design.js +234 -0
  5. package/dist/autopilot/design.js.map +1 -0
  6. package/dist/autopilot/estimate-texts.d.ts +6 -0
  7. package/dist/autopilot/estimate-texts.d.ts.map +1 -1
  8. package/dist/autopilot/estimate-texts.js +20 -7
  9. package/dist/autopilot/estimate-texts.js.map +1 -1
  10. package/dist/autopilot/estimate.d.ts +23 -0
  11. package/dist/autopilot/estimate.d.ts.map +1 -1
  12. package/dist/autopilot/estimate.js +74 -22
  13. package/dist/autopilot/estimate.js.map +1 -1
  14. package/dist/autopilot/outline-check.d.ts +9 -0
  15. package/dist/autopilot/outline-check.d.ts.map +1 -1
  16. package/dist/autopilot/outline-check.js +16 -0
  17. package/dist/autopilot/outline-check.js.map +1 -1
  18. package/dist/autopilot/outline-compose.d.ts +3 -3
  19. package/dist/autopilot/outline-compose.d.ts.map +1 -1
  20. package/dist/autopilot/outline-compose.js +4 -4
  21. package/dist/autopilot/outline-compose.js.map +1 -1
  22. package/dist/autopilot/planner.d.ts +9 -10
  23. package/dist/autopilot/planner.d.ts.map +1 -1
  24. package/dist/autopilot/planner.js +87 -25
  25. package/dist/autopilot/planner.js.map +1 -1
  26. package/dist/autopilot/prompts.d.ts +18 -0
  27. package/dist/autopilot/prompts.d.ts.map +1 -1
  28. package/dist/autopilot/prompts.js +163 -0
  29. package/dist/autopilot/prompts.js.map +1 -1
  30. package/dist/autopilot/runner.d.ts.map +1 -1
  31. package/dist/autopilot/runner.js +22 -3
  32. package/dist/autopilot/runner.js.map +1 -1
  33. package/dist/autopilot/state.d.ts +9 -1
  34. package/dist/autopilot/state.d.ts.map +1 -1
  35. package/dist/autopilot/state.js +80 -1
  36. package/dist/autopilot/state.js.map +1 -1
  37. package/dist/autopilot/tasks.d.ts +3 -1
  38. package/dist/autopilot/tasks.d.ts.map +1 -1
  39. package/dist/autopilot/tasks.js +448 -64
  40. package/dist/autopilot/tasks.js.map +1 -1
  41. package/dist/autopilot/types.d.ts +89 -1
  42. package/dist/autopilot/types.d.ts.map +1 -1
  43. package/dist/autopilot/types.js +4 -0
  44. package/dist/autopilot/types.js.map +1 -1
  45. package/dist/book/design.d.ts +265 -0
  46. package/dist/book/design.d.ts.map +1 -0
  47. package/dist/book/design.js +632 -0
  48. package/dist/book/design.js.map +1 -0
  49. package/dist/book/outline.d.ts +20 -4
  50. package/dist/book/outline.d.ts.map +1 -1
  51. package/dist/book/outline.js +46 -9
  52. package/dist/book/outline.js.map +1 -1
  53. package/dist/index.d.ts +2 -0
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +2 -0
  56. package/dist/index.js.map +1 -1
  57. package/dist/server/client.d.ts +2 -1
  58. package/dist/server/client.d.ts.map +1 -1
  59. package/dist/server/client.js +7 -2
  60. package/dist/server/client.js.map +1 -1
  61. package/dist/server/protocol.d.ts +10 -0
  62. package/dist/server/protocol.d.ts.map +1 -1
  63. package/dist/server/protocol.js +10 -0
  64. package/dist/server/protocol.js.map +1 -1
  65. package/dist/testing/index.d.ts +2 -0
  66. package/dist/testing/index.d.ts.map +1 -1
  67. package/dist/testing/index.js +67 -0
  68. package/dist/testing/index.js.map +1 -1
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. 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, 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";
@@ -17,9 +18,11 @@ import { bulletList, clipText, countWords, isItalian, languageName, OUTPUT_TOKEN
17
18
  import { chapterLines, layoutChapters, listSection, outlineList } from "./outline.js";
18
19
  import { legacyChapters, queuedMarkReviewed, startedReview } from "./frozen.js";
19
20
  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";
21
+ import { PLAN_BATCH_CHAPTERS, SCENES_PER_CHAPTER, batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts, sceneFile, scenesForChapter } from "./planner.js";
22
+ import { designFindingsInsight, designLastRound, designPlateau, designReaderRounds, designTarget, endDesign, loadDesignCheckInput, planBatchChapters } from "./design.js";
23
+ import { outlineDesignGaps } from "./outline-check.js";
24
+ 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";
25
+ import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES, CONCEPT_LOGLINE_CHARACTERS, closedRound, designActive, designMaxRounds, normalizeFinalReview, recordChapterRound } from "./state.js";
23
26
  import { STORY_SO_FAR_MAX_WORDS, STORY_SO_FAR_TARGET_WORDS, pruneStorySnapshots, readStorySoFar, renderTotalResumeBody, storySoFarExcess } from "./story-so-far.js";
24
27
  // ─── Shared prompt fragments ────────────────────────────────────────────────
25
28
  function bookHeader(ctx) {
@@ -185,8 +188,9 @@ function outlineGhostwriter(ctx, entry) {
185
188
  return undefined;
186
189
  }
187
190
  /** 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");
191
+ function outlineContentOf(chapter, design) {
192
+ // A designed chapter keeps its events in its design: the text says what happens, once.
193
+ const body = [chapter.summary.trim(), chapter.keyEvents.length && !design ? bulletList(chapter.keyEvents) : ""].filter(Boolean).join("\n\n");
190
194
  return { title: chapter.title, body, ...(chapter.ghostwriter ? { ghostwriter: chapter.ghostwriter } : {}) };
191
195
  }
192
196
  /**
@@ -198,20 +202,24 @@ function outlineContentOf(chapter) {
198
202
  * 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
203
  * of the journal of the Synopsis (`outline/changes.yml`), by the autopilot, in the same commit.
200
204
  */
201
- async function fillOutline(ctx, planned, imported) {
202
- const fill = ctx.state.options.fillOutline !== false;
205
+ async function fillOutline(ctx, planned, imported, designs) {
206
+ // A design lives in the entries of the Synopsis: a design run writes them whatever `fillOutline` says.
207
+ const fill = ctx.state.options.fillOutline !== false || designActive(ctx.state);
203
208
  const outline = outlineOf(ctx);
204
209
  const entries = new Map((await outline.chapters()).map((entry) => [entry.number, entry]));
205
210
  const changes = [];
206
211
  const was = new Map();
207
212
  const now = new Map();
208
213
  const write = async (chapter, existing) => {
209
- const content = outlineContentOf(chapter);
210
- const digest = await outlineEntryDigest(content);
214
+ const design = designs?.get(chapter.number);
215
+ const content = outlineContentOf(chapter, design);
216
+ // The design of the plan replaces the whole design of an entry of the autopilot; without one, the entry keeps the design it has.
217
+ const patch = design ? wholeDesignPatch(design) : undefined;
218
+ const digest = await outlineEntryDigest({ ...content, design: outlineDesignOf({ design: patch, frontmatter: existing?.frontmatter }) });
211
219
  if (!existing || digest !== existing.contentDigest) {
212
220
  changes.push({
213
221
  path: existing?.path ?? outlineChapterPath(chapter.number),
214
- content: serializeOutlineChapter({ number: chapter.number, ...content, origin: "autopilot", digest, frontmatter: existing?.frontmatter }),
222
+ content: serializeOutlineChapter({ number: chapter.number, ...content, ...(patch ? { design: patch } : {}), origin: "autopilot", digest, frontmatter: existing?.frontmatter }),
215
223
  expectedHash: existing ? existing.hash : null,
216
224
  });
217
225
  if (existing)
@@ -475,13 +483,19 @@ async function runConcept(ctx) {
475
483
  assertFrontmatterReadable(STORY_DESIGN_FILE, design.document, ctx.language);
476
484
  if (context && isThinDocument(context.document.body))
477
485
  assertFrontmatterReadable(CONTEXT_FILE, context.document, ctx.language);
486
+ // 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.
487
+ const designing = designActive(ctx.state);
478
488
  const response = await ctx.ai({
479
489
  capability: AI_CAPABILITIES.writer,
480
490
  label: "autopilot:concept",
481
- system: architectSystemPrompt(ctx.language),
491
+ system: designing ? `${architectSystemPrompt(ctx.language)}\n\n${DESIGN_ARCHITECT_ROLE}` : architectSystemPrompt(ctx.language),
482
492
  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.",
493
+ designing
494
+ ? `Design the foundation of this novel from the author's description, for about ${view.lastChapter} chapters: no prose, only the design a writer needs.`
495
+ : `Design the foundation of this novel from the author's brief, for about ${view.lastChapter} chapters.`,
496
+ designing
497
+ ? "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."
498
+ : "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
499
  ctx.state.brief.synopsis ? "The author's chapter-by-chapter synopsis is binding: the concept must make it possible exactly as written." : "",
486
500
  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
501
  "Reuse the existing canon names instead of duplicating them.",
@@ -497,8 +511,8 @@ async function runConcept(ctx) {
497
511
  ctx.snapshot.canon.length ? `EXISTING CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true })}` : "",
498
512
  `DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
499
513
  ])}`,
500
- json: CONCEPT_TOOL,
501
- maxOutputTokens: outputLimit(ctx, 9000),
514
+ json: designing ? DESIGN_CONCEPT_TOOL : CONCEPT_TOOL,
515
+ maxOutputTokens: outputLimit(ctx, designing ? 12000 : 9000),
502
516
  temperature: 0.8,
503
517
  });
504
518
  const output = requireStructuredFields(response.json, { storyDesign: "text" }, "The concept");
@@ -544,9 +558,13 @@ async function runConcept(ctx) {
544
558
  else
545
559
  counts.other += 1;
546
560
  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 });
561
+ const content = renderMarkdown({ type: kind, id: `${kind}:${slug}`, ...label, ...frontmatter, canon: "draft" }, body);
562
+ changes.push({ path, content, expectedHash: null });
563
+ created.set(path, content);
548
564
  return slug;
549
565
  };
566
+ /** The files this step creates, by path, as it writes them. */
567
+ const created = new Map();
550
568
  const characterSlug = (name) => known.find((entry) => entry.kind === "character" && sameCanonEntity("character", name, entry.names))?.slug ?? canonSlug("character", name);
551
569
  const characters = asArray(output.characters).slice(0, 10).map(asRecord);
552
570
  for (const character of characters) {
@@ -561,6 +579,7 @@ async function runConcept(ctx) {
561
579
  arc: asString(character.arc) || undefined,
562
580
  desires: asString(character.desire) ? [asString(character.desire)] : undefined,
563
581
  fears: asString(character.fear) ? [asString(character.fear)] : undefined,
582
+ relationships: designing && asStringList(character.relationships, 12).length ? asStringList(character.relationships, 12) : undefined,
564
583
  }, `# ${name}\n\n${asString(character.description)}`);
565
584
  }
566
585
  for (const location of asArray(output.locations).slice(0, 10).map(asRecord)) {
@@ -573,16 +592,43 @@ async function runConcept(ctx) {
573
592
  if (name)
574
593
  create("faction", name, { mission: asString(faction.mission) || undefined }, `# ${name}\n\n${asString(faction.description)}`);
575
594
  }
595
+ if (designing) {
596
+ for (const item of asArray(output.items).slice(0, 8).map(asRecord)) {
597
+ const name = asString(item.name);
598
+ if (name)
599
+ create("item", name, { significance: asString(item.significance) || undefined }, `# ${name}\n\n${asString(item.description)}`);
600
+ }
601
+ }
576
602
  const secrets = [];
577
603
  for (const secret of asArray(output.secrets).slice(0, 8).map(asRecord)) {
578
604
  const title = asString(secret.title);
579
605
  if (!title)
580
606
  continue;
581
607
  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)}`);
608
+ const consequences = designing ? asStringList(secret.consequences, 12) : [];
609
+ const slug = create("secret", title, { holders, stakes: asString(secret.stakes) || undefined, status: "hidden", ...(consequences.length ? { consequences } : {}) }, `# ${title}\n\n${asString(secret.truth)}`);
583
610
  const revealChapter = asInteger(secret.revealChapter, 0, 0, MAX_BOOK_CHAPTERS);
584
611
  secrets.push({ slug, title, revealChapter: revealChapter || undefined });
585
612
  }
613
+ if (designing) {
614
+ // The ledgers this step wrote are the design's: a later step may rewrite them while nobody changes them.
615
+ const ledgers = { ...(ctx.state.design.ledgers ?? {}) };
616
+ for (const secret of secrets) {
617
+ const path = canonPath("secret", secret.slug);
618
+ const content = created.get(path);
619
+ if (content)
620
+ ledgers[path] = await secretLedgerDigest(parseMarkdown(content).frontmatter);
621
+ }
622
+ ctx.state.design.ledgers = ledgers;
623
+ // The themes, the tone and the rules of the world have no other home: `bible/` gets them when it has none.
624
+ const themes = asStringList(output.themes, 12);
625
+ const tone = asString(output.tone);
626
+ if ((themes.length || tone) && !ctx.snapshot.files.has(BIBLE_THEMES_FILE))
627
+ changes.push({ path: BIBLE_THEMES_FILE, content: serializeBibleThemes({ themes, tone }), expectedHash: null });
628
+ const rules = asStringList(output.worldRules, 20);
629
+ if (rules.length && !ctx.snapshot.files.has(BIBLE_WORLD_FILE))
630
+ changes.push({ path: BIBLE_WORLD_FILE, content: serializeBibleWorld({ rules }), expectedHash: null });
631
+ }
586
632
  // The pitch of the book, kept for the description of the outline that the plan writes when the author has none.
587
633
  const pitch = clipText(logline || asString(output.premise), CONCEPT_LOGLINE_CHARACTERS).trim();
588
634
  ctx.state.concept = { done: true, generated: true, secrets, ...(pitch ? { logline: pitch } : {}) };
@@ -688,7 +734,10 @@ async function runPlan(ctx) {
688
734
  const view = await authorOutline(ctx);
689
735
  const target = view.lastChapter;
690
736
  const range = planRange(imported, target);
691
- const batch = nextPlanBatch(previous, range);
737
+ // A design run plans fewer chapters a call: it says much more of each.
738
+ const designing = designActive(ctx.state);
739
+ const size = planBatchChapters(ctx.state, PLAN_BATCH_CHAPTERS);
740
+ const batch = nextPlanBatch(previous, range, size);
692
741
  if (!batch)
693
742
  throw new Error("There is no chapter left to plan.");
694
743
  const { start: startNumber, last: lastNumber } = range;
@@ -710,14 +759,19 @@ async function runPlan(ctx) {
710
759
  const plannedNumbers = new Set((previous?.chapters ?? []).map((chapter) => chapter.number));
711
760
  const unlisted = view.any ? Array.from({ length: batchCount }, (_, index) => from + index).filter((number) => !view.entries.has(number)) : [];
712
761
  const ahead = [...view.entries.values()].filter((entry) => entry.number >= startNumber && (entry.number < from || entry.number > to) && !plannedNumbers.has(entry.number));
762
+ const designData = designing ? await designContext(ctx) : null;
713
763
  const response = await ctx.ai({
714
764
  capability: AI_CAPABILITIES.writer,
715
765
  label: "autopilot:plan",
716
- system: architectSystemPrompt(ctx.language),
766
+ system: designing ? `${architectSystemPrompt(ctx.language)}\n\n${DESIGN_ARCHITECT_ROLE}` : architectSystemPrompt(ctx.language),
717
767
  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}.`,
768
+ designing
769
+ ? (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}.`)
770
+ : revising
771
+ ? `Revise the chapter plan (chapters ${from}-${to}) applying the director's changes:\n${bulletList(notes)}`
772
+ : `Plan the next ${batchCount} chapters of the novel, numbered ${from} to ${to}.`,
773
+ designing ? DESIGN_CHAPTER_RULE : "",
774
+ designing ? DESIGN_LEDGER_RULE : "",
721
775
  batched ? `The novel will have ${target} chapters in all and is planned in batches: this call covers only chapters ${from} to ${to}.` : "",
722
776
  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
777
  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 +796,48 @@ async function runPlan(ctx) {
742
796
  resume ? `STORY SO FAR (before chapter ${startNumber}):\n${resume}` : "",
743
797
  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
798
  batched && revising ? `CURRENT VERSION OF CHAPTERS ${from}-${to} (revise it):\n${existing.map(chapterPlanBlock).join("\n\n")}` : "",
799
+ designing && revising ? await designedEntriesSection(ctx, from, to, `THE DESIGN OF CHAPTERS ${from}-${to} NOW (revise it)`) : "",
800
+ ...(designData ? designData.sections : []),
745
801
  `DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
746
802
  ])}`,
747
- json: PLAN_TOOL,
748
- maxOutputTokens: outputLimit(ctx, 9000),
803
+ json: designing ? DESIGN_PLAN_TOOL : PLAN_TOOL,
804
+ maxOutputTokens: outputLimit(ctx, designing ? 4000 + 1500 * batchCount : 9000),
749
805
  temperature: 0.7,
750
806
  });
751
- const output = requireStructuredFields(response.json, { chapters: "list" }, "The chapter plan");
807
+ const output = requireStructuredFields(response.json, { chapters: "list" }, designing ? "The design of the chapters" : "The chapter plan");
752
808
  const proposed = asArray(output.chapters).map(asRecord).filter((chapter) => asString(chapter.title)).slice(0, batchCount);
753
809
  if (proposed.length < batchCount)
754
810
  throw new AiReplyRejectedError(`The chapter plan has ${proposed.length} chapters with a title, but ${batchCount} were requested (chapters ${from}-${to}).`);
811
+ // 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.
812
+ const designs = new Map();
813
+ if (designing) {
814
+ proposed.forEach((chapter, index) => {
815
+ const number = from + index;
816
+ const { patch, problems } = normalizeDesignPatch(asRecord(chapter.design));
817
+ if (problems.length)
818
+ throw new AiReplyRejectedError(`The design of chapter ${number} is over the limits (${problems.join("; ")}): return it shorter, whole.`);
819
+ const design = Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== null && value !== undefined));
820
+ if (!design.goal || !design.events?.length)
821
+ throw new AiReplyRejectedError(`The design of chapter ${number} has no narrative goal or no main events: return every chapter with its whole design.`);
822
+ designs.set(number, design);
823
+ });
824
+ }
755
825
  const planned = proposed.map((chapter, index) => {
756
826
  const number = from + index;
757
827
  // The hypothetical title of the author's entry is the chapter's: the model refines a title only where the entry has none.
758
828
  const entry = view.entries.get(number);
759
829
  const title = entry?.title ? clipText(entry.title, OUTLINE_TITLE_MAX_CHARS).trim() : asString(chapter.title);
760
830
  const ghostwriter = outlineGhostwriter(ctx, entry);
831
+ const design = designs.get(number);
761
832
  return {
762
833
  number,
763
834
  title,
764
835
  slug: chapterSlug(number, title),
765
836
  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),
837
+ goal: design ? design.goal ?? "" : asString(chapter.goal),
838
+ pov: design ? (design.pov ?? []).slice(0, 6) : asStringList(chapter.pov, 6),
839
+ keyEvents: design ? (design.events ?? []).slice(0, 12) : asStringList(chapter.keyEvents, 12),
840
+ reveals: design ? (design.reveals ?? []).slice(0, 8) : asStringList(chapter.reveals, 8),
770
841
  status: "planned",
771
842
  scenes: [],
772
843
  ...(ghostwriter ? { ghostwriter } : {}),
@@ -794,7 +865,7 @@ async function runPlan(ctx) {
794
865
  revisionNotes = [];
795
866
  }
796
867
  else if (revising) {
797
- const pending = revisionBatchStarts(previous, range).filter((start) => start !== from);
868
+ const pending = revisionBatchStarts(previous, range, size).filter((start) => start !== from);
798
869
  if (pending.length)
799
870
  revisionBatches = pending;
800
871
  else
@@ -819,7 +890,16 @@ async function runPlan(ctx) {
819
890
  ...(previous?.removedChapters?.length ? { removedChapters: previous.removedChapters } : {}),
820
891
  };
821
892
  // 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));
893
+ changes.push(...await fillOutline(ctx, planned, imported, designs));
894
+ if (designing) {
895
+ changes.push(...await designLedgerChanges(ctx, asArray(output.secrets).map(asRecord), from, to));
896
+ // 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.
897
+ const yours = planned.filter((chapter) => view.entries.has(chapter.number)).map((chapter) => chapter.number);
898
+ if (yours.length) {
899
+ const italian = isItalian(ctx.language);
900
+ 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" });
901
+ }
902
+ }
823
903
  changes.push(await planFileChange(ctx));
824
904
  // 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
905
  const italian = isItalian(ctx.language);
@@ -835,6 +915,123 @@ async function runPlan(ctx) {
835
915
  summary: batched ? `${single ? "Chapter" : "Chapters"} ${covered}: ${list}` : list,
836
916
  };
837
917
  }
918
+ // ─── The design of the book (`AutopilotDesign`) ─────────────────────────────
919
+ /** Characters of the designs of the chapters a prompt quotes, in all: the neighbourhood of what is designed keeps the most. */
920
+ const DESIGN_ENTRIES_CHARS = 16_000;
921
+ /**
922
+ * 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
923
+ * who will write the book (so that the design fits a voice it can be written in).
924
+ */
925
+ async function designContext(ctx) {
926
+ const [themesFile, worldFile, secrets, ghostwriter] = await Promise.all([
927
+ ctx.store.read(BIBLE_THEMES_FILE),
928
+ ctx.store.read(BIBLE_WORLD_FILE),
929
+ secretsLedgerBlock(ctx),
930
+ loadGhostwriter(ctx.store, ctx.snapshot).catch(() => null),
931
+ ]);
932
+ const themes = readBibleThemes(themesFile?.content);
933
+ const world = readBibleWorld(worldFile?.content);
934
+ return {
935
+ sections: [
936
+ 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")}` : "",
937
+ world.rules.length ? `RULES OF THE WORLD (never broken):\n${bulletList(world.rules)}` : "",
938
+ secrets ? `SECRETS AND THEIR LEDGER:\n${secrets}` : "",
939
+ ghostwriter ? `GHOSTWRITER WHO WILL WRITE THE BOOK (design what this voice can write well):\n${truncate(ghostwriterBlock(ghostwriter), 1500)}` : "",
940
+ ].filter(Boolean),
941
+ };
942
+ }
943
+ /** The secrets of the book with their truth and their ledger, a few lines each, for the steps of a design. */
944
+ async function secretsLedgerBlock(ctx) {
945
+ const planned = new Map(ctx.state.concept.secrets.map((secret) => [secret.slug, secret.revealChapter]));
946
+ const lines = await Promise.all(ctx.snapshot.canon.filter((entry) => entry.kind === "secret").slice(0, 20).map(async (entry) => {
947
+ const file = await ctx.store.read(entry.path);
948
+ if (!file)
949
+ return "";
950
+ const document = parseMarkdown(file.content);
951
+ const { ledger } = readSecretLedger(document.frontmatter);
952
+ const holders = Array.isArray(document.frontmatter.holders) ? document.frontmatter.holders.filter((item) => typeof item === "string") : [];
953
+ const reveal = referencedChapterNumber(entry.revealIn) ?? planned.get(entry.slug);
954
+ const notes = (label, items) => (items.length ? `${label}: ${items.map((item) => `ch. ${item.chapter} ${truncate(item.note, 120)}`).join("; ")}` : "");
955
+ return [
956
+ `- ${entry.name}: ${truncate(document.body.replace(/^#[^\n]*\n+/, "").replace(/\s+/g, " ").trim(), 300) || "(no truth written)"}`,
957
+ holders.length ? ` Known from the start by: ${holders.join(", ")}` : "",
958
+ ledger.learnedBy.length ? ` Learned by: ${ledger.learnedBy.map((item) => `${item.character} (ch. ${item.chapter})`).join(", ")}` : "",
959
+ reveal ? ` Revealed to the reader in chapter ${reveal}` : " Not placed yet: it needs a reveal chapter",
960
+ notes(" Clues", ledger.clues),
961
+ notes(" Red herrings", ledger.redHerrings),
962
+ ledger.consequences.length ? ` Consequences: ${ledger.consequences.join("; ")}` : "",
963
+ ].filter(Boolean).join("\n");
964
+ }));
965
+ return lines.filter(Boolean).join("\n");
966
+ }
967
+ /** 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. */
968
+ async function designedEntriesSection(ctx, from, to, label) {
969
+ const entries = (await outlineOf(ctx).chapters()).filter((entry) => entry.design && (from === undefined || entry.number >= from) && (to === undefined || entry.number <= to));
970
+ if (!entries.length)
971
+ return "";
972
+ const share = Math.max(400, Math.floor(DESIGN_ENTRIES_CHARS / entries.length));
973
+ return `${label}:\n${entries.map((entry) => `Chapter ${entry.number}${entry.title ? ` «${entry.title}»` : ""}:\n${designText(entry.design, share)}`).join("\n\n")}`;
974
+ }
975
+ /** A ledger item of the model as the engine keeps it: a whole chapter from 0 and a note (or a character), or nothing. */
976
+ function ledgerNotes(value) {
977
+ 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);
978
+ }
979
+ /**
980
+ * 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
981
+ * 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`),
982
+ * what falls in those chapters. A secret of the author's keeps its ledger, and the author is told.
983
+ */
984
+ async function designLedgerChanges(ctx, items, from, to) {
985
+ const design = ctx.state.design;
986
+ const ledgers = { ...(design.ledgers ?? {}) };
987
+ const changes = [];
988
+ const kept = [];
989
+ const characters = ctx.snapshot.canon.filter((entry) => entry.kind === "character");
990
+ const characterRef = (name) => {
991
+ const found = characters.find((entry) => sameCanonEntity("character", name, [entry.name, ...entry.aliases]));
992
+ return found ? `character:${found.slug}` : name.trim();
993
+ };
994
+ for (const item of items) {
995
+ const title = asString(item.title);
996
+ const secret = ctx.snapshot.canon.find((entry) => entry.kind === "secret" && sameCanonEntity("secret", title, [entry.name, ...entry.aliases]));
997
+ if (!secret)
998
+ continue;
999
+ const reveal = asInteger(item.revealChapter, 0, 0, MAX_BOOK_CHAPTERS);
1000
+ const planned = ctx.state.concept.secrets.find((entry) => entry.slug === secret.slug);
1001
+ if (planned && reveal > 0 && (reveal >= from && reveal <= to || !planned.revealChapter))
1002
+ planned.revealChapter = reveal;
1003
+ const learnedBy = asArray(item.learnedBy).map(asRecord)
1004
+ .map((entry) => ({ character: characterRef(asString(entry.character)), chapter: asInteger(entry.chapter, -1, -1, MAX_BOOK_CHAPTERS) }))
1005
+ .filter((entry) => entry.character && entry.chapter >= 0);
1006
+ const batch = { learnedBy, readerKnows: ledgerNotes(item.readerKnows), clues: ledgerNotes(item.clues), redHerrings: ledgerNotes(item.redHerrings) };
1007
+ const file = await ctx.store.read(secret.path);
1008
+ if (!file)
1009
+ continue;
1010
+ const document = parseMarkdown(file.content);
1011
+ if (document.error) {
1012
+ kept.push(secret.name);
1013
+ continue;
1014
+ }
1015
+ const owned = ledgers[secret.path] !== undefined && ledgers[secret.path] === await secretLedgerDigest(document.frontmatter);
1016
+ if (!owned) {
1017
+ kept.push(secret.name);
1018
+ continue;
1019
+ }
1020
+ const merged = mergeSecretLedger(readSecretLedger(document.frontmatter).ledger, batch, from, to);
1021
+ const frontmatter = { ...document.frontmatter, ...secretLedgerFrontmatter(merged) };
1022
+ const content = renderMarkdown(frontmatter, document.body);
1023
+ if (content === file.content)
1024
+ continue;
1025
+ changes.push({ path: secret.path, content, expectedHash: file.hash });
1026
+ ledgers[secret.path] = await secretLedgerDigest(parseMarkdown(content).frontmatter);
1027
+ }
1028
+ design.ledgers = ledgers;
1029
+ if (kept.length) {
1030
+ const italian = isItalian(ctx.language);
1031
+ 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" });
1032
+ }
1033
+ return changes;
1034
+ }
838
1035
  /** Where a review of the whole plan looks first: the start of what is being planned, not the chapters the author wrote. */
839
1036
  function planFocus(plan) {
840
1037
  return plan.chapters.find((chapter) => !chapter.imported)?.number;
@@ -868,49 +1065,52 @@ async function runPlanReader(ctx) {
868
1065
  return { changes: [], summary: "Reader not available." };
869
1066
  }
870
1067
  const design = await readBody(ctx.store, STORY_DESIGN_FILE, 2500);
1068
+ // A reader of a design reads the design of every chapter, and must contest it as well as judge it.
1069
+ const designing = designActive(ctx.state);
1070
+ const designSections = designing ? [...(await designContext(ctx)).sections.filter((section) => !section.startsWith("GHOSTWRITER")), await designedEntriesSection(ctx, undefined, undefined, "THE DESIGN OF EVERY CHAPTER")] : [];
871
1071
  const asked = await readerReply(ctx, ctx.ai({
872
1072
  capability: AI_CAPABILITIES.reader,
873
1073
  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([
1074
+ system: designing
1075
+ ? `${readerPersonaSystemPrompt(reader, languageName(ctx.language), "brief")}\n\n${DESIGN_READER_ROLE}`
1076
+ : `${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.`,
1077
+ user: `${request([designing
1078
+ ? "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?"
1079
+ : "React as this reader: would you read this book? What excites you, what worries you, what would you wish for?"])}\n\n${data([
876
1080
  bookHeader(ctx),
877
1081
  ctx.state.brief.idea ? `PITCH:\n${ctx.state.brief.idea}` : "",
878
1082
  design ? `PREMISE:\n${design}` : "",
879
1083
  listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
1084
+ ...designSections,
880
1085
  ])}`,
881
- json: PLAN_REACTION_TOOL,
882
- maxOutputTokens: outputLimit(ctx, 1500),
883
- }), (response) => requireStructuredFields(response.json, { interest: "score", reaction: "text" }, "The reader's reaction"));
1086
+ json: designing ? DESIGN_REACTION_TOOL : PLAN_REACTION_TOOL,
1087
+ maxOutputTokens: outputLimit(ctx, designing ? 2500 : 1500),
1088
+ }), (response) => requireStructuredFields(response.json, designing ? { interest: "score", reaction: "text", counterProposal: "text" } : { interest: "score", reaction: "text" }, "The reader's reaction"));
884
1089
  if ("skipped" in asked) {
885
1090
  plan.skippedReaders = [...new Set([...(plan.skippedReaders ?? []), reader.slug])];
886
1091
  return skipReader(ctx, reader.name, asked.skipped);
887
1092
  }
888
1093
  const output = asked.value;
1094
+ const counterProposal = designing ? asString(output.counterProposal) : "";
889
1095
  const reaction = {
890
1096
  slug: reader.slug,
891
1097
  name: reader.name,
892
1098
  interest: Math.round(Math.max(1, normalizeScore(output.interest) ?? 5)),
893
1099
  reaction: asString(output.reaction),
894
- concerns: asStringList(output.concerns, 8),
895
- wishes: asStringList(output.wishes, 8),
1100
+ concerns: [...asStringList(output.concerns, 8), ...(designing ? asStringList(output.weakSpots, 8) : [])].slice(0, 12),
1101
+ // The counter-proposal of a reader of a design travels with its wishes, so that the director weighs it with the rest.
1102
+ wishes: [...asStringList(output.wishes, 8), ...(counterProposal ? [`${isItalian(ctx.language) ? "Controproposta" : "Counter-proposal"}: ${counterProposal}`] : [])],
896
1103
  };
897
1104
  plan.readerReactions = [...plan.readerReactions.filter((entry) => entry.slug !== reader.slug), reaction];
898
1105
  ctx.insight(reaction.interest >= 7 ? "ok" : reaction.interest >= 5 ? "info" : "warning", `${reader.name}: ${reaction.interest}/10`, reaction.reaction);
899
1106
  return { changes: [], summary: `${reaction.interest}/10 — ${truncate(reaction.reaction, 240)}` };
900
1107
  }
901
1108
  async function runPlanReview(ctx) {
1109
+ if (designActive(ctx.state))
1110
+ return runDesignReview(ctx);
902
1111
  const plan = ctx.state.plan;
903
1112
  // 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);
1113
+ await assertRewritable(ctx, await secretsToPlace(ctx, plan));
914
1114
  const [design, view] = await Promise.all([readBody(ctx.store, STORY_DESIGN_FILE, 5000), authorOutline(ctx)]);
915
1115
  const style = evaluationStyleOf(ctx, "plan");
916
1116
  const lastRound = plan.rounds >= 2;
@@ -975,20 +1175,7 @@ async function runPlanReview(ctx) {
975
1175
  delete plan.revisionBatches;
976
1176
  plan.awaitingAuthor = ctx.state.options.pauseAfterPlan || ctx.director.autonomy === "ask-always";
977
1177
  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
- }
1178
+ changes.push(...await approvedPlanChanges(ctx, plan));
992
1179
  ctx.insight("ok", isItalian(ctx.language) ? `Piano approvato dal direttore (${score}/10)` : `Plan approved by the director (${score}/10)`, summaryText);
993
1180
  }
994
1181
  const question = asRecord(output.questionForAuthor);
@@ -1005,6 +1192,203 @@ async function runPlanReview(ctx) {
1005
1192
  changes.push(await planFileChange(ctx));
1006
1193
  return { changes: compact(changes), summary: `${approved ? "approve" : "revise"} ${score}/10 — ${summaryText}` };
1007
1194
  }
1195
+ /** 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. */
1196
+ async function secretsToPlace(ctx, plan) {
1197
+ const paths = [];
1198
+ for (const secret of ctx.state.concept.secrets) {
1199
+ const path = canonPath("secret", secret.slug);
1200
+ if (!plan.chapters.some((entry) => entry.number === secret.revealChapter) || !ctx.snapshot.files.has(path))
1201
+ continue;
1202
+ const file = await ctx.store.read(path);
1203
+ if (file && !frontmatterString(parseMarkdown(file.content).frontmatter, "reveal_in"))
1204
+ paths.push(path);
1205
+ }
1206
+ return paths;
1207
+ }
1208
+ /** 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. */
1209
+ async function approvedPlanChanges(ctx, plan) {
1210
+ const changes = [];
1211
+ for (const chapter of plan.chapters)
1212
+ if (!chapter.imported)
1213
+ changes.push(ensureChapterFile(ctx, chapter));
1214
+ for (const secret of ctx.state.concept.secrets) {
1215
+ const chapter = plan.chapters.find((entry) => entry.number === secret.revealChapter);
1216
+ const path = canonPath("secret", secret.slug);
1217
+ if (!chapter || !ctx.snapshot.files.has(path))
1218
+ continue;
1219
+ changes.push(await changeFor(ctx, path, (existing) => {
1220
+ if (!existing || frontmatterString(existing.frontmatter, "reveal_in"))
1221
+ return null;
1222
+ return renderMarkdown({ ...existing.frontmatter, reveal_in: `chapter:${chapter.slug}`, known_from: `chapter:${chapter.slug}` }, existing.body);
1223
+ }));
1224
+ }
1225
+ return changes;
1226
+ }
1227
+ /**
1228
+ * 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
1229
+ * 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
1230
+ * 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
1231
+ * standing guidance. The approval ends the design: the run stops there, and waits for the author.
1232
+ */
1233
+ async function runDesignReview(ctx) {
1234
+ const plan = ctx.state.plan;
1235
+ const design = ctx.state.design;
1236
+ const italian = isItalian(ctx.language);
1237
+ await assertRewritable(ctx, await secretsToPlace(ctx, plan));
1238
+ const outline = outlineOf(ctx);
1239
+ const [storyDesign, view, checkInput, designData, entriesSection] = await Promise.all([
1240
+ readBody(ctx.store, STORY_DESIGN_FILE, 5000),
1241
+ authorOutline(ctx),
1242
+ loadDesignCheckInput(ctx.store, ctx.snapshot, outline, ctx.state),
1243
+ designContext(ctx),
1244
+ designedEntriesSection(ctx, undefined, undefined, "THE DESIGN OF EVERY CHAPTER"),
1245
+ ]);
1246
+ const findings = [...designChecks(checkInput), ...outlineDesignGaps(checkInput.chapters)];
1247
+ const told = designFindingsInsight(findings, ctx.language);
1248
+ if (told)
1249
+ ctx.insight(told.tone, told.title, told.detail, { code: "designChecks" });
1250
+ const style = evaluationStyleOf(ctx, "plan");
1251
+ const target = designTarget(ctx.state, ctx.director);
1252
+ const maxRounds = designMaxRounds(design);
1253
+ const roundNumber = plan.rounds + 1;
1254
+ const lastRound = designLastRound(ctx.state);
1255
+ const response = await ctx.ai({
1256
+ capability: AI_CAPABILITIES.director,
1257
+ label: "autopilot:plan-review",
1258
+ system: directorSystemPrompt(ctx.director, ctx.language),
1259
+ user: `${request([
1260
+ `Review the design of the book before any prose is written (review ${roundNumber} of at most ${Math.max(maxRounds, roundNumber)}).`,
1261
+ `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.`,
1262
+ ...DESIGN_DIRECTOR_RULES,
1263
+ 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." : "",
1264
+ style.rule,
1265
+ 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." : "",
1266
+ 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.",
1267
+ authorRules(ctx, false),
1268
+ ])}\n\n${data([
1269
+ bookHeader(ctx),
1270
+ briefBlock(ctx),
1271
+ outlineBookSection(view),
1272
+ outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1273
+ style.block,
1274
+ storyDesign ? `STORY DESIGN:\n${storyDesign}` : "",
1275
+ `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
1276
+ ...designData.sections,
1277
+ listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
1278
+ entriesSection,
1279
+ 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.",
1280
+ plan.readerReactions.length
1281
+ ? `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")}`
1282
+ : "",
1283
+ ])}`,
1284
+ json: DESIGN_REVIEW_TOOL,
1285
+ maxOutputTokens: outputLimit(ctx, 5000),
1286
+ });
1287
+ // Without a verdict and a score the design is never approved by default.
1288
+ const output = requireStructuredFields(response.json, { verdict: "text", score: "score" }, "The director's review of the design");
1289
+ const verdictGiven = verdictOf(output.verdict, "The director's review of the design");
1290
+ const score = Math.round(normalizeScore(output.score) * 10) / 10;
1291
+ const summaryText = asString(output.summary);
1292
+ const counterProposal = asString(output.counterProposal);
1293
+ const requested = asArray(output.changes).map(asRecord)
1294
+ .map((change) => ({ instruction: asString(change.instruction), chapterNumber: asInteger(change.chapterNumber, 0, 0, MAX_BOOK_CHAPTERS) }))
1295
+ .filter((change) => change.instruction);
1296
+ const critical = asArray(output.critical).map(asRecord)
1297
+ .map((item) => ({ instruction: asString(item.issue), chapterNumber: asInteger(item.chapterNumber, 0, 0, MAX_BOOK_CHAPTERS) }))
1298
+ .filter((item) => item.instruction);
1299
+ const noteOf = (change) => `${change.chapterNumber ? `Chapter ${change.chapterNumber}: ` : ""}${change.instruction}`;
1300
+ const changesRequested = requested.map(noteOf);
1301
+ const criticalNotes = critical.map((item) => `Critical — ${noteOf(item)}`);
1302
+ const guidance = asStringList(output.guidance, 10);
1303
+ const interests = plan.readerReactions.map((reaction) => reaction.interest);
1304
+ const readers = interests.length ? Math.round((interests.reduce((sum, value) => sum + value, 0) / interests.length) * 10) / 10 : undefined;
1305
+ const at = ctx.now().toISOString();
1306
+ design.rounds = [...design.rounds, { round: roundNumber, score, verdict: "revise", ...(readers !== undefined ? { readers } : {}), critical: critical.length, findings: findings.length, at }];
1307
+ const plateau = designPlateau(design);
1308
+ // A score alone never approves: the target and no critical inconsistency; or nothing left to change at all.
1309
+ let outcome = null;
1310
+ let escalate = false;
1311
+ if (!critical.length && verdictGiven === "approve" && score >= target)
1312
+ outcome = "target";
1313
+ else if (!critical.length && !changesRequested.length)
1314
+ outcome = "unchanged";
1315
+ else if (lastRound || plateau) {
1316
+ if (critical.length && !design.escalated)
1317
+ escalate = true;
1318
+ else
1319
+ outcome = lastRound ? "rounds" : "plateau";
1320
+ }
1321
+ if (verdictGiven === "approve" && score < target && !critical.length && changesRequested.length && !outcome) {
1322
+ ctx.insight("warning", withheldApproval(ctx, score, italian ? "il progetto viene rivisto." : "the design is revised.", target));
1323
+ }
1324
+ const figures = { round: roundNumber, rounds: maxRounds, score, target, critical: critical.length, findings: findings.length };
1325
+ const changes = [];
1326
+ const range = planRange(importedChapters(ctx.snapshot), view.lastChapter);
1327
+ const size = planBatchChapters(ctx.state, PLAN_BATCH_CHAPTERS);
1328
+ if (outcome) {
1329
+ plan.approved = true;
1330
+ plan.revisionNotes = [];
1331
+ delete plan.revisionBatches;
1332
+ // The design waits for the author, always: approving it, or starting to write, is the author's.
1333
+ plan.awaitingAuthor = true;
1334
+ const left = outcome === "rounds" || outcome === "plateau" ? [...criticalNotes, ...changesRequested] : [];
1335
+ ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, [...guidance, ...left]);
1336
+ design.rounds[design.rounds.length - 1].verdict = "approve";
1337
+ changes.push(...await approvedPlanChanges(ctx, plan));
1338
+ endDesign(ctx.state, outcome, at);
1339
+ const chapters = plan.chapters.filter((chapter) => !chapter.imported).length;
1340
+ const reached = outcome === "target" || outcome === "unchanged";
1341
+ const tone = critical.length ? "warning" : reached ? "ok" : "info";
1342
+ const title = italian
1343
+ ? `Progetto pronto: ${chapters} capitoli, approvato dal direttore con ${score}/10${reached ? "" : outcome === "plateau" ? " (i giri non lo miglioravano più)" : " (dopo i giri permessi)"}`
1344
+ : `Design ready: ${chapters} chapters, approved by the director with ${score}/10${reached ? "" : outcome === "plateau" ? " (the rounds stopped improving it)" : " (after the rounds allowed)"}`;
1345
+ const leftDetail = left.length ? `${italian ? "Resta come indicazione per la scrittura" : "Left as guidance for the writing"}: ${left.slice(0, 4).join(" · ")}` : "";
1346
+ ctx.insight(tone, title, [summaryText, leftDetail].filter(Boolean).join("\n"), { code: "designReady", figures: { ...figures, designOutcome: outcome, chapters } });
1347
+ }
1348
+ else {
1349
+ plan.rounds += 1;
1350
+ plan.revisionNotes = [...criticalNotes, ...changesRequested];
1351
+ plan.revisionBatches = batchesNamed(range, [...critical, ...requested].map((change) => change.chapterNumber), size);
1352
+ // The readers read the design again before the next review while the policy says so.
1353
+ if (plan.rounds < designReaderRounds(ctx.state)) {
1354
+ plan.readersDone = false;
1355
+ plan.readerReactions = [];
1356
+ delete plan.skippedReaders;
1357
+ }
1358
+ ctx.insight("warning", italian
1359
+ ? `Giro ${roundNumber} del progetto: ${score}/10 (obiettivo ${target}/10), ${plan.revisionNotes.length} modifiche${critical.length ? `, ${critical.length} incoerenze critiche` : ""}`
1360
+ : `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 });
1361
+ if (escalate) {
1362
+ design.escalated = true;
1363
+ ctx.state.question = {
1364
+ id: `question-${ctx.now().getTime()}`,
1365
+ kind: "director",
1366
+ question: italian
1367
+ ? `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?`
1368
+ : `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?`,
1369
+ context: criticalNotes.join("\n"),
1370
+ options: italian
1371
+ ? ["Correggile come ritieni meglio", "Tieni il progetto com'è: la scrittura ne terrà conto"]
1372
+ : ["Fix them as you see best", "Keep the design as it is: the writing will take them into account"],
1373
+ askedAt: at,
1374
+ };
1375
+ 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 });
1376
+ }
1377
+ }
1378
+ const question = asRecord(output.questionForAuthor);
1379
+ if (!ctx.state.question && ctx.director.autonomy !== "full" && asString(question.question)) {
1380
+ ctx.state.question = {
1381
+ id: `question-${ctx.now().getTime()}`,
1382
+ kind: "director",
1383
+ question: asString(question.question),
1384
+ context: summaryText,
1385
+ options: asStringList(question.options, 5),
1386
+ askedAt: at,
1387
+ };
1388
+ }
1389
+ changes.push(await planFileChange(ctx));
1390
+ return { changes: compact(changes), summary: `${outcome ? "approve" : "revise"} ${score}/10 — ${summaryText}` };
1391
+ }
1008
1392
  // ─── The author changed the outline of a chapter not written yet ────────────
1009
1393
  /**
1010
1394
  * 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