novelforge-agent 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +82 -14
  2. package/dist/src/cli/index.js +92 -2
  3. package/dist/src/cli/install.js +224 -0
  4. package/dist/src/core/bibleStore.js +36 -0
  5. package/dist/src/core/characterStore.js +74 -0
  6. package/dist/src/core/contextBuilder.js +44 -1
  7. package/dist/src/core/fileNames.js +4 -0
  8. package/dist/src/core/index.js +4 -0
  9. package/dist/src/core/projectOps.js +187 -0
  10. package/dist/src/core/projectStore.js +11 -0
  11. package/dist/src/core/prompts/en-US.js +117 -13
  12. package/dist/src/core/prompts/zh-CN.js +116 -12
  13. package/dist/src/core/retrieval/index.js +8 -0
  14. package/dist/src/core/schemas.js +98 -1
  15. package/dist/src/core/steps/architecture.js +7 -1
  16. package/dist/src/core/steps/chapter.js +11 -1
  17. package/dist/src/core/steps/chapterReview.js +25 -1
  18. package/dist/src/core/steps/chapterRevision.js +17 -0
  19. package/dist/src/core/steps/memoryCard.js +4 -0
  20. package/dist/src/core/steps/novelMetadata.js +4 -2
  21. package/dist/src/core/threadStore.js +150 -0
  22. package/dist/src/core/workflow.js +3 -3
  23. package/dist/src/mcp/tools.js +198 -18
  24. package/package.json +5 -1
  25. package/src/cli/index.ts +94 -1
  26. package/src/cli/install.ts +275 -0
  27. package/src/core/bibleStore.ts +57 -0
  28. package/src/core/characterStore.ts +93 -0
  29. package/src/core/contextBuilder.ts +44 -4
  30. package/src/core/fileNames.ts +5 -0
  31. package/src/core/index.ts +4 -0
  32. package/src/core/projectOps.ts +243 -0
  33. package/src/core/projectStore.ts +11 -0
  34. package/src/core/prompts/en-US.ts +126 -22
  35. package/src/core/prompts/types.ts +2 -1
  36. package/src/core/prompts/zh-CN.ts +118 -14
  37. package/src/core/retrieval/index.ts +10 -0
  38. package/src/core/schemas.ts +108 -1
  39. package/src/core/steps/architecture.ts +7 -1
  40. package/src/core/steps/chapter.ts +11 -1
  41. package/src/core/steps/chapterReview.ts +27 -1
  42. package/src/core/steps/chapterRevision.ts +18 -0
  43. package/src/core/steps/memoryCard.ts +4 -0
  44. package/src/core/steps/novelMetadata.ts +4 -2
  45. package/src/core/threadStore.ts +173 -0
  46. package/src/core/types.ts +102 -1
  47. package/src/core/workflow.ts +3 -3
  48. package/src/mcp/tools.ts +322 -19
@@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { chapterFileName, chapterReviewFileName, memoryFileName } from './fileNames.js';
4
4
  import { formatHits, retrieve } from './retrieval/index.js';
