narrarium-engine 0.1.24 → 0.1.26

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 (87) hide show
  1. package/README.md +21 -3
  2. package/dist/ai/config.d.ts +27 -0
  3. package/dist/ai/config.d.ts.map +1 -1
  4. package/dist/ai/config.js +16 -1
  5. package/dist/ai/config.js.map +1 -1
  6. package/dist/ai/fetch-client.d.ts +2 -2
  7. package/dist/ai/fetch-client.d.ts.map +1 -1
  8. package/dist/ai/fetch-client.js +54 -5
  9. package/dist/ai/fetch-client.js.map +1 -1
  10. package/dist/ai/memory.d.ts +30 -6
  11. package/dist/ai/memory.d.ts.map +1 -1
  12. package/dist/ai/memory.js +15 -2
  13. package/dist/ai/memory.js.map +1 -1
  14. package/dist/ai/prompt-cache.d.ts +41 -0
  15. package/dist/ai/prompt-cache.d.ts.map +1 -0
  16. package/dist/ai/prompt-cache.js +76 -0
  17. package/dist/ai/prompt-cache.js.map +1 -0
  18. package/dist/ai/request.d.ts +6 -1
  19. package/dist/ai/request.d.ts.map +1 -1
  20. package/dist/ai/request.js +76 -1
  21. package/dist/ai/request.js.map +1 -1
  22. package/dist/ai/router.d.ts +5 -1
  23. package/dist/ai/router.d.ts.map +1 -1
  24. package/dist/ai/router.js +2 -1
  25. package/dist/ai/router.js.map +1 -1
  26. package/dist/ai/routing.d.ts.map +1 -1
  27. package/dist/ai/routing.js +7 -2
  28. package/dist/ai/routing.js.map +1 -1
  29. package/dist/ai/types.d.ts +19 -1
  30. package/dist/ai/types.d.ts.map +1 -1
  31. package/dist/ai/types.js.map +1 -1
  32. package/dist/autopilot/campaign.d.ts +9 -2
  33. package/dist/autopilot/campaign.d.ts.map +1 -1
  34. package/dist/autopilot/campaign.js +84 -14
  35. package/dist/autopilot/campaign.js.map +1 -1
  36. package/dist/autopilot/estimate-texts.d.ts +5 -0
  37. package/dist/autopilot/estimate-texts.d.ts.map +1 -1
  38. package/dist/autopilot/estimate-texts.js +9 -3
  39. package/dist/autopilot/estimate-texts.js.map +1 -1
  40. package/dist/autopilot/estimate.d.ts +25 -3
  41. package/dist/autopilot/estimate.d.ts.map +1 -1
  42. package/dist/autopilot/estimate.js +70 -20
  43. package/dist/autopilot/estimate.js.map +1 -1
  44. package/dist/autopilot/frozen.d.ts +2 -0
  45. package/dist/autopilot/frozen.d.ts.map +1 -1
  46. package/dist/autopilot/frozen.js.map +1 -1
  47. package/dist/autopilot/planner.d.ts +1 -0
  48. package/dist/autopilot/planner.d.ts.map +1 -1
  49. package/dist/autopilot/planner.js +133 -12
  50. package/dist/autopilot/planner.js.map +1 -1
  51. package/dist/autopilot/review-policy.d.ts +25 -5
  52. package/dist/autopilot/review-policy.d.ts.map +1 -1
  53. package/dist/autopilot/review-policy.js +84 -2
  54. package/dist/autopilot/review-policy.js.map +1 -1
  55. package/dist/autopilot/review-readers.d.ts +69 -0
  56. package/dist/autopilot/review-readers.d.ts.map +1 -0
  57. package/dist/autopilot/review-readers.js +79 -0
  58. package/dist/autopilot/review-readers.js.map +1 -0
  59. package/dist/autopilot/runner.d.ts +2 -0
  60. package/dist/autopilot/runner.d.ts.map +1 -1
  61. package/dist/autopilot/runner.js +22 -0
  62. package/dist/autopilot/runner.js.map +1 -1
  63. package/dist/autopilot/state.d.ts +11 -0
  64. package/dist/autopilot/state.d.ts.map +1 -1
  65. package/dist/autopilot/state.js +60 -5
  66. package/dist/autopilot/state.js.map +1 -1
  67. package/dist/autopilot/tasks.d.ts.map +1 -1
  68. package/dist/autopilot/tasks.js +138 -60
  69. package/dist/autopilot/tasks.js.map +1 -1
  70. package/dist/autopilot/types.d.ts +93 -11
  71. package/dist/autopilot/types.d.ts.map +1 -1
  72. package/dist/autopilot/types.js +2 -0
  73. package/dist/autopilot/types.js.map +1 -1
  74. package/dist/index.d.ts +2 -0
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +2 -0
  77. package/dist/index.js.map +1 -1
  78. package/dist/server/client.d.ts.map +1 -1
  79. package/dist/server/client.js +9 -2
  80. package/dist/server/client.js.map +1 -1
  81. package/dist/server/protocol.d.ts +20 -0
  82. package/dist/server/protocol.d.ts.map +1 -1
  83. package/dist/server/protocol.js +24 -0
  84. package/dist/server/protocol.js.map +1 -1
  85. package/dist/version.d.ts +1 -1
  86. package/dist/version.js +1 -1
  87. package/package.json +1 -1
