@cloud411716/fancy-webnovel 1.0.46 → 3.0.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 (271) hide show
  1. package/client.js +369 -0
  2. package/cordis.patch.yml +4 -13
  3. package/docs/douyin-plugin.md +118 -0
  4. package/docs/material-library/README.md +404 -0
  5. package/docs/material-library/import.js +437 -0
  6. package/docs/material-library/prompt.md +370 -0
  7. package/docs/material-library/queries.surql +94 -0
  8. package/docs/material-library/sample.jsonl +14 -0
  9. package/docs/material-library/schema.surql +46 -0
  10. package/docs/mcp-profile.example.yml +24 -0
  11. package/docs/story-graph-design.md +602 -0
  12. package/docs/story-graph-validation.md +81 -0
  13. package/docs/workspace-mcp.md +284 -0
  14. package/index.js +26 -38
  15. package/lib/atomic-write.js +109 -0
  16. package/lib/chapter-order.js +100 -0
  17. package/lib/chinese-num.js +111 -0
  18. package/lib/confirmation.js +80 -0
  19. package/lib/db-init.js +123 -0
  20. package/lib/deployed-state.js +141 -0
  21. package/lib/direction-labels.js +265 -0
  22. package/lib/error-codes.js +104 -0
  23. package/lib/infra.js +594 -0
  24. package/lib/llm-wiki.js +109 -0
  25. package/lib/material-db.js +149 -0
  26. package/lib/path-guard.js +150 -0
  27. package/lib/projects.js +400 -0
  28. package/lib/scraper-utils.js +305 -0
  29. package/lib/surreal-server.js +338 -0
  30. package/lib/topic-decision.js +860 -0
  31. package/lib/topic-fields.js +251 -0
  32. package/lib/topic-schema.js +225 -0
  33. package/lib/workspace.js +501 -0
  34. package/package.json +62 -5
  35. package/plugins/fancy-analyze/analyze-definitions.md +519 -0
  36. package/plugins/fancy-analyze/command-input.js +65 -0
  37. package/plugins/fancy-analyze/index.js +2024 -0
  38. package/plugins/fancy-analyze/ingest-coverage.js +107 -0
  39. package/plugins/fancy-analyze/schema-analyze.md +627 -0
  40. package/plugins/fancy-analyze/schema-write.md +178 -0
  41. package/plugins/fancy-analyze/scripts/append-summary-chapter.js +612 -0
  42. package/plugins/fancy-analyze/scripts/split_source.js +292 -0
  43. package/plugins/fancy-analyze/summary-progress.js +495 -0
  44. package/plugins/fancy-analyze/templates.js +1179 -0
  45. package/plugins/fancy-bootstrap/index.js +313 -0
  46. package/plugins/fancy-bootstrap/scripts/init.js +177 -0
  47. package/plugins/fancy-bootstrap/scripts/path-utils.js +21 -0
  48. package/plugins/fancy-bootstrap/templates.js +71 -0
  49. package/plugins/fancy-db/index.js +172 -0
  50. package/plugins/fancy-douyin/deploy.js +134 -0
  51. package/plugins/fancy-douyin/index.js +551 -0
  52. package/plugins/fancy-douyin/prompts/01-analysis-prompt.md +84 -0
  53. package/plugins/fancy-douyin/scripts/crawl-note.cjs +194 -0
  54. package/plugins/fancy-douyin/scripts/lib.cjs +197 -0
  55. package/plugins/fancy-douyin/scripts/scan-account.cjs +128 -0
  56. package/plugins/fancy-douyin/scripts/start-chrome.cjs +203 -0
  57. package/plugins/fancy-douyin/state.js +197 -0
  58. package/plugins/fancy-douyin/templates.js +127 -0
  59. package/plugins/fancy-export/exporter.js +805 -0
  60. package/plugins/fancy-export/index.js +63 -0
  61. package/plugins/fancy-import/import-core.js +1118 -0
  62. package/plugins/fancy-import/import-driver.js +604 -0
  63. package/plugins/fancy-import/index.js +738 -0
  64. package/plugins/fancy-import/prompts/01-import-prompt.md +131 -0
  65. package/plugins/fancy-import/templates.js +58 -0
  66. package/plugins/fancy-material/exporter.js +153 -0
  67. package/plugins/fancy-material/genres.js +256 -0
  68. package/plugins/fancy-material/index.js +835 -0
  69. package/plugins/fancy-material/inventory.js +143 -0
  70. package/plugins/fancy-material/kinds.js +313 -0
  71. package/plugins/fancy-material/queue.js +55 -0
  72. package/plugins/fancy-material/scripts/query.js +254 -0
  73. package/plugins/fancy-material/templates.js +258 -0
  74. package/plugins/fancy-material/tool-deploy.js +138 -0
  75. package/plugins/fancy-material/validate.js +149 -0
  76. package/plugins/fancy-project/index.js +133 -0
  77. package/plugins/fancy-scan/existing-block.js +100 -0
  78. package/plugins/fancy-scan/index.js +708 -0
  79. package/plugins/fancy-scan/prompts/01-analysis-prompt.md +302 -0
  80. package/plugins/fancy-scan/scripts/append-block.js +725 -0
  81. package/plugins/fancy-scan/scripts/report-validate.js +824 -0
  82. package/plugins/fancy-scan/scripts/run-scan.js +667 -0
  83. package/plugins/fancy-scan/scripts/scrapers/fanqie-rank-scraper.js +923 -0
  84. package/plugins/fancy-scan/scripts/scrapers/jjwxc-rank-scraper.js +469 -0
  85. package/plugins/fancy-scan/scripts/scrapers/qimao-rank-scraper.js +629 -0
  86. package/plugins/fancy-scan/templates/blocks.js +155 -0
  87. package/plugins/fancy-scan/templates/platforms.js +372 -0
  88. package/plugins/fancy-scan/templates/report-schema.js +90 -0
  89. package/plugins/fancy-scan/templates.js +694 -0
  90. package/plugins/fancy-scan/tool-deploy.js +335 -0
  91. package/plugins/fancy-scan/wait-turn.js +46 -0
  92. package/plugins/fancy-story-builder/db/README.md +106 -0
  93. package/plugins/fancy-story-builder/db/client.js +228 -0
  94. package/plugins/fancy-story-builder/db/commands.js +145 -0
  95. package/plugins/fancy-story-builder/db/ids.js +39 -0
  96. package/plugins/fancy-story-builder/db/import.js +798 -0
  97. package/plugins/fancy-story-builder/db/project.js +299 -0
  98. package/plugins/fancy-story-builder/db/query.js +361 -0
  99. package/plugins/fancy-story-builder/db/schema.js +417 -0
  100. package/plugins/fancy-story-builder/db/stage-sync.js +238 -0
  101. package/plugins/fancy-story-builder/deploy-manifest.js +239 -0
  102. package/plugins/fancy-story-builder/deslop-driver.js +821 -0
  103. package/plugins/fancy-story-builder/flesh-output.js +168 -0
  104. package/plugins/fancy-story-builder/index.js +6861 -0
  105. package/plugins/fancy-story-builder/patch-driver.js +390 -0
  106. package/plugins/fancy-story-builder/prompts/01-skeleton-prompt.md +563 -0
  107. package/plugins/fancy-story-builder/prompts/02-flesh-prompt.md +602 -0
  108. package/plugins/fancy-story-builder/prompts/03-rhythm-prompt.md +539 -0
  109. package/plugins/fancy-story-builder/prompts/04-writing-prompt.md +225 -0
  110. package/plugins/fancy-story-builder/prompts/05-deslop-prompt.md +96 -0
  111. package/plugins/fancy-story-builder/purpose-template.md +83 -0
  112. package/plugins/fancy-story-builder/references/formulas-rhythm.json +302 -0
  113. package/plugins/fancy-story-builder/references/formulas-skeleton.json +402 -0
  114. package/plugins/fancy-story-builder/references/genre-profiles.json +3514 -0
  115. package/plugins/fancy-story-builder/references/glossary.md +594 -0
  116. package/plugins/fancy-story-builder/references/index.md +581 -0
  117. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/00-index.md +174 -0
  118. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/01-scene.md +150 -0
  119. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/02-chapter-workflow.md +99 -0
  120. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/03-opening-chapter.md +104 -0
  121. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/04-dialogue-mastery.md +274 -0
  122. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/05-genre-formulas.md +432 -0
  123. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/06-tone-ensemble.md +259 -0
  124. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/07-ledger-audit.md +222 -0
  125. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/08-diagnosis-revision.md +205 -0
  126. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/09-reading-power.md +135 -0
  127. package/plugins/fancy-story-builder/references//345/206/231/344/275/234/346/214/207/345/257/274/10-deslop.md +129 -0
  128. package/plugins/fancy-story-builder/references//350/212/202/345/245/217/346/214/207/345/257/274/00-index.md +98 -0
  129. package/plugins/fancy-story-builder/references//350/212/202/345/245/217/346/214/207/345/257/274/01-upgrade-rhythm.md +300 -0
  130. package/plugins/fancy-story-builder/references//350/212/202/345/245/217/346/214/207/345/257/274/02-arc-rhythm.md +168 -0
  131. package/plugins/fancy-story-builder/references//350/212/202/345/245/217/346/214/207/345/257/274/03-highpoint-hooks.md +189 -0
  132. package/plugins/fancy-story-builder/references//350/212/202/345/245/217/346/214/207/345/257/274/04-satisfaction.md +226 -0
  133. package/plugins/fancy-story-builder/references//350/212/202/345/245/217/346/214/207/345/257/274/05-foreshadow-density.md +195 -0
  134. package/plugins/fancy-story-builder/references//350/212/202/345/245/217/346/214/207/345/257/274/06-chapter-outline.md +226 -0
  135. package/plugins/fancy-story-builder/references//350/212/202/345/245/217/346/214/207/345/257/274/07-audit.md +181 -0
  136. package/plugins/fancy-story-builder/references//350/241/200/350/202/211/346/214/207/345/257/274/00-index.md +100 -0
  137. package/plugins/fancy-story-builder/references//350/241/200/350/202/211/346/214/207/345/257/274/01-character.md +243 -0
  138. package/plugins/fancy-story-builder/references//350/241/200/350/202/211/346/214/207/345/257/274/02-worldbuilding.md +245 -0
  139. package/plugins/fancy-story-builder/references//350/241/200/350/202/211/346/214/207/345/257/274/03-relations.md +185 -0
  140. package/plugins/fancy-story-builder/references//350/241/200/350/202/211/346/214/207/345/257/274/04-emotion-methods.md +286 -0
  141. package/plugins/fancy-story-builder/references//350/241/200/350/202/211/346/214/207/345/257/274/05-audit.md +187 -0
  142. package/plugins/fancy-story-builder/references//351/252/250/346/236/266/346/214/207/345/257/274/00-index.md +91 -0
  143. package/plugins/fancy-story-builder/references//351/252/250/346/236/266/346/214/207/345/257/274/01-positioning.md +209 -0
  144. package/plugins/fancy-story-builder/references//351/252/250/346/236/266/346/214/207/345/257/274/02-packaging.md +135 -0
  145. package/plugins/fancy-story-builder/references//351/252/250/346/236/266/346/214/207/345/257/274/03-entities.md +305 -0
  146. package/plugins/fancy-story-builder/references//351/252/250/346/236/266/346/214/207/345/257/274/04-conflict.md +328 -0
  147. package/plugins/fancy-story-builder/references//351/252/250/346/236/266/346/214/207/345/257/274/05-quota.md +187 -0
  148. package/plugins/fancy-story-builder/references//351/252/250/346/236/266/346/214/207/345/257/274/06-audit.md +160 -0
  149. package/plugins/fancy-story-builder/rhythm-output.js +140 -0
  150. package/plugins/fancy-story-builder/schema-setting.json +1100 -0
  151. package/plugins/fancy-story-builder/schema-setting.md +232 -0
  152. package/plugins/fancy-story-builder/scripts/ai-patterns.js +619 -0
  153. package/plugins/fancy-story-builder/scripts/brief-validate.js +164 -0
  154. package/plugins/fancy-story-builder/scripts/check-guide-compliance.js +289 -0
  155. package/plugins/fancy-story-builder/scripts/content-quality.js +416 -0
  156. package/plugins/fancy-story-builder/scripts/deslop-validate.js +143 -0
  157. package/plugins/fancy-story-builder/scripts/error-classes.js +112 -0
  158. package/plugins/fancy-story-builder/scripts/flesh-validate.js +1312 -0
  159. package/plugins/fancy-story-builder/scripts/formula-engine.js +112 -0
  160. package/plugins/fancy-story-builder/scripts/graph-utils.js +1484 -0
  161. package/plugins/fancy-story-builder/scripts/label-coverage.js +171 -0
  162. package/plugins/fancy-story-builder/scripts/prompt-drift-check.js +441 -0
  163. package/plugins/fancy-story-builder/scripts/reading-power.js +298 -0
  164. package/plugins/fancy-story-builder/scripts/reference-log.js +110 -0
  165. package/plugins/fancy-story-builder/scripts/rhythm-validate.js +1312 -0
  166. package/plugins/fancy-story-builder/scripts/schema-pages.js +2668 -0
  167. package/plugins/fancy-story-builder/scripts/semantic-lint.js +381 -0
  168. package/plugins/fancy-story-builder/scripts/skeleton-quota.js +145 -0
  169. package/plugins/fancy-story-builder/scripts/skeleton-validate.js +1973 -0
  170. package/plugins/fancy-story-builder/scripts/stage-batches.js +1405 -0
  171. package/plugins/fancy-story-builder/scripts/stage-contract.js +429 -0
  172. package/plugins/fancy-story-builder/scripts/story-artifacts.js +933 -0
  173. package/plugins/fancy-story-builder/scripts/upstream-query.js +198 -0
  174. package/plugins/fancy-story-builder/scripts/v2/baseline.js +112 -0
  175. package/plugins/fancy-story-builder/scripts/v2/cast.js +517 -0
  176. package/plugins/fancy-story-builder/scripts/v2/context.js +434 -0
  177. package/plugins/fancy-story-builder/scripts/v2/contracts.js +493 -0
  178. package/plugins/fancy-story-builder/scripts/v2/core.js +419 -0
  179. package/plugins/fancy-story-builder/scripts/v2/engine.js +1068 -0
  180. package/plugins/fancy-story-builder/scripts/v2/export-markdown.js +794 -0
  181. package/plugins/fancy-story-builder/scripts/v2/genre.js +195 -0
  182. package/plugins/fancy-story-builder/scripts/v2/knowledge.js +321 -0
  183. package/plugins/fancy-story-builder/scripts/v2/macro.js +409 -0
  184. package/plugins/fancy-story-builder/scripts/v2/manifest.js +538 -0
  185. package/plugins/fancy-story-builder/scripts/v2/migrate.js +137 -0
  186. package/plugins/fancy-story-builder/scripts/v2/prompts.js +1335 -0
  187. package/plugins/fancy-story-builder/scripts/v2/rhythm.js +618 -0
  188. package/plugins/fancy-story-builder/scripts/v2/scale.js +843 -0
  189. package/plugins/fancy-story-builder/scripts/v2/snapshot.js +121 -0
  190. package/plugins/fancy-story-builder/scripts/v2/stages.js +273 -0
  191. package/plugins/fancy-story-builder/scripts/v2/writing.js +216 -0
  192. package/plugins/fancy-story-builder/scripts/writing-rules.js +167 -0
  193. package/plugins/fancy-story-builder/scripts/writing-validate.js +682 -0
  194. package/plugins/fancy-story-builder/skeleton-output.js +199 -0
  195. package/plugins/fancy-story-builder/stage-driver.js +1049 -0
  196. package/plugins/fancy-story-builder/storydb/README.md +271 -0
  197. package/plugins/fancy-story-builder/storydb/cli.js +458 -0
  198. package/plugins/fancy-story-builder/storydb/client.js +351 -0
  199. package/plugins/fancy-story-builder/storydb/compile.js +452 -0
  200. package/plugins/fancy-story-builder/storydb/context.js +288 -0
  201. package/plugins/fancy-story-builder/storydb/definitions.js +699 -0
  202. package/plugins/fancy-story-builder/storydb/driver.js +106 -0
  203. package/plugins/fancy-story-builder/storydb/dsh-tools.js +313 -0
  204. package/plugins/fancy-story-builder/storydb/export.js +175 -0
  205. package/plugins/fancy-story-builder/storydb/ids.js +31 -0
  206. package/plugins/fancy-story-builder/storydb/impact.js +170 -0
  207. package/plugins/fancy-story-builder/storydb/import.js +559 -0
  208. package/plugins/fancy-story-builder/storydb/mcp.js +99 -0
  209. package/plugins/fancy-story-builder/storydb/prompts.js +952 -0
  210. package/plugins/fancy-story-builder/storydb/stage-command.js +379 -0
  211. package/plugins/fancy-story-builder/storydb/stage.js +426 -0
  212. package/plugins/fancy-story-builder/storydb/store.js +891 -0
  213. package/plugins/fancy-story-builder/storydb/tools.js +592 -0
  214. package/plugins/fancy-story-builder/storydb/validation.js +183 -0
  215. package/plugins/fancy-story-builder/templates/v2/10-scale/scale-template.json +144 -0
  216. package/plugins/fancy-story-builder/templates/v2/20-macro/emotion-template.json +15 -0
  217. package/plugins/fancy-story-builder/templates/v2/20-macro/endings-template.json +16 -0
  218. package/plugins/fancy-story-builder/templates/v2/20-macro/lines-template.json +28 -0
  219. package/plugins/fancy-story-builder/templates/v2/20-macro/roles-template.json +10 -0
  220. package/plugins/fancy-story-builder/templates/v2/20-macro/story-template.json +19 -0
  221. package/plugins/fancy-story-builder/templates/v2/20-macro/volumes-template.json +24 -0
  222. package/plugins/fancy-story-builder/templates/v2/20-macro/world-template.json +24 -0
  223. package/plugins/fancy-story-builder/templates/v2/30-cast/characters-template.json +49 -0
  224. package/plugins/fancy-story-builder/templates/v2/30-cast/climaxes-template.json +14 -0
  225. package/plugins/fancy-story-builder/templates/v2/30-cast/conflicts-template.json +30 -0
  226. package/plugins/fancy-story-builder/templates/v2/30-cast/factions-template.json +18 -0
  227. package/plugins/fancy-story-builder/templates/v2/30-cast/foreshadows-template.json +29 -0
  228. package/plugins/fancy-story-builder/templates/v2/30-cast/information-template.json +29 -0
  229. package/plugins/fancy-story-builder/templates/v2/30-cast/items-template.json +13 -0
  230. package/plugins/fancy-story-builder/templates/v2/30-cast/locations-template.json +12 -0
  231. package/plugins/fancy-story-builder/templates/v2/30-cast/payoffs-template.json +16 -0
  232. package/plugins/fancy-story-builder/templates/v2/30-cast/relations-template.json +44 -0
  233. package/plugins/fancy-story-builder/templates/v2/40-rhythm/chapter-map-template.json +81 -0
  234. package/plugins/fancy-story-builder/templates/v2/40-rhythm/outline-template.json +162 -0
  235. package/plugins/fancy-story-builder/templates/v2/50-writing/ledger-template.json +46 -0
  236. package/plugins/fancy-story-builder/templates/v2/60-deslop/report-template.json +10 -0
  237. package/plugins/fancy-story-builder/templates//350/212/202/345/245/217//346/227/266/345/272/217/346/230/240/345/260/204/346/250/241/346/235/277.json +427 -0
  238. package/plugins/fancy-story-builder/templates//350/212/202/345/245/217//347/253/240/350/212/202/347/273/206/347/272/262/346/250/241/346/235/277.json +34 -0
  239. package/plugins/fancy-story-builder/templates//350/212/202/345/245/217//347/253/240/350/212/202/350/247/204/345/210/222/346/250/241/346/235/277.json +24 -0
  240. package/plugins/fancy-story-builder/templates//350/212/202/345/245/217//350/212/202/345/245/217/345/217/202/346/225/260/346/250/241/346/235/277.json +27 -0
  241. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//344/270/226/347/225/214/350/247/202/350/247/204/345/210/231/346/250/241/346/235/277.json +168 -0
  242. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//345/205/263/351/224/256/351/201/223/345/205/267/346/250/241/346/235/277.json +184 -0
  243. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//345/205/266/344/273/226/345/256/236/344/275/223/346/250/241/346/235/277.json +62 -0
  244. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//345/206/262/347/252/201/346/250/241/346/235/277.json +131 -0
  245. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//345/211/247/346/203/205/346/250/241/346/235/277.json +85 -0
  246. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//345/212/277/345/212/233/346/250/241/346/235/277.json +103 -0
  247. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//345/234/260/347/202/271/346/250/241/346/235/277.json +68 -0
  248. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//347/273/223/345/261/200/346/250/241/346/235/277.json +142 -0
  249. package/plugins/fancy-story-builder/templates//350/241/200/350/202/211//350/247/222/350/211/262/346/250/241/346/235/277.json +292 -0
  250. package/plugins/fancy-story-builder/templates//351/252/250/346/236/266//345/205/263/347/263/273/346/250/241/346/235/277.json +266 -0
  251. package/plugins/fancy-story-builder/templates//351/252/250/346/236/266//345/256/236/344/275/223/346/250/241/346/235/277.json +336 -0
  252. package/plugins/fancy-story-builder/templates//351/252/250/346/236/266//345/261/202/347/272/247/346/250/241/346/235/277.json +65 -0
  253. package/plugins/fancy-story-builder/templates//351/252/250/346/236/266//346/241/206/346/236/266/346/250/241/346/235/277.json +308 -0
  254. package/plugins/fancy-story-builder/templates.js +1446 -0
  255. package/plugins/fancy-story-builder/wiki-references.js +540 -0
  256. package/plugins/fancy-story-builder/writing-driver.js +1388 -0
  257. package/plugins/fancy-topic/index.js +1057 -0
  258. package/plugins/fancy-topic/prompts/01-exploration-prompt.md +115 -0
  259. package/plugins/fancy-topic/scripts/save-suggestion.js +219 -0
  260. package/plugins/fancy-topic/scripts/select-topic.js +317 -0
  261. package/plugins/fancy-topic/templates.js +476 -0
  262. package/plugins/fancy-topic/tool-deploy.js +200 -0
  263. package/commands/bootstrap/index.js +0 -164
  264. package/commands/bootstrap/init-project.js +0 -121
  265. package/commands/scan/index.js +0 -283
  266. package/commands/scan/platforms/fanqie.js +0 -146
  267. package/commands/scan/platforms/jinjiang.js +0 -143
  268. package/commands/scan/platforms/qidian.js +0 -102
  269. package/commands/scan/platforms/qimao.js +0 -127
  270. package/commands/scan/scraper.js +0 -195
  271. package/infra.js +0 -160
