Originally created by: Evan-Pycraft
Bug Description
When manifest.json or current_state.json has lastAppliedChapter / chapter greater than actual chapter files (e.g., state poisoning, interrupted rewrite), inkos write rewrite <book> <chapter> calculates the wrong chapter number.
Example: Running inkos write rewrite book 50 writes chapter 74 instead.
Root Cause
In getNextChapterNumber():
return Math.max(indexedChapter, durableChapter, runtimeState.manifest.lastAppliedChapter) + 1;
durableChapter (from chapter files) = 49 ✅
runtimeState.manifest.lastAppliedChapter (from corrupted JSON) = 73 ❌
Math.max(49, 73) = 73 → returns 74
Fix
Modified getNextChapterNumber to only trust durableChapter (determined from actual artifacts like chapter files, index.json, markdown state):
return Math.max(indexedChapter, durableChapter) + 1;
Also added consistency check in loadOrBootstrapCurrentState: when JSON chapter exceeds durable story progress, rebuild from markdown.
Test
# Before fix
$ inkos write rewrite 茅山禁术-诡案寻踪 50
Regenerating chapter 74... ❌
# After fix
$ inkos write rewrite 茅山禁术-诡案寻踪 50
Regenerating chapter 50... ✅
Affected Scenario
This bug is triggered when:
- A rewrite operation is interrupted mid-write
- State files become desynchronized from actual chapter artifacts
manifest.lastAppliedChapter leads the actual story progress