@@ -1,6 +1,6 @@
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, referencedChapterNumber, 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
6
  import { OUTLINE_TITLE_MAX_CHARS, OutlineReader, outlineBookDigest, outlineDesignOf, outlineEntryDigest, serializeOutlineBook, serializeOutlineChapter, wholeDesignPatch } from "../book/outline.js";
@@ -17,12 +17,13 @@ import { asArray, asInteger, asOneOf, asRecord, asString, asStringList } from ".
17
17
  import { bulletList, clipText, countWords, isItalian, languageName, OUTPUT_TOKENS_CEILING, sceneCharacterLimit, scaleOutputTokens, tokensPerWord, truncate } from "../util/text.js";
18
18
  import { chapterLines, layoutChapters, listSection, outlineList } from "./outline.js";
19
19
  import { legacyChapters, queuedMarkReviewed, startedReview } from "./frozen.js";
20
- import { reviewMaxRounds, reviewTarget } from "./review-policy.js";
20
+ import { readerGate, reviewMaxRounds, reviewReaderTargets, reviewTarget } from "./review-policy.js";
21
+ import { blockersText, readerStanding } from "./review-readers.js";
21
22
  import { PLAN_BATCH_CHAPTERS, SCENES_PER_CHAPTER, batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts, sceneFile, scenesForChapter } from "./planner.js";
22
23
  import { designFindingsInsight, designLastRound, designPlateau, designReaderRounds, designTarget, endDesign, loadDesignCheckInput, planBatchChapters } from "./design.js";
23
24
  import { outlineDesignGaps } from "./outline-check.js";
24
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";
25
- import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES, CONCEPT_LOGLINE_CHARACTERS, closedRound, designActive, designMaxRounds, normalizeFinalReview, recordChapterRound } from "./state.js";
26
+ import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES, CONCEPT_LOGLINE_CHARACTERS, closedRound, designActive, designMaxRounds, normalizeFinalReview, readingRound, recordChapterRound } from "./state.js";
26
27
  import { STORY_SO_FAR_MAX_WORDS, STORY_SO_FAR_TARGET_WORDS, pruneStorySnapshots, readStorySoFar, renderTotalResumeBody, storySoFarExcess } from "./story-so-far.js";
27
28
  // ─── Shared prompt fragments ────────────────────────────────────────────────