@@ -0,0 +1,121 @@
1
+ /**
2
+ * v2/snapshot.js —— 内容寻址快照与回滚。
3
+ *
4
+ * 只存哈希不能回滚;这里存真实内容对象:
5
+ * 设定/.snapshots/<id>/manifest.json 路径 → 对象哈希
6
+ * 设定/.objects/<sha256> 实际文件内容
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import crypto from 'node:crypto';
11
+ import {
12
+ V2_STAGES,
13
+ bytesHash,
14
+ ensureDir,
15
+ nowIso,
16
+ readJson,
17
+ stageDir,
18
+ writeJsonAtomic,
19
+ } from './core.js';
20
+
21
+ const SNAPSHOT_ROOT = ['设定', '.snapshots'];
22
+ const OBJECT_ROOT = ['设定', '.objects'];
23
+
24
+ function objectPath(projectRoot, hash) {
25
+ return path.join(projectRoot, ...OBJECT_ROOT, hash.replace(/^sha256:/, ''));
26
+ }
27
+
28
+ function digest(bytes) {
29
+ return 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
30
+ }
31
+
32
+ function stageJsonFiles(projectRoot) {
33
+ const out = [];
34
+ for (const stage of V2_STAGES) {
35
+ const dir = stageDir(projectRoot, stage.id);
36
+ if (!fs.existsSync(dir)) continue;
37
+ const walk = (current) => {
38
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
39
+ if (entry.name.startsWith('.') || entry.name === '_context') continue;
40
+ const full = path.join(current, entry.name);
41
+ if (entry.isDirectory()) {
42
+ if (['outlines', 'chapters', 'timelines'].includes(entry.name)) walk(full);
43
+ continue;
44
+ }
45
+ if (entry.name === 'bundle.json' || entry.name === 'README.md') continue;
46
+ if (entry.name.endsWith('.json') || entry.name.endsWith('.md')) out.push(full);
47
+ }
48
+ };
49
+ walk(dir);
50
+ }
51
+ const manifest = path.join(projectRoot, '设定', 'manifest.json');
52
+ if (fs.existsSync(manifest)) out.push(manifest);
53
+ return out.sort();
54
+ }
55
+
56
+ export function createSnapshot(projectRoot, label = '') {
57
+ const id = nowIso().replace(/[:.]/g, '-') + '-' + crypto.randomBytes(3).toString('hex');
58
+ const snapDir = path.join(projectRoot, ...SNAPSHOT_ROOT, id);
59
+ ensureDir(snapDir);
60
+ ensureDir(path.join(projectRoot, ...OBJECT_ROOT));
61
+ const files = {};
62
+ for (const file of stageJsonFiles(projectRoot)) {
63
+ const bytes = fs.readFileSync(file);
64
+ const hash = digest(bytes);
65
+ const obj = objectPath(projectRoot, hash);
66
+ if (!fs.existsSync(obj)) {
67
+ fs.writeFileSync(obj, bytes);
68
+ }
69
+ files[path.relative(projectRoot, file).split(path.sep).join('/')] = hash;
70
+ }
71
+ const manifest = {
72
+ id,
73
+ created_at: nowIso(),
74
+ label: String(label || ''),
75
+ files,
76
+ };
77
+ writeJsonAtomic(path.join(snapDir, 'manifest.json'), manifest);
78
+ return { ok: true, id, path: path.relative(projectRoot, snapDir).split(path.sep).join('/'), fileCount: Object.keys(files).length };
79
+ }
80
+
81
+ export function listSnapshots(projectRoot) {
82
+ const root = path.join(projectRoot, ...SNAPSHOT_ROOT);
83
+ if (!fs.existsSync(root)) return [];
84
+ const out = [];
85
+ for (const name of fs.readdirSync(root)) {
86
+ const manifest = readJson(path.join(root, name, 'manifest.json'), null);
87
+ if (manifest) out.push({ id: manifest.id || name, createdAt: manifest.created_at, label: manifest.label, fileCount: Object.keys(manifest.files || {}).length });
88
+ }
89
+ return out.sort((a, b) => String(b.id).localeCompare(String(a.id)));
90
+ }
91
+
92
+ export function rollbackSnapshot(projectRoot, snapshotId) {
93
+ const snap = readJson(path.join(projectRoot, ...SNAPSHOT_ROOT, snapshotId, 'manifest.json'), null);
94
+ if (!snap) return { ok: false, error: '快照不存在:' + snapshotId };
95
+ // 先给当前状态拍一张,保证回滚可撤销
96
+ const pre = createSnapshot(projectRoot, 'pre-rollback-' + snapshotId);
97
+ let restored = 0;
98
+ const errors = [];
99
+ for (const [rel, hash] of Object.entries(snap.files || {})) {
100
+ const obj = objectPath(projectRoot, hash);
101
+ if (!fs.existsSync(obj)) {
102
+ errors.push({ path: rel, message: '对象缺失:' + hash });
103
+ continue;
104
+ }
105
+ const target = path.join(projectRoot, ...rel.split('/'));
106
+ ensureDir(path.dirname(target));
107
+ fs.copyFileSync(obj, target);
108
+ restored += 1;
109
+ }
110
+ // 删除快照里没有的当前业务文件(避免回滚后残留新文件)
111
+ const current = new Set(stageJsonFiles(projectRoot).map((f) => path.relative(projectRoot, f).split(path.sep).join('/')));
112
+ for (const rel of current) {
113
+ if (Object.prototype.hasOwnProperty.call(snap.files || {}, rel)) continue;
114
+ try {
115
+ fs.unlinkSync(path.join(projectRoot, ...rel.split('/')));
116
+ } catch {
117
+ // ignore
118
+ }
119
+ }
120
+ return { ok: errors.length === 0, restored, errors, preSnapshot: pre.id, snapshot: snapshotId };
121
+ }
@@ -0,0 +1,273 @@
1
+ /**
2
+ * v2/stages.js —— 2.0 阶段编排(纯函数部分)
3
+ *
4
+ * 加载阶段文件、跑校验、补 _meta、写 bundle/README/status。
5
+ * LLM 调用在 index.js 的命令处理器里,不在这里。
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import {
10
+ CONTRACT_VERSION,
11
+ SCHEMA_VERSION,
12
+ V2_STAGE_BY_ID,
13
+ asArray,
14
+ contentHash,
15
+ fileExists,
16
+ nowIso,
17
+ readJson,
18
+ readStageStatus,
19
+ relProjectPath,
20
+ stageDir,
21
+ stageFile,
22
+ writeJsonAtomic,
23
+ writeStageStatus,
24
+ writeTextAtomic,
25
+ } from './core.js';
26
+ import { contractFor } from './contracts.js';
27
+ import { ensureContext, quantitySnapshot, validateBundle, writeBundle } from './context.js';
28
+ import { buildManifest } from './manifest.js';
29
+ import { renderScaleMd, validateScale } from './scale.js';
30
+ import { detectProfileKey, getProfile, loadGenreProfiles } from './genre.js';
31
+ import { validateMacro } from './macro.js';
32
+ import { validateCast } from './cast.js';
33
+ import { loadRhythm, validateRhythm } from './rhythm.js';
34
+ import { loadWriting, validateWriting } from './writing.js';
35
+
36
+ export function loadDocuments(projectRoot, stageId) {
37
+ const spec = V2_STAGE_BY_ID[stageId];
38
+ const dir = stageDir(projectRoot, stageId);
39
+ const out = {};
40
+ if (!spec) return out;
41
+ if (stageId === '20-macro') {
42
+ return {
43
+ world: readJson(path.join(dir, 'world.json'), null),
44
+ story: readJson(path.join(dir, 'story.json'), null),
45
+ volumes: readJson(path.join(dir, 'volumes.json'), null),
46
+ lines: readJson(path.join(dir, 'lines.json'), null),
47
+ endings: readJson(path.join(dir, 'endings.json'), null),
48
+ emotion: readJson(path.join(dir, 'emotion.json'), null),
49
+ roles: readJson(path.join(dir, 'roles.json'), null),
50
+ };
51
+ }
52
+ if (stageId === '30-cast') {
53
+ return {
54
+ characters: readJson(path.join(dir, 'characters.json'), null),
55
+ factions: readJson(path.join(dir, 'factions.json'), null),
56
+ locations: readJson(path.join(dir, 'locations.json'), null),
57
+ items: readJson(path.join(dir, 'items.json'), null),
58
+ conflicts: readJson(path.join(dir, 'conflicts.json'), null),
59
+ foreshadows: readJson(path.join(dir, 'foreshadows.json'), null),
60
+ climaxes: readJson(path.join(dir, 'climaxes.json'), null),
61
+ payoffs: readJson(path.join(dir, 'payoffs.json'), null),
62
+ relations: readJson(path.join(dir, 'relations.json'), null),
63
+ information: readJson(path.join(dir, 'information.json'), null),
64
+ };
65
+ }
66
+ for (const file of spec.requiredFiles) {
67
+ out[file.replace(/\.json$/, '')] = readJson(path.join(dir, file), null);
68
+ }
69
+ return out;
70
+ }
71
+
72
+ export function missingStageFiles(projectRoot, stageId) {
73
+ const spec = V2_STAGE_BY_ID[stageId];
74
+ if (!spec) return [];
75
+ return spec.requiredFiles.filter((f) => !fileExists(stageFile(projectRoot, stageId, f)));
76
+ }
77
+
78
+ export function stageGate(projectRoot, stageId) {
79
+ const spec = V2_STAGE_BY_ID[stageId];
80
+ const missing = [];
81
+ for (const up of (spec && spec.upstream) || []) {
82
+ const status = readStageStatus(projectRoot, up, { allowLegacy: false });
83
+ if (status.status !== 'passed') {
84
+ missing.push({ stage: up, status: status.status });
85
+ }
86
+ }
87
+ return { ok: missing.length === 0, missing };
88
+ }
89
+
90
+ export function validateStage(projectRoot, stageId, opts = {}) {
91
+ const scale = readJson(stageFile(projectRoot, '10-scale', 'scale.json'), null);
92
+ if (stageId === '00-baseline') {
93
+ const input = readJson(stageFile(projectRoot, '00-baseline', 'input.json'), null);
94
+ const formulas = readJson(stageFile(projectRoot, '00-baseline', 'formulas.json'), null);
95
+ const errors = [];
96
+ if (!input) errors.push({ code: 'BASELINE_INPUT_MISSING', path: '00-baseline/input.json', message: '缺少 input.json' });
97
+ if (!formulas) errors.push({ code: 'BASELINE_FORMULAS_MISSING', path: '00-baseline/formulas.json', message: '缺少 formulas.json' });
98
+ if (input) {
99
+ for (const key of ['book_name', 'target_chapters', 'target_words']) {
100
+ if (!input[key]) errors.push({ code: 'BASELINE_REQUIRED', path: 'input.' + key, message: '缺少必填字段' });
101
+ }
102
+ }
103
+ return { ok: errors.length === 0, errors, warnings: [], data: input };
104
+ }
105
+ if (stageId === '10-scale') {
106
+ const formulas = opts.formulasDoc || readJson(stageFile(projectRoot, '00-baseline', 'formulas.json'), null);
107
+ const profilesDoc = opts.profilesDoc || loadGenreProfiles(projectRoot);
108
+ const profileKey = (scale && scale.genre_profile) || detectProfileKey(readJson(stageFile(projectRoot, '00-baseline', 'input.json'), {}) || {}, profilesDoc);
109
+ const profile = opts.profile || getProfile(profilesDoc, profileKey);
110
+ return validateScale(scale, formulas, { ...opts, profilesDoc, profile, genreProfileKey: profileKey });
111
+ }
112
+ if (stageId === '20-macro') {
113
+ const macro = loadDocuments(projectRoot, stageId);
114
+ return validateMacro(macro, scale, opts);
115
+ }
116
+ if (stageId === '30-cast') {
117
+ const cast = loadDocuments(projectRoot, stageId);
118
+ const macro = loadDocuments(projectRoot, '20-macro');
119
+ return validateCast(cast, scale, macro, opts);
120
+ }
121
+ if (stageId === '40-rhythm') {
122
+ const macro = loadDocuments(projectRoot, '20-macro');
123
+ const cast = loadDocuments(projectRoot, '30-cast');
124
+ const rhythm = loadRhythm(projectRoot, stageDir(projectRoot, stageId), opts);
125
+ return validateRhythm(rhythm, scale, macro, cast, { ...opts, stageDir: stageDir(projectRoot, stageId) });
126
+ }
127
+ if (stageId === '50-writing') {
128
+ const writing = loadWriting(projectRoot);
129
+ return validateWriting(writing, { dir: writing.dir, ...opts });
130
+ }
131
+ return { ok: true, errors: [], warnings: [], data: null };
132
+ }
133
+
134
+ /**
135
+ * 给阶段所有业务 JSON 补 _meta(upstream / quantity_snapshot / content_hash)。
136
+ * 然后写 bundle/README,并刷新 manifest。
137
+ */
138
+ export function finalizeStage(projectRoot, stageId, opts = {}) {
139
+ const spec = V2_STAGE_BY_ID[stageId];
140
+ if (!spec) return { ok: false, error: '未知阶段:' + stageId };
141
+ if (stageId === '40-rhythm') {
142
+ const map = readJson(stageFile(projectRoot, '40-rhythm', 'chapter_map.json'), null);
143
+ if (map && Array.isArray(map.chapters)) {
144
+ writeJsonAtomic(stageFile(projectRoot, '40-rhythm', 'index.json'), {
145
+ _meta: { schema_version: SCHEMA_VERSION, node_id: '40-rhythm.index', stage: '40-rhythm' },
146
+ chapters: map.chapters.map((c) => ({
147
+ chapter_id: c.chapter_id,
148
+ display_no: c.display_no,
149
+ title: c.title,
150
+ volume: c.volume,
151
+ act: c.act,
152
+ path: 'outlines/' + c.chapter_id + '.json',
153
+ status: c.status || 'draft',
154
+ })),
155
+ });
156
+ }
157
+ }
158
+ const scale = readJson(stageFile(projectRoot, '10-scale', 'scale.json'), null);
159
+ const dir = stageDir(projectRoot, stageId);
160
+ const manifestBefore = buildManifest(projectRoot, { write: false });
161
+ const upstreamOf = (ids) => asArray(ids).map((nodeId) => {
162
+ const node = manifestBefore.nodes && manifestBefore.nodes[nodeId];
163
+ if (!node) return null;
164
+ return {
165
+ node_id: nodeId,
166
+ path: node.path,
167
+ hash: node.hash,
168
+ snapshot: node.kind === 'stage' ? '_context/' + nodeId.split('-').pop() + '.json' : undefined,
169
+ };
170
+ }).filter(Boolean);
171
+ const files = [];
172
+ if (stageId === '40-rhythm') {
173
+ files.push(path.join(dir, 'chapter_map.json'));
174
+ let names = [];
175
+ try {
176
+ names = fs.readdirSync(path.join(dir, 'outlines')).filter((n) => n.endsWith('.json'));
177
+ } catch {
178
+ names = [];
179
+ }
180
+ for (const name of names) files.push(path.join(dir, 'outlines', name));
181
+ if (fs.existsSync(path.join(dir, 'index.json'))) files.push(path.join(dir, 'index.json'));
182
+ } else {
183
+ for (const name of spec.requiredFiles) files.push(path.join(dir, name));
184
+ }
185
+ if (stageId === '50-writing') {
186
+ files.push(path.join(dir, 'ledger.json'));
187
+ }
188
+ for (const file of files) {
189
+ if (!fs.existsSync(file)) continue;
190
+ const data = readJson(file, null);
191
+ if (!data || typeof data !== 'object') continue;
192
+ const rel = path.relative(dir, file).split(path.sep).join('/');
193
+ const isOutline = rel.startsWith('outlines/');
194
+ const upstreamIds = isOutline
195
+ ? ['40-rhythm.chapter_map', '10-scale', '20-macro', '30-cast']
196
+ : (spec.upstream || []);
197
+ const upstream = upstreamOf(upstreamIds);
198
+ const nodeId = isOutline
199
+ ? '40-rhythm.outline.' + rel.replace(/^outlines\//, '').replace(/\.json$/, '')
200
+ : stageId + '.' + rel.replace(/\.(json|md)$/, '').replace(/\//g, '.');
201
+ data._meta = {
202
+ schema_version: SCHEMA_VERSION,
203
+ contract_version: CONTRACT_VERSION,
204
+ node_id: nodeId,
205
+ stage: stageId,
206
+ path: path.join(spec.dir, rel).split(path.sep).join('/'),
207
+ status: opts.status || 'draft',
208
+ locked: false,
209
+ content_hash: contentHash(data),
210
+ generated_at: nowIso(),
211
+ upstream,
212
+ quantity_snapshot: quantitySnapshot(stageId, scale),
213
+ self_contained: {
214
+ context_dir: '_context',
215
+ required_files: (contractFor(stageId) && contractFor(stageId).readOrder || []).filter((x) => x.startsWith('_context/')),
216
+ },
217
+ };
218
+ writeJsonAtomic(file, data);
219
+ }
220
+ writeBundle(projectRoot, stageId);
221
+ buildManifest(projectRoot, { write: true });
222
+ return { ok: true, files: files.map((f) => relProjectPath(projectRoot, f)) };
223
+ }
224
+
225
+ /**
226
+ * 完整阶段校验:业务校验 + 自包含 + bundle。写 .stage-status.json。
227
+ */
228
+ export function runStageValidation(projectRoot, stageId, opts = {}) {
229
+ const report = validateStage(projectRoot, stageId, opts);
230
+ const errors = [...asArray(report.errors)];
231
+ const warnings = [...asArray(report.warnings || [])];
232
+ if (opts.selfContained !== false) {
233
+ const context = ensureContext(projectRoot, stageId);
234
+ for (const e of asArray(context.errors)) errors.push(e);
235
+ writeBundle(projectRoot, stageId);
236
+ const bundle = validateBundle(projectRoot, stageId);
237
+ for (const e of asArray(bundle.errors)) errors.push(e);
238
+ }
239
+ const ok = errors.length === 0;
240
+ if (ok && stageId === '10-scale') {
241
+ writeTextAtomic(stageFile(projectRoot, '10-scale', 'scale.md'), renderScaleMd(report.data || readJson(stageFile(projectRoot, '10-scale', 'scale.json'), {})));
242
+ }
243
+ writeStageStatus(projectRoot, stageId, {
244
+ ok,
245
+ status: ok ? 'passed' : 'stale',
246
+ files: {},
247
+ errors,
248
+ warnings,
249
+ });
250
+ if (ok) {
251
+ finalizeStage(projectRoot, stageId, { status: 'passed' });
252
+ } else {
253
+ buildManifest(projectRoot, { write: true });
254
+ }
255
+ return { ok, errors, warnings, data: report.data };
256
+ }
257
+
258
+ export function describeStage(projectRoot, stageId) {
259
+ const status = readStageStatus(projectRoot, stageId);
260
+ return {
261
+ stage: stageId,
262
+ label: V2_STAGE_BY_ID[stageId] ? V2_STAGE_BY_ID[stageId].label : stageId,
263
+ status: status.status,
264
+ checkedAt: status.checkedAt,
265
+ errors: status.errors.length,
266
+ warnings: status.warnings.length,
267
+ missing: missingStageFiles(projectRoot, stageId),
268
+ };
269
+ }
270
+
271
+ export function stageOverview(projectRoot) {
272
+ return Object.keys(V2_STAGE_BY_ID).map((id) => describeStage(projectRoot, id));
273
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * v2/writing.js —— 50-writing:只按单章细纲写正文。
3
+ *
4
+ * 结构校验:
5
+ * - 每章文件存在、标题章号正确、有效字数达标
6
+ * - ledger 有对应条目
7
+ * - must_write 至少有可识别内容落入正文
8
+ * - must_not_write 的明确禁令没有被直接违反
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { asArray, readJson, readText, stageDir, v2Error } from './core.js';
13
+ import { countEffectiveChars } from '../content-quality.js';
14
+ import { loadRhythm } from './rhythm.js';
15
+ import { knowledgeKey, replayKnowledge, validateKnowledgeSnapshot } from './knowledge.js';
16
+
17
+ export function chapterFileName(displayNo) {
18
+ return '第' + String(displayNo).padStart(3, '0') + '章.md';
19
+ }
20
+
21
+ export function loadWriting(projectRoot) {
22
+ const dir = stageDir(projectRoot, '50-writing');
23
+ const ledger = readJson(path.join(dir, 'ledger.json'), { chapters: [] });
24
+ const rhythmDir = stageDir(projectRoot, '40-rhythm');
25
+ const rhythm = loadRhythm(projectRoot, rhythmDir);
26
+ const castDir = stageDir(projectRoot, '30-cast');
27
+ const cast = {
28
+ characters: readJson(path.join(castDir, 'characters.json'), null),
29
+ information: readJson(path.join(castDir, 'information.json'), null),
30
+ foreshadows: readJson(path.join(castDir, 'foreshadows.json'), null),
31
+ };
32
+ return { dir, ledger, rhythm, cast };
33
+ }
34
+
35
+ function keywordsOf(phrase) {
36
+ const text = String(phrase || '');
37
+ const out = new Set();
38
+ for (const part of text.split(/[,。;、::;,.\s()()“”"']+/)) {
39
+ if (part.length >= 2) out.add(part);
40
+ if (part.length > 6) {
41
+ out.add(part.slice(0, 4));
42
+ out.add(part.slice(-4));
43
+ }
44
+ }
45
+ return [...out];
46
+ }
47
+
48
+ function hasAnyKeyword(text, phrase) {
49
+ const kws = keywordsOf(phrase);
50
+ if (!kws.length) return true;
51
+ return kws.some((k) => text.includes(k));
52
+ }
53
+
54
+ export function validateWriting(writing, opts = {}) {
55
+ const errors = [];
56
+ const warnings = [];
57
+ const { ledger, rhythm, cast } = writing || {};
58
+ const knowledge = cast ? replayKnowledge(rhythm && rhythm.chapter_map && rhythm.chapter_map.chapters, cast) : null;
59
+ const chapters = asArray(rhythm && rhythm.chapter_map && rhythm.chapter_map.chapters);
60
+ const outlines = (rhythm && rhythm.outlines) || new Map();
61
+ const ledgerRows = asArray(ledger && ledger.chapters);
62
+ const ledgerByCh = new Map();
63
+ const ledgerById = new Map();
64
+ for (const row of ledgerRows) {
65
+ if (!row) continue;
66
+ if (row.ch !== undefined) ledgerByCh.set(Number(row.ch), row);
67
+ if (row.chapter_id) ledgerById.set(row.chapter_id, row);
68
+ }
69
+
70
+ const writingDir = opts.dir;
71
+ const chapterFilter = opts.chapterIds instanceof Set ? opts.chapterIds : null;
72
+ let written = 0;
73
+ for (const c of chapters) {
74
+ if (!c || c.status === 'archived') continue;
75
+ const displayNo = Number(c.display_no);
76
+ const id = c.chapter_id;
77
+ if (chapterFilter && !chapterFilter.has(displayNo)) continue;
78
+ const file = path.join(writingDir, 'chapters', chapterFileName(displayNo));
79
+ const text = readText(file, null);
80
+ if (text === null) {
81
+ errors.push(v2Error('WRITING_CHAPTER_MISSING', {
82
+ path: 'chapters/' + chapterFileName(displayNo),
83
+ message: '第 ' + displayNo + ' 章正文缺失',
84
+ contract: '50-writing/README.md#writing',
85
+ reference: '40-rhythm/chapter_map.json',
86
+ }));
87
+ continue;
88
+ }
89
+ written += 1;
90
+ const first = String(text).split('\n', 1)[0].trim();
91
+ const m = /^#\s*第\s*(\d+)\s*章(?:\s|$)/.exec(first);
92
+ if (!m) {
93
+ errors.push(v2Error('WRITING_TITLE', {
94
+ path: 'chapters/' + chapterFileName(displayNo),
95
+ message: '正文第一行必须是 `# 第N章 标题`',
96
+ actual: first.slice(0, 40),
97
+ contract: '50-writing/README.md#writing',
98
+ }));
99
+ } else if (Number(m[1]) !== displayNo) {
100
+ errors.push(v2Error('WRITING_TITLE', {
101
+ path: 'chapters/' + chapterFileName(displayNo),
102
+ message: '标题章号与 display_no 不一致',
103
+ expected: displayNo, actual: Number(m[1]),
104
+ contract: '50-writing/README.md#writing',
105
+ }));
106
+ }
107
+ const chars = countEffectiveChars(text);
108
+ if (chars < 500) {
109
+ errors.push(v2Error('WRITING_EMPTY_BODY', {
110
+ path: 'chapters/' + chapterFileName(displayNo),
111
+ message: '正文太短',
112
+ actual: chars,
113
+ hint: '至少写 500 个有效字符;如果细纲信息不足,先修细纲',
114
+ contract: '50-writing/README.md#writing',
115
+ }));
116
+ }
117
+ const target = Number(c.word_target || 0);
118
+ if (target > 0 && (chars < target * 0.6 || chars > target * 1.6)) {
119
+ warnings.push(v2Error('WRITING_WORD_COUNT', {
120
+ path: 'chapters/' + chapterFileName(displayNo),
121
+ severity: 'warning',
122
+ message: '正文字数与细纲 word_target 偏差较大',
123
+ expected: '约 ' + target, actual: chars,
124
+ contract: '50-writing/README.md#writing',
125
+ }));
126
+ }
127
+ const ledgerRow = ledgerById.get(id) || ledgerByCh.get(displayNo);
128
+ if (!ledgerRow) {
129
+ errors.push(v2Error('WRITING_LEDGER_ENTRY_MISSING', {
130
+ path: 'ledger.json#chapters',
131
+ message: '第 ' + displayNo + ' 章没有 ledger 条目',
132
+ contract: '50-writing/README.md#ledger',
133
+ }));
134
+ } else {
135
+ for (const key of ['ch', 'chapter_id', 'title', 'pov', 'word_count']) {
136
+ if (ledgerRow[key] === undefined || ledgerRow[key] === null || ledgerRow[key] === '') {
137
+ errors.push(v2Error('WRITING_LEDGER_FIELD', {
138
+ path: 'ledger.json#chapters[' + displayNo + '].' + key,
139
+ message: 'ledger 条目缺少字段:' + key,
140
+ contract: '50-writing/README.md#ledger',
141
+ }));
142
+ }
143
+ }
144
+ if (knowledge) {
145
+ const expected = knowledge.snapshots.get(displayNo) || new Map();
146
+ const changes = asArray(ledgerRow.knowledge_changes);
147
+ for (let j = 0; j < changes.length; j += 1) {
148
+ const change = changes[j];
149
+ if (!change || typeof change !== 'object' || !change.subject_type || !change.subject_id || !change.character) continue;
150
+ const key = knowledgeKey(change.subject_type, change.subject_id, change.character);
151
+ const exp = expected.get(key);
152
+ const to = change.to || change.state || change.coverage;
153
+ if (!exp) {
154
+ warnings.push(v2Error('WRITING_KNOWLEDGE_UNKNOWN', {
155
+ path: 'ledger.json#chapters[' + displayNo + '].knowledge_changes[' + j + ']',
156
+ severity: 'warning',
157
+ message: '章节地图没有登记这条知识:' + key,
158
+ contract: '50-writing/README.md#knowledge',
159
+ }));
160
+ } else if (to && to !== exp.state) {
161
+ errors.push(v2Error('WRITING_KNOWLEDGE_CONFLICT', {
162
+ path: 'ledger.json#chapters[' + displayNo + '].knowledge_changes[' + j + '].to',
163
+ message: '第 ' + displayNo + ' 章 ledger 的知识状态与章节地图冲突',
164
+ expected: exp.state, actual: to,
165
+ contract: '50-writing/README.md#knowledge',
166
+ }));
167
+ }
168
+ }
169
+ const snapshots = asArray(ledgerRow.knowledge_state).filter((x) => x && typeof x === 'object');
170
+ const snap = validateKnowledgeSnapshot(snapshots, expected, { chapterNo: displayNo, path: 'ledger.json#chapters[' + displayNo + '].knowledge_state' });
171
+ for (const e of snap.errors) errors.push(v2Error(e.code, { ...e, contract: '50-writing/README.md#knowledge' }));
172
+ for (const w of snap.warnings) warnings.push(v2Error(w.code, { ...w, severity: 'warning', contract: '50-writing/README.md#knowledge' }));
173
+ }
174
+ }
175
+ const outline = outlines.get(id);
176
+ const chapter = outline && outline.chapter || {};
177
+ const hard = chapter.hard_constraints || (outline && outline.hard_constraints) || {};
178
+ const must = asArray(hard.must_write || chapter.must_write);
179
+ for (const phrase of must) {
180
+ if (!hasAnyKeyword(text, phrase)) {
181
+ errors.push(v2Error('WRITING_MUST_WRITE', {
182
+ path: 'chapters/' + chapterFileName(displayNo),
183
+ message: '正文没有覆盖细纲必须写的内容:' + phrase,
184
+ contract: '50-writing/README.md#writing',
185
+ reference: '40-rhythm/outlines/' + id + '.json#chapter.hard_constraints.must_write',
186
+ }));
187
+ }
188
+ }
189
+ const mustNot = asArray(hard.must_not_write || chapter.must_not_write);
190
+ for (const phrase of mustNot) {
191
+ const textPhrase = String(phrase || '').trim();
192
+ if (textPhrase.length >= 4 && text.includes(textPhrase)) {
193
+ errors.push(v2Error('WRITING_MUST_NOT_WRITE', {
194
+ path: 'chapters/' + chapterFileName(displayNo),
195
+ message: '正文出现细纲明确禁止的内容:' + textPhrase,
196
+ contract: '50-writing/README.md#writing',
197
+ reference: '40-rhythm/outlines/' + id + '.json#chapter.hard_constraints.must_not_write',
198
+ }));
199
+ }
200
+ }
201
+ }
202
+
203
+ if (written === 0) {
204
+ errors.push(v2Error('WRITING_EMPTY', {
205
+ path: 'chapters',
206
+ message: '当前没有任何正文文件。',
207
+ contract: '50-writing/README.md#writing',
208
+ }));
209
+ }
210
+
211
+ return { ok: errors.length === 0, errors, warnings, data: writing };
212
+ }
213
+
214
+ export function renderLedgerRow(projectRoot, chapter, text, ledgerRow) {
215
+ return ledgerRow;
216
+ }