5
+ import { activeThreads, loadThreads } from './threadStore.js';
5
6
  async function readOptional(path) {
6
7
  try {
7
8
  return await readFile(path, 'utf8');
@@ -15,10 +16,26 @@ export async function buildContext(input) {
15
16
  const metadata = await readOptional(join(input.projectPath, 'novel.json'));
16
17
  const storyBible = await readOptional(join(input.projectPath, 'story-bible.md'));
17
18
  const chaptersJson = await readOptional(join(input.projectPath, 'architecture/chapters.json'));
19
+ const charactersJson = await readOptional(join(input.projectPath, 'characters.json'));
20
+ const volumePacingJson = await readOptional(join(input.projectPath, 'architecture/volume-pacing.json'));
18
21
  if (metadata)
19
22
  parts.push(`## Novel Metadata\n${metadata}`);
20
23
  if (storyBible)
21
24
  parts.push(`## Story Bible\n${storyBible.slice(0, 4000)}`);
25
+ if (charactersJson)
26
+ parts.push(`## Character State Table\n${charactersJson}`);
27
+ function addVolumePacing(volumeId) {
28
+ if (!volumePacingJson)
29
+ return;
30
+ try {
31
+ const boards = JSON.parse(volumePacingJson);
32
+ const board = volumeId ? boards.find((item) => item.volumeId === volumeId) : undefined;
33
+ parts.push(`## Volume Pacing Board\n${JSON.stringify(board ?? boards, null, 2)}`);
34
+ }
35
+ catch {
36
+ parts.push(`## Volume Pacing Board\n${volumePacingJson}`);
37
+ }
38
+ }
22
39
  if (input.purpose === 'chapter_generation' && input.chapterNumber) {
23
40
  let currentArchitectureForQuery;
24
41
  if (chaptersJson) {
@@ -27,6 +44,7 @@ export async function buildContext(input) {
27
44
  if (chapter) {
28
45
  currentArchitectureForQuery = chapter;
29
46
  parts.push(`## Current Chapter Architecture\n${JSON.stringify(chapter, null, 2)}`);
47
+ addVolumePacing(chapter.volumeId);
30
48
  }
31
49
  }
32
50
  if (input.chapterNumber > 1) {
@@ -54,6 +72,19 @@ export async function buildContext(input) {
54
72
  if (formatted)
55
73
  parts.push(`## Retrieved Relevant Snippets (lexical, BM25-style)\n${formatted}`);
56
74
  }
75
+ const allThreads = await loadThreads(input.projectPath);
76
+ const active = activeThreads(allThreads);
77
+ if (active.length) {
78
+ const lines = active.map((t) => {
79
+ const flags = [`#${t.id}`, `status=${t.status}`, `planted=ch${t.plantedAt}`];
80
+ if (t.plannedPayoffAt)
81
+ flags.push(`payoff=ch${t.plannedPayoffAt}`);
82
+ if (t.lastTouchedAt !== t.plantedAt)
83
+ flags.push(`touched=ch${t.lastTouchedAt}`);
84
+ return `- ${t.description} (${flags.join(', ')})`;
85
+ });
86
+ parts.push(`## Active Foreshadow Threads (do not silently drop or contradict)\n${lines.join('\n')}`);
87
+ }
57
88
  }
58
89
  }
59
90
  if (input.purpose === 'memory_extraction' && input.chapterNumber) {
@@ -77,8 +108,10 @@ export async function buildContext(input) {
77
108
  if (chaptersJson) {
78
109
  const chapters = JSON.parse(chaptersJson);
79
110
  const arch = chapters.find((item) => item.chapterNumber === input.chapterNumber);
80
- if (arch)
111
+ if (arch) {
81
112
  parts.push(`## Target Chapter Architecture\n${JSON.stringify(arch, null, 2)}`);
113
+ addVolumePacing(arch.volumeId);
114
+ }
82
115
  }
83
116
  const chapter = await readOptional(join(input.projectPath, 'chapters', chapterFileName(input.chapterNumber)));
84
117
  if (chapter)
@@ -93,6 +126,16 @@ export async function buildContext(input) {
93
126
  const chapter = await readOptional(join(input.projectPath, 'chapters', chapterFileName(input.chapterNumber)));
94
127
  if (chapter)
95
128
  parts.push(`## Current Chapter Text\n${chapter}`);
129
+ if (chaptersJson) {
130
+ try {
131
+ const chapters = JSON.parse(chaptersJson);
132
+ const arch = chapters.find((item) => item.chapterNumber === input.chapterNumber);
133
+ addVolumePacing(arch?.volumeId);
134
+ }
135
+ catch {
136
+ // ignore malformed architecture here; review feedback is still useful
137
+ }
138
+ }
96
139
  const review = await readOptional(join(input.projectPath, 'reviews/chapter', chapterReviewFileName(input.chapterNumber)));
97
140
  if (review)
98
141
  parts.push(`## Editor Review\n${review}`);
@@ -39,3 +39,7 @@ export function chapterVersionFileName(chapterNumber, timestamp) {
39
39
  const safeTs = timestamp.replace(/[:.]/g, '-');
40
40
  return `${padChapterNumber(chapterNumber)}.${safeTs}.md`;
41
41
  }
42
+ export function storyBibleVersionFileName(timestamp) {
43
+ const safeTs = timestamp.replace(/[:.]/g, '-');
44
+ return `story-bible.${safeTs}.md`;
45
+ }
@@ -7,3 +7,7 @@ export * from './contextBuilder.js';
7
7
  export * from './prompts.js';
8
8
  export * from './retrieval/index.js';
9
9
  export * from './projectDiscovery.js';
10
+ export * from './threadStore.js';
11
+ export * from './bibleStore.js';
12
+ export * from './projectOps.js';
13
+ export * from './characterStore.js';
@@ -0,0 +1,187 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { cp, readdir, unlink, writeFile } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
+ import { loadState, saveState } from './projectStore.js';
5
+ import { removeChapterFromIndex, removeMemoryCardFromIndex } from './retrieval/index.js';
6
+ import { chapterFileName, memoryFileName } from './fileNames.js';
7
+ export async function forkProject(input) {
8
+ const source = resolve(input.sourceProjectPath);
9
+ const state = await loadState(source);
10
+ const suffix = randomBytes(3).toString('hex');
11
+ const label = (input.label ?? 'fork').replace(/[^a-z0-9-]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase() || 'fork';
12
+ const targetName = `${basename(source)}-${label}-${suffix}`;
13
+ const target = join(dirname(source), targetName);
14
+ await cp(source, target, { recursive: true });
15
+ const forkedState = {
16
+ ...state,
17
+ projectId: randomUUID(),
18
+ projectPath: target,
19
+ createdAt: new Date().toISOString(),
20
+ updatedAt: new Date().toISOString(),
21
+ };
22
+ await saveState(forkedState);
23
+ return { newProjectPath: target, newProjectId: forkedState.projectId };
24
+ }
25
+ async function tryUnlink(path) {
26
+ try {
27
+ await unlink(path);
28
+ return true;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ async function tryRmDirEntry(dirPath, prefix) {
35
+ const removed = [];
36
+ try {
37
+ const items = await readdir(dirPath);
38
+ for (const item of items) {
39
+ if (item.startsWith(prefix)) {
40
+ const full = join(dirPath, item);
41
+ try {
42
+ await unlink(full);
43
+ removed.push(full);
44
+ }
45
+ catch {
46
+ // ignore
47
+ }
48
+ }
49
+ }
50
+ }
51
+ catch {
52
+ // dir absent
53
+ }
54
+ return removed;
55
+ }
56
+ export async function deleteChapter(input) {
57
+ const state = await loadState(input.projectPath);
58
+ const n = input.chapterNumber;
59
+ if (n < 1)
60
+ throw new Error('chapterNumber must be >= 1');
61
+ const removed = [];
62
+ const chapterRel = join('chapters', chapterFileName(n));
63
+ if (await tryUnlink(join(state.projectPath, chapterRel)))
64
+ removed.push(chapterRel);
65
+ const memoryRel = join('memory', memoryFileName(n));
66
+ if (await tryUnlink(join(state.projectPath, memoryRel)))
67
+ removed.push(memoryRel);
68
+ // Versions of this chapter
69
+ const versionsRemoved = await tryRmDirEntry(join(state.projectPath, 'chapters/.versions'), `${chapterFileName(n).replace(/\.md$/, '')}.`);
70
+ removed.push(...versionsRemoved);
71
+ // Per-chapter review
72
+ const reviewName = `chapter-${String(n).padStart(3, '0')}.json`;
73
+ if (await tryUnlink(join(state.projectPath, 'reviews/chapter', reviewName))) {
74
+ removed.push(`reviews/chapter/${reviewName}`);
75
+ }
76
+ // Update state.files
77
+ const nextFiles = { ...state.files };
78
+ delete nextFiles[`chapter-${n}`];
79
+ delete nextFiles[`memory-${n}`];
80
+ delete nextFiles[`review-chapter-${n}`];
81
+ // Remove this chapter and its memory card from the lexical index
82
+ await removeChapterFromIndex(state.projectPath, n);
83
+ await removeMemoryCardFromIndex(state.projectPath, n);
84
+ // Adjust state.currentChapter & currentStep if needed
85
+ let newCurrentChapter = state.currentChapter;
86
+ let newCurrentStep = state.currentStep;
87
+ if (state.currentChapter > n) {
88
+ // user deleted an earlier chapter; current pointer becomes the deleted one to be regenerated
89
+ newCurrentChapter = n;
90
+ newCurrentStep = 'chapter';
91
+ }
92
+ else if (state.currentChapter === n + 1 && (state.currentStep === 'chapter' || state.currentStep === 'memory_card')) {
93
+ // we just finished chapter n and were about to do n+1; step back
94
+ newCurrentChapter = n;
95
+ newCurrentStep = 'chapter';
96
+ }
97
+ const nextState = {
98
+ ...state,
99
+ files: nextFiles,
100
+ currentChapter: newCurrentChapter,
101
+ currentStep: newCurrentStep,
102
+ pendingAction: undefined,
103
+ };
104
+ await saveState(nextState);
105
+ return { removed, newCurrentChapter, newCurrentStep };
106
+ }
107
+ const STEP_FILE_KEYS = {
108
+ novel_metadata: ['novel'],
109
+ story_bible: ['storyBible'],
110
+ architecture: ['architecture'],
111
+ continuity_review: ['continuityReview'],
112
+ };
113
+ const STEP_FILE_PATHS = {
114
+ novel_metadata: ['novel.json'],
115
+ story_bible: ['story-bible.md'],
116
+ architecture: ['architecture/full.md', 'architecture/volumes.json', 'architecture/chapters.json'],
117
+ };
118
+ export async function redoStep(input) {
119
+ const state = await loadState(input.projectPath);
120
+ const removed = [];
121
+ if (input.step === 'chapter' || input.step === 'memory_card') {
122
+ const chapter = input.chapterNumber ?? state.currentChapter;
123
+ if (input.step === 'memory_card') {
124
+ const rel = join('memory', memoryFileName(chapter));
125
+ if (await tryUnlink(join(state.projectPath, rel)))
126
+ removed.push(rel);
127
+ delete state.files[`memory-${chapter}`];
128
+ }
129
+ else {
130
+ // chapter: also remove its memory + per-chapter review since they depend on it
131
+ const cRel = join('chapters', chapterFileName(chapter));
132
+ if (await tryUnlink(join(state.projectPath, cRel)))
133
+ removed.push(cRel);
134
+ const mRel = join('memory', memoryFileName(chapter));
135
+ if (await tryUnlink(join(state.projectPath, mRel)))
136
+ removed.push(mRel);
137
+ delete state.files[`chapter-${chapter}`];
138
+ delete state.files[`memory-${chapter}`];
139
+ await removeChapterFromIndex(state.projectPath, chapter);
140
+ await removeMemoryCardFromIndex(state.projectPath, chapter);
141
+ }
142
+ state.currentChapter = chapter;
143
+ state.currentStep = input.step;
144
+ state.pendingAction = undefined;
145
+ }
146
+ else if (input.step === 'novel_metadata' || input.step === 'story_bible' || input.step === 'architecture' || input.step === 'continuity_review') {
147
+ const paths = STEP_FILE_PATHS[input.step] ?? [];
148
+ for (const p of paths) {
149
+ if (await tryUnlink(join(state.projectPath, p)))
150
+ removed.push(p);
151
+ }
152
+ const keys = STEP_FILE_KEYS[input.step] ?? [];
153
+ for (const k of keys) {
154
+ delete state.files[k];
155
+ }
156
+ state.currentStep = input.step;
157
+ state.pendingAction = undefined;
158
+ if (input.step === 'novel_metadata')
159
+ state.currentChapter = 1;
160
+ }
161
+ else {
162
+ throw new Error(`redo_step does not support step: ${input.step}`);
163
+ }
164
+ // Trim completedSteps after the redo target
165
+ const idx = state.completedSteps.lastIndexOf(input.step);
166
+ if (idx >= 0)
167
+ state.completedSteps = state.completedSteps.slice(0, idx);
168
+ await saveState(state);
169
+ return {
170
+ removed,
171
+ currentStep: state.currentStep,
172
+ currentChapter: state.currentChapter,
173
+ };
174
+ }
175
+ // =============================================================================
176
+ // guards
177
+ // =============================================================================
178
+ export function assertProjectPath(workspaceRoot, projectPath) {
179
+ const root = resolve(workspaceRoot);
180
+ const target = resolve(projectPath);
181
+ const rel = relative(root, target);
182
+ if (rel.startsWith('..') || isAbsolute(rel)) {
183
+ throw new Error(`Refusing to operate outside workspace: ${target}`);
184
+ }
185
+ }
186
+ // keep tsc happy if no other refs
187
+ void writeFile;
@@ -15,6 +15,7 @@ export async function ensureProjectDirectories(projectPath) {
15
15
  await mkdir(join(projectPath, 'architecture'), { recursive: true });
16
16
  await mkdir(join(projectPath, 'chapters'), { recursive: true });
17
17
  await mkdir(join(projectPath, 'chapters/.versions'), { recursive: true });
18
+ await mkdir(join(projectPath, 'story-bible-versions'), { recursive: true });
18
19
  await mkdir(join(projectPath, 'memory'), { recursive: true });
19
20
  await mkdir(join(projectPath, 'reviews'), { recursive: true });
20
21
  await mkdir(join(projectPath, 'reviews/chapter'), { recursive: true });
@@ -31,6 +32,16 @@ export async function archiveChapterVersion(projectPath, chapterRelative, versio
31
32
  return undefined;
32
33
  }
33
34
  }
35
+ export async function archiveStoryBible(projectPath, versionRelative) {
36
+ const sourcePath = join(projectPath, 'story-bible.md');
37
+ try {
38
+ const existing = await readFile(sourcePath, 'utf8');
39
+ return saveMarkdownFile(projectPath, versionRelative, existing);
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
34
45
  export async function createProject(input) {
35
46
  const workspaceRoot = resolve(input.workspaceRoot);
36
47
  const baseDir = input.outputDir || 'novels';
@@ -101,6 +101,18 @@ Output valid JSON only, in this shape:
101
101
  "order": 1
102
102
  }
103
103
  ],
104
+ "volumePacing": [
105
+ {
106
+ "volumeId": "v1",
107
+ "start": "Volume starting state: protagonist/world/conflict",
108
+ "promise": "Core reader promise or question for this volume",
109
+ "keyTurns": ["Key turn 1", "Key turn 2"],
110
+ "midpoint": "Midpoint turn or changed understanding",
111
+ "climax": "Volume climax",
112
+ "payoffs": ["Threads or promises this volume plans to pay off"],
113
+ "lingeringMysteries": ["Mysteries intentionally left open at volume end"]
114
+ }
115
+ ],
104
116
  "chapters": [
105
117
  {
106
118
  "chapterNumber": 1,
@@ -116,36 +128,50 @@ Rules:
116
128
  - chapters.length must be at least ${input.state.targetChapters}.
117
129
  - chapterNumber must start at 1 and increase contiguously.
118
130
  - volumeId must reference an id from volumes.
131
+ - volumePacing must provide one pacing board for every volume.
119
132
  - requiredBeats must include at least one concrete, actionable beat.
120
133
  ${strictJsonOutputRules()}`,
121
134
  };
122
135
  }
123
136
  function buildChapterPrompt(input) {
137
+ const ch = input.state.currentChapter;
138
+ const isFirstChapter = ch <= 1;
124
139
  return {
125
140
  purpose: 'chapter',
126
141
  expectedFormat: 'Markdown',
127
- prompt: `You are a professional long-form fiction writer. Write chapter ${input.state.currentChapter} directly.
142
+ prompt: `You are a professional long-form fiction writer. Write chapter ${ch} directly.
128
143
 
129
144
  ## Priority Order
130
145
  1. Strictly follow the current chapter architecture, user additions, story bible hard constraints, and previous-chapter continuity.
131
- 2. Use relevant memory and prior text evidence to preserve consistency.
146
+ 2. Use relevant memory, prior text evidence, and active foreshadow threads.
132
147
  3. Treat full-book and volume plans as distant planning context only. Do not write concrete future events early.
133
148
 
134
- ## Style And Length
149
+ ## Length Target
150
+ - Default target: ~2500 words (±20%). If the chapter architecture specifies targetWords, follow it.
151
+ - Do not pad to hit the target; do not under-write to be brief at the cost of conflict.
152
+
153
+ ## Structure
154
+ ${isFirstChapter
155
+ ? '- This is chapter 1. No recap needed. Open with character and situation directly.'
156
+ : '- Start with a 2-3 sentence recap or bridge so a reader who skipped the last chapter can re-enter (unless the chapter architecture has requireRecap=false). Make it natural, not meta-narration like "previously...".'}
157
+ - The chapter must end on a clear hook: cliffhanger, mystery, emotional resonance, reveal, or volume close — per the chapter architecture endHookFocus. Default: cliffhanger.
158
+
159
+ ## Style
135
160
  - Match the novel's genre, world, character identities, and emotional tone.
136
- - Keep the language natural, stable, and readable. Prioritize narrative progress, character work, and emotional accumulation.
137
- - Dialogue must fit each character's identity, relationship, and immediate situation.
138
- - Important emotion should appear through action, body language, pacing, and subtext where possible.
139
- - Scene description should provide useful sensory and atmospheric detail, but never stall the plot.
140
- - Conflict, turns, suspense, and the chapter-end hook should be clear.
161
+ - Natural, stable, readable language; prioritize narrative progress, character work, and emotional accumulation.
162
+ - Dialogue fits each character's identity, relationship, and situation.
163
+ - Important emotion comes through action, body language, pacing, and subtext.
164
+ - Scene description has useful sensory detail without stalling.
165
+ - POV: strictly follow the chapter architecture povCharacter (if set). No mid-chapter POV switch.
141
166
 
142
167
  ## Execution Rules
143
168
  - Write only what the current chapter architecture authorizes.
144
- - Do not introduce unauthorized major characters. Functional background characters should stay light.
145
- - Keep names, items, places, abilities, timeline, injuries, relationships, and knowledge boundaries consistent.
146
- - If the previous chapter ends mid-action, mid-dialogue, or in the same scene, this chapter must continue from that point.
169
+ - Do not introduce unauthorized major characters. Functional background characters stay light.
170
+ - Keep names, items, places, abilities, timelines, injuries, relationships, and knowledge boundaries consistent.
171
+ - If the previous chapter ends mid-action or mid-scene, this chapter must continue from that point.
172
+ - Active foreshadow threads may be advanced or paid off this chapter, but **never silently dropped** — even if you choose not to touch them, leave them coherent.
147
173
  - Avoid cost-free power jumps, forced stupidity, mechanical twists, info-dumps, and empty lyricism.
148
- - Do not output summaries, bullet points, lectures, or explanatory prefaces.
174
+ - Do not output summaries, bullet points, lectures, explanatory prefaces, or meta-text like "what I changed".
149
175
 
150
176
  ${input.context ? `## Generation Context\n${input.context}\n` : ''}## Output Requirements
151
177
  - Output Markdown.
@@ -185,13 +211,41 @@ Output valid JSON only, in this shape:
185
211
  "after": "After"
186
212
  }
187
213
  ],
188
- "openThreads": ["Unresolved promise, danger, question, or plot thread"]
214
+ "openThreads": ["Unresolved promise, danger, question, or plot thread"],
215
+ "wordCount": <approximate word count of this chapter as an integer>,
216
+ "threadActions": [
217
+ {
218
+ "kind": "plant | build | pay | drop",
219
+ "threadId": "id of an existing active thread (required for build/pay/drop; leave empty for plant — the system will assign one)",
220
+ "description": "for plant: what the new thread is; for others: one sentence on how this chapter advanced/paid/dropped that thread"
221
+ }
222
+ ],
223
+ "characterUpdates": [
224
+ {
225
+ "name": "Character name",
226
+ "role": "Role if confirmed or changed this chapter",
227
+ "goal": "Current goal at chapter end",
228
+ "belief": "Core belief or understanding driving them at chapter end",
229
+ "relationships": [
230
+ { "name": "Related character", "dynamic": "Relationship state at chapter end" }
231
+ ],
232
+ "abilities": ["Abilities, resources, or limits confirmed at chapter end"],
233
+ "secrets": ["Secrets still hidden or only partially known at chapter end"],
234
+ "emotionalState": "Emotional state at chapter end"
235
+ }
236
+ ]
189
237
  }
190
238
 
191
239
  Rules:
192
240
  - Record only information that happened or was confirmed in this chapter.
193
241
  - Do not speculate about future plot.
194
242
  - Make facts and stateChanges concrete enough for later chapter reference.
243
+ - wordCount: approximate word count (English) or character count (CJK). An integer estimate is fine.
244
+ - threadActions is critical:
245
+ · For any active foreshadow thread in the context's "Active Foreshadow Threads" section, if this chapter advanced it emit kind="build"; if this chapter paid it off emit kind="pay"; if this chapter abandoned it emit kind="drop". threadId is required.
246
+ · For any new thread this chapter plants, emit kind="plant" with a clear description.
247
+ · If an active thread was not touched, no action needed — but never silently delete it. Without a drop action, the thread stays active.
248
+ - characterUpdates maintains a separate character state table. Emit only important characters whose state changed or was reconfirmed in this chapter; goal, belief, relationships, abilities, secrets, and emotionalState must reflect the chapter ending.
195
249
  ${strictJsonOutputRules()}`,
196
250
  };
197
251
  }
@@ -241,6 +295,12 @@ function buildChapterReviewPrompt(input) {
241
295
  prompt: `You are a strict editor reviewing a single chapter of a serial novel for in-chapter problems and conflicts with established context.
242
296
 
243
297
  ${input.context ? `## Review Context\n${input.context}\n` : ''}## Review Focus
298
+ - This is a mandatory chapter acceptance gate. If any acceptance item fails, status must be "issues_found" and the workflow must revise before continuing.
299
+ - Whether every requiredBeat is fulfilled; missing beats must appear in acceptance.requiredBeats.missingBeats.
300
+ - Whether this chapter advances the main line, character state, or active foreshadow threads. If it is static, at least one of narrativeProgress/characterProgress/foreshadowProgress must fail.
301
+ - Whether it violates the story bible, character state table, volume pacing board, or prior memory.
302
+ - Whether the ending has a clear hook that matches the chapter architecture endHookFocus.
303
+ - Whether it repeats prior chapter beats, conflict patterns, reveals, or dialogue functions.
244
304
  - Character voice, motivation, and state vs the story bible and prior memory.
245
305
  - World rules, item ownership, and ability limits.
246
306
  - Timeline, location, and continuity with the previous chapter ending.
@@ -252,6 +312,37 @@ Output valid JSON only, in this shape:
252
312
  {
253
313
  "chapterNumber": ${chapter},
254
314
  "status": "clean",
315
+ "acceptance": {
316
+ "requiredBeats": {
317
+ "status": "pass | fail",
318
+ "evidence": "Evidence for each requiredBeat",
319
+ "missingBeats": []
320
+ },
321
+ "narrativeProgress": {
322
+ "status": "pass | fail",
323
+ "evidence": "How this chapter advances the main line or phase objective"
324
+ },
325
+ "characterProgress": {
326
+ "status": "pass | fail",
327
+ "evidence": "How this chapter changes or confirms key character goal, belief, relationship, ability, secret, or emotion"
328
+ },
329
+ "foreshadowProgress": {
330
+ "status": "pass | fail",
331
+ "evidence": "How this chapter plants, advances, pays, or deliberately preserves foreshadow threads"
332
+ },
333
+ "storyBibleConsistency": {
334
+ "status": "pass | fail",
335
+ "evidence": "Whether it matches the story bible, character state table, and world rules"
336
+ },
337
+ "endingHook": {
338
+ "status": "pass | fail",
339
+ "evidence": "The ending hook passage and its function"
340
+ },
341
+ "repetition": {
342
+ "status": "pass | fail",
343
+ "evidence": "Whether it repeats prior beats; if not, explain why"
344
+ }
345
+ },
255
346
  "issues": [
256
347
  {
257
348
  "severity": "low | medium | high",
@@ -266,6 +357,8 @@ Output valid JSON only, in this shape:
266
357
  Rules:
267
358
  - If there are no issues, use status "clean" with an empty issues array.
268
359
  - Otherwise use status "issues_found".
360
+ - status may be "clean" only when every acceptance item is "pass".
361
+ - If any acceptance item is "fail", include a matching issue with a concrete fix.
269
362
  - evidence must be specific; do not write "possibly" or "maybe".
270
363
  ${strictJsonOutputRules()}`,
271
364
  };
@@ -349,6 +442,17 @@ function buildPromptForStep(input) {
349
442
  return buildChapterRevisionPrompt(input);
350
443
  case 'cross_chapter_review':
351
444
  return buildCrossChapterReviewPrompt(input);
445
+ case 'story_bible_amend':
446
+ return {
447
+ purpose: 'story_bible',
448
+ expectedFormat: 'Markdown',
449
+ prompt: `Based on the current story bible and the amendment context, output the FULL revised story bible Markdown.
450
+
451
+ ${input.context ? `## Amendment Context\n${input.context}\n` : ''}## Output Requirements
452
+ - Output the entire story-bible.md content — it replaces the old one (old version auto-archived under story-bible-versions/).
453
+ - Preserve everything that still holds; modify / add / remove only what the amendment context justifies.
454
+ - Do not output diff markers, change logs, or bullet summaries — just the new full bible.`,
455
+ };
352
456
  case 'complete':
353
457
  return {
354
458
  purpose: 'continuity_review',