28
29
  function bookHeader(ctx) {
@@ -89,6 +90,20 @@ function data(sections) {
89
90
  function request(lines) {
90
91
  return currentRequest(lines.filter((line) => Boolean(line && line.trim())).join("\n\n"));
91
92
  }
93
+ /**
94
+ * The prompt of a call that is made again and again about the same material (the rounds of a review, the revisions of a plan, the scenes repaired of a chapter): what stays the same from one call to the next
95
+ * (`stable`) first, then what changes with each call (`changing`: the fixes of the last round, the findings of this one), and the request, which changes too, last. A provider that caches the start of a prompt serves
96
+ * everything before the first thing that changes from its cache, and one that has to be told where (`cache_control`) is told it ends there. The words are the same as with the request first: only their order is not.
97
+ */
98
+ function stableFirst(stable, changing, asked) {
99
+ const closing = "\n</repository_content>";
100
+ const text = data([...stable, ...changing]);
101
+ const first = data(stable);
102
+ // The stable sections end where the first one that changes begins: inside the one block of data, after their blank line (`data` joins the sections with one); when nothing changes, where the request begins.
103
+ const changes = changing.some((section) => Boolean(section && section.trim()));
104
+ const stableEnd = changes ? first.length - closing.length + 2 : text.length + 2;
105
+ return { user: `${text}\n\n${asked}`, cacheBreak: Math.min(stableEnd, text.length + 2) };
106
+ }
92
107
  /** A limit on the reply of a step, sized for a book in a Latin script and grown for the language of this one (unchanged for Italian and English). */
93
108
  function outputLimit(ctx, tokens) {
94
109
  return scaleOutputTokens(tokens, ctx.snapshot.book.language);
@@ -1118,27 +1133,28 @@ async function runPlanReview(ctx) {
1118
1133
  capability: AI_CAPABILITIES.director,
1119
1134
  label: "autopilot:plan-review",
1120
1135
  system: directorSystemPrompt(ctx.director, ctx.language),
1121
- user: `${request([
1122
- `Review the concept and the chapter plan before any prose is written (review ${plan.rounds + 1}).`,
1123
- "Approve when the plan delivers the brief and the vision with a satisfying shape; otherwise list precise changes chapter by chapter. Weigh the simulated readers by their weights: do not chase every opinion.",
1124
- view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) binds the plan: never ask to change its chapters, their order, their titles or their events; ask only for what enriches them." : "",
1125
- style.rule,
1126
- lastRound ? "This is the final plan review: approve it and turn anything still imperfect into standing guidance." : "",
1127
- ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical choice you cannot settle from the vision and the author's rules.",
1128
- authorRules(ctx, false),
1129
- ])}\n\n${data([
1136
+ ...stableFirst([
1130
1137
  bookHeader(ctx),
1131
1138
  briefBlock(ctx),
1132
1139
  outlineBookSection(view),
1133
- outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1134
1140
  style.block,
1135
1141
  design ? `STORY DESIGN:\n${design}` : "",
1136
1142
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
1143
+ ], [
1144
+ outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1137
1145
  listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
1138
1146
  plan.readerReactions.length
1139
1147
  ? `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")}`
1140
1148
  : "",
1141
- ])}`,
1149
+ ], request([
1150
+ `Review the concept and the chapter plan before any prose is written (review ${plan.rounds + 1}).`,
1151
+ "Approve when the plan delivers the brief and the vision with a satisfying shape; otherwise list precise changes chapter by chapter. Weigh the simulated readers by their weights: do not chase every opinion.",
1152
+ view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) binds the plan: never ask to change its chapters, their order, their titles or their events; ask only for what enriches them." : "",
1153
+ style.rule,
1154
+ lastRound ? "This is the final plan review: approve it and turn anything still imperfect into standing guidance." : "",
1155
+ ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical choice you cannot settle from the vision and the author's rules.",
1156
+ authorRules(ctx, false),
1157
+ ])),
1142
1158
  json: PLAN_REVIEW_TOOL,
1143
1159
  maxOutputTokens: outputLimit(ctx, 4000),
1144
1160
  });
@@ -1256,23 +1272,15 @@ async function runDesignReview(ctx) {
1256
1272
  capability: AI_CAPABILITIES.director,
1257
1273
  label: "autopilot:plan-review",
1258
1274
  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([
1275
+ ...stableFirst([
1269
1276
  bookHeader(ctx),
1270
1277
  briefBlock(ctx),
1271
1278
  outlineBookSection(view),
1272
- outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1273
1279
  style.block,
1274
1280
  storyDesign ? `STORY DESIGN:\n${storyDesign}` : "",
1275
1281
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
1282
+ ], [
1283
+ outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1276
1284
  ...designData.sections,
1277
1285
  listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
1278
1286
  entriesSection,
@@ -1280,7 +1288,16 @@ async function runDesignReview(ctx) {
1280
1288
  plan.readerReactions.length
1281
1289
  ? `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
1290
  : "",
1283
- ])}`,
1291
+ ], request([
1292
+ `Review the design of the book before any prose is written (review ${roundNumber} of at most ${Math.max(maxRounds, roundNumber)}).`,
1293
+ `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.`,
1294
+ ...DESIGN_DIRECTOR_RULES,
1295
+ 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." : "",
1296
+ style.rule,
1297
+ 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." : "",
1298
+ 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.",
1299
+ authorRules(ctx, false),
1300
+ ])),
1284
1301
  json: DESIGN_REVIEW_TOOL,
1285
1302
  maxOutputTokens: outputLimit(ctx, 5000),
1286
1303
  });
@@ -1677,6 +1694,32 @@ async function chapterSource(ctx, chapter) {
1677
1694
  const readerText = chapterReaderText(paragraphs.map((paragraph) => ({ title: paragraph.title, raw: paragraph.raw })));
1678
1695
  return { paragraphs, readerText, sourceHash: await sha256Hex(readerText), sourceVersion: paragraphs.map((paragraph) => paragraph.hash).join(":") };
1679
1696
  }
1697
+ /** 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`). */
1698
+ function readingSlugs(ctx) {
1699
+ return activeReaders(ctx.readerPanel, ctx.director, ctx.state.options.maxReaders).map((reader) => reader.slug);
1700
+ }
1701
+ /** 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. */
1702
+ function readersGateOf(ctx) {
1703
+ return readerGate(ctx.state, readingSlugs(ctx));
1704
+ }
1705
+ /** What the readers said in the review, as a round records it: each reader's vote, the readers that do not count, the round. */
1706
+ function readingOf(ctx, review, round = review.round) {
1707
+ const targets = reviewReaderTargets(ctx.state);
1708
+ if (!targets || !review.readerScores.length)
1709
+ return undefined;
1710
+ return { votes: Object.fromEntries(review.readerScores.map((score) => [score.slug, score.score])), excluded: targets.excluded, round };
1711
+ }
1712
+ /** 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. */
1713
+ function readersTargetsBlock(ctx, review, targets) {
1714
+ const nameOf = (slug) => review.readerScores.find((score) => score.slug === slug)?.name ?? ctx.readerPanel.find((reader) => reader.slug === slug)?.name ?? slug;
1715
+ const standing = review.readerScores.length ? readerStanding(review.readerScores.map((score) => ({ slug: score.slug, score: score.score })), targets) : null;
1716
+ const lines = [
1717
+ targets.average !== undefined ? `- the average of the readers that count: ${standing?.average != null ? `${standing.average}/10 now, ` : ""}target ${targets.average}/10` : "",
1718
+ ...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`),
1719
+ ...[...targets.excluded].map((slug) => `- ${nameOf(slug)}: does not count (left out of the average and of the targets)`),
1720
+ ].filter(Boolean);
1721
+ 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")}`;
1722
+ }
1680
1723
  async function runReader(ctx) {
1681
1724
  const chapter = chapterOf(ctx);
1682
1725
  const review = ctx.state.review;
@@ -1806,6 +1849,12 @@ async function runReadersSummary(ctx) {
1806
1849
  }));
1807
1850
  review.findings = [...review.findings.filter((finding) => finding.source !== "reader"), ...findings];
1808
1851
  review.readersSummaryDone = true;
1852
+ // 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.
1853
+ const reading = review.reading && !review.readRecorded ? readingOf(ctx, review) : undefined;
1854
+ if (reading && review.reading) {
1855
+ recordChapterRound(chapter, readingRound({ ...reading, reading: review.reading }));
1856
+ review.readRecorded = true;
1857
+ }
1809
1858
  ctx.insight(overall >= 7 ? "ok" : overall >= 5 ? "info" : "warning", isItalian(ctx.language) ? `Lettori: ${overall}/10` : `Readers: ${overall}/10`, asStringList(output.consensus, 2).join(" · "));
1810
1859
  return { changes: compact([change]), summary: `${overall}/10 — ${findings.length} proposals for the director` };
1811
1860
  }
@@ -1823,12 +1872,7 @@ async function runSpecialists(ctx) {
1823
1872
  capability: AI_CAPABILITIES.specialist,
1824
1873
  label: `autopilot:specialists:${chapter.number}`,
1825
1874
  system: specialistsSystemPrompt(ctx.language),
1826
- user: `${request([
1827
- `Review chapter ${chapter.number} «${chapter.title}» (review round ${review.round}). Return at most 12 findings, most important first, using the scene numbers of the markers.`,
1828
- review.previousFixes.length ? `These fixes were applied after the previous round: verify them and report only remaining or new real problems.\n${bulletList(review.previousFixes)}` : "",
1829
- style.rule,
1830
- authorRules(ctx, false),
1831
- ])}\n\n${data([
1875
+ ...stableFirst([
1832
1876
  bookHeader(ctx),
1833
1877
  `GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
1834
1878
  style.block,
@@ -1836,10 +1880,16 @@ async function runSpecialists(ctx) {
1836
1880
  chapterPlanBlock(chapter),
1837
1881
  `SCENE PLANS:\n${chapter.scenes.map((scene) => `- Scene ${scene.number} «${scene.title}»: ${scene.goal}`).join("\n")}`,
1838
1882
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: false }) || "-"}`,
1839
- relevant.length ? `CANON DETAILS:\n${await canonDetails(ctx.store, relevant, 600)}` : "",
1840
1883
  secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
1841
1884
  `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, sceneLimit(ctx, 14000))}`,
1842
- ])}`,
1885
+ // What the chapter's text names is read from the text: it goes after it, so that everything before the text stays the same while the text is not touched.
1886
+ relevant.length ? `CANON DETAILS:\n${await canonDetails(ctx.store, relevant, 600)}` : "",
1887
+ ], [], request([
1888
+ `Review chapter ${chapter.number} «${chapter.title}» (review round ${review.round}). Return at most 12 findings, most important first, using the scene numbers of the markers.`,
1889
+ review.previousFixes.length ? `These fixes were applied after the previous round: verify them and report only remaining or new real problems.\n${bulletList(review.previousFixes)}` : "",
1890
+ style.rule,
1891
+ authorRules(ctx, false),
1892
+ ])),
1843
1893
  json: FINDINGS_TOOL,
1844
1894
  maxOutputTokens: outputLimit(ctx, 5000),
1845
1895
  });
@@ -1897,6 +1947,8 @@ async function runDirectorReview(ctx) {
1897
1947
  const maxRounds = reviewMaxRounds(ctx.state, ctx.director);
1898
1948
  const target = reviewTarget(ctx.state, ctx.director);
1899
1949
  const last = review.round >= maxRounds;
1950
+ // The targets for the readers, when the review has them: the director is told they are rules too, and where the readers stand.
1951
+ const gate = review.authorEdit ? undefined : readersGateOf(ctx);
1900
1952
  const perScene = sceneLimit(ctx, Math.max(3000, Math.floor(60000 / Math.max(1, source.paragraphs.length))));
1901
1953
  const style = evaluationStyleOf(ctx, "chapter");
1902
1954
  const authorNote = review.authorEdit ? startedReview(ctx.state)?.note : undefined;
@@ -1905,19 +1957,7 @@ async function runDirectorReview(ctx) {
1905
1957
  label: `autopilot:director-review:${chapter.number}`,
1906
1958
  // The profile as the policy makes it: its approval score is the target (the same profile, word for word, without a policy).
1907
1959
  system: directorSystemPrompt(target === ctx.director.approvalScore ? ctx.director : { ...ctx.director, approvalScore: target }, ctx.language),
1908
- user: `${request([
1909
- `Decide on chapter ${chapter.number} «${chapter.title}» (review round ${review.round} of ${maxRounds}).`,
1910
- "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.",
1911
- `Score the chapter from 1 to 10. Verdict "approve" when it deserves at least ${target}/10 and nothing critical remains; otherwise "revise".`,
1912
- style.rule,
1913
- review.authorEdit
1914
- ? "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."
1915
- : last ? "This is the LAST review round: accepted fixes will be applied and the chapter closed without another review, so accept only what really matters." : "",
1916
- authorNote ? `The author's note on the change: «${authorNote}»` : "",
1917
- "Add standing guidance for the next chapters when this chapter taught you something.",
1918
- ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical matter you must not settle alone.",
1919
- authorRules(ctx, false),
1920
- ])}\n\n${data([
1960
+ ...stableFirst([
1921
1961
  bookHeader(ctx),
1922
1962
  directorGuidance(ctx),
1923
1963
  style.block,
@@ -1929,10 +1969,26 @@ async function runDirectorReview(ctx) {
1929
1969
  ? `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")}`
1930
1970
  : "",
1931
1971
  readersSummary ? `READERS PANEL SUMMARY:\n${readersSummary}` : "",
1972
+ gate ? readersTargetsBlock(ctx, review, gate) : "",
1973
+ `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, perScene)}`,
1974
+ // What changes with each round (the fixes of the last one, the findings of this one) goes after the text, which does not change until a fix is applied.
1975
+ ], [
1932
1976
  review.previousFixes.length ? `FIXES APPLIED AFTER THE PREVIOUS ROUND:\n${bulletList(review.previousFixes)}` : "",
1933
1977
  `FINDINGS TO DECIDE:\n${review.findings.length ? review.findings.map(findingLine).join("\n\n") : "None."}`,
1934
- `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, perScene)}`,
1935
- ])}`,
1978
+ ], request([
1979
+ `Decide on chapter ${chapter.number} «${chapter.title}» (review round ${review.round} of ${maxRounds}).`,
1980
+ "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.",
1981
+ `Score the chapter from 1 to 10. Verdict "approve" when it deserves at least ${target}/10 and nothing critical remains; otherwise "revise".`,
1982
+ 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." : "",
1983
+ style.rule,
1984
+ review.authorEdit
1985
+ ? "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."
1986
+ : last ? "This is the LAST review round: accepted fixes will be applied and the chapter closed without another review, so accept only what really matters." : "",
1987
+ authorNote ? `The author's note on the change: «${authorNote}»` : "",
1988
+ "Add standing guidance for the next chapters when this chapter taught you something.",
1989
+ ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical matter you must not settle alone.",
1990
+ authorRules(ctx, false),
1991
+ ])),
1936
1992
  json: CHAPTER_REVIEW_TOOL,
1937
1993
  maxOutputTokens: outputLimit(ctx, 6000),
1938
1994
  });
@@ -2022,8 +2078,11 @@ async function runDirectorReview(ctx) {
2022
2078
  review.repairQueue = review.authorEdit ? [] : [...new Set(accepted.map((decision) => decision.sceneNumber))].sort((left, right) => left - right);
2023
2079
  // 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
2024
2080
  // 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.
2025
- const readersReadNow = review.readersRound !== undefined ? review.readersRound === review.round : review.history.length === 0;
2026
- recordChapterRound(chapter, closedRound({ director: score, readers: readersReadNow ? review.readerScores.map((entry) => entry.score) : undefined, verdict, accepted: accepted.length, rejected: rejected.length }));
2081
+ // (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.)
2082
+ const readersReadNow = (review.readersRound !== undefined ? review.readersRound === review.round : review.history.length === 0) && !review.readRecorded;
2083
+ // 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).
2084
+ const reading = readersReadNow ? readingOf(ctx, review) : undefined;
2085
+ recordChapterRound(chapter, closedRound({ director: score, readers: readersReadNow ? review.readerScores.map((entry) => entry.score) : undefined, verdict, accepted: accepted.length, rejected: rejected.length, ...(reading ? { reading } : {}) }));
2027
2086
  review.history = [...review.history, { round: review.round, verdict, score, accepted: accepted.length, rejected: rejected.length }];
2028
2087
  ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, asStringList(output.guidance, 6));
2029
2088
  const question = asRecord(output.questionForAuthor);
@@ -2101,24 +2160,25 @@ async function rewriteScene(ctx, chapter, scene, instructions, mode) {
2101
2160
  capability: AI_CAPABILITIES.writer,
2102
2161
  label: `autopilot:${mode}:${chapter.number}.${scene.number}`,
2103
2162
  system: writerSystemPrompt(ctx.language),
2104
- user: `${request([
2105
- mode === "repair"
2106
- ? `Revise scene ${scene.number} of chapter ${chapter.number} «${scene.title}» applying ONLY these fixes approved by the director:`
2107
- : `Rewrite scene ${scene.number} of chapter ${chapter.number} «${scene.title}» to honor the author's revision:`,
2108
- instructions.map((instruction, index) => `${index + 1}. ${instruction}`).join("\n"),
2109
- "Keep everything else as it is: events, facts, voice, rhythm, secrets and approximate length, unless an instruction requires otherwise. Return the complete revised scene.",
2110
- authorRules(ctx),
2111
- ])}\n\n${data([
2163
+ ...stableFirst([
2112
2164
  bookHeader(ctx),
2113
2165
  `GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
2114
2166
  directorGuidance(ctx),
2167
+ ], [
2115
2168
  scenePlanBlock(scene),
2116
2169
  relevant.length ? `RELEVANT CANON:\n${await canonDetails(ctx.store, relevant)}` : "",
2117
2170
  secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
2118
2171
  neighbors.previousEnding ? `PREVIOUS SCENE ENDING:\n${neighbors.previousEnding}` : "",
2119
2172
  neighbors.nextOpening ? `NEXT SCENE OPENING (keep it consistent):\n${neighbors.nextOpening}` : "",
2120
2173
  `CURRENT SCENE:\n${loaded.document.body}`,
2121
- ])}`,
2174
+ ], request([
2175
+ mode === "repair"
2176
+ ? `Revise scene ${scene.number} of chapter ${chapter.number} «${scene.title}» applying ONLY these fixes approved by the director:`
2177
+ : `Rewrite scene ${scene.number} of chapter ${chapter.number} «${scene.title}» to honor the author's revision:`,
2178
+ instructions.map((instruction, index) => `${index + 1}. ${instruction}`).join("\n"),
2179
+ "Keep everything else as it is: events, facts, voice, rhythm, secrets and approximate length, unless an instruction requires otherwise. Return the complete revised scene.",
2180
+ authorRules(ctx),
2181
+ ])),
2122
2182
  maxOutputTokens: sceneOutputLimit(ctx, Math.max(originalWords, 300)),
2123
2183
  temperature: Math.min(0.7, ghostwriter?.temperature ?? 0.7),
2124
2184
  });
@@ -2149,6 +2209,9 @@ async function runRepair(ctx) {
2149
2209
  scene.words = words;
2150
2210
  if (summary)
2151
2211
  scene.summary = summary;
2212
+ // 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).
2213
+ if (review.readText !== undefined)
2214
+ review.repairs = (review.repairs ?? 0) + 1;
2152
2215
  ctx.insight("ok", isItalian(ctx.language) ? `Scena ${chapter.number}.${scene.number} corretta (${instructions.length})` : `Scene ${chapter.number}.${scene.number} revised (${instructions.length})`, instructions.join(" · "));
2153
2216
  return { changes: [change], summary: `${instructions.length} fixes applied, ${words} words.` };
2154
2217
  }
@@ -2228,6 +2291,21 @@ async function runConsolidate(ctx) {
2228
2291
  changes.push(await renderPlot(ctx));
2229
2292
  changes.push(await planFileChange(ctx));
2230
2293
  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);
2294
+ // Closed with a target of the readers not reached: what stood in the way, and why it was not worked on any more.
2295
+ const gate = review?.gateStop ? reviewReaderTargets(ctx.state) : undefined;
2296
+ if (review && gate) {
2297
+ const standing = readerStanding(review.readerScores.map((score) => ({ slug: score.slug, score: score.score })), gate);
2298
+ const names = (slug) => review.readerScores.find((score) => score.slug === slug)?.name ?? ctx.readerPanel.find((reader) => reader.slug === slug)?.name ?? slug;
2299
+ const italian = isItalian(ctx.language);
2300
+ const averageBlocked = standing.blockers.some((blocker) => blocker.subject === "average");
2301
+ const readersUnder = standing.blockers.filter((blocker) => blocker.subject === "reader").length;
2302
+ const why = review.gateStop === "plateau"
2303
+ ? (italian ? "le ultime correzioni non avvicinavano i lettori all'obiettivo" : "the last corrections did not bring the readers closer to their target")
2304
+ : (italian ? `i giri di revisione permessi (${review.round}) sono finiti` : `the rounds of review allowed (${review.round}) are used`);
2305
+ 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.`,
2306
+ // 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.
2307
+ { 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 } : {}) } });
2308
+ }
2231
2309
  return { changes: compact(changes), summary };
2232
2310
  }
2233
2311
  const WRITTEN_SCENES = {