@oh-story/dsh 0.1.4 → 0.1.5

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 (479) hide show
  1. package/README.md +56 -12
  2. package/lib/client.js +2692 -268
  3. package/lib/client.js.map +4 -4
  4. package/lib/drama/manifest.json +136 -101
  5. package/lib/drama/skills/short-drama/SKILL.md +61 -1
  6. package/lib/drama/skills/short-drama/references/contract-and-ownership.md +7 -4
  7. package/lib/drama/skills/short-drama/references/creator-documents.md +133 -8
  8. package/lib/drama/skills/short-drama/references/creator-workflow.md +38 -2
  9. package/lib/drama/skills/short-drama/references/knowhow-index.md +3 -0
  10. package/lib/drama/skills/short-drama/references/reference-roles.md +10 -7
  11. package/lib/drama/skills/short-drama/references/runtime-preflight.md +3 -0
  12. package/lib/drama/skills/short-drama/scripts/creator_markdown_check.py +1002 -0
  13. package/lib/drama/skills/short-drama/scripts/project_tool.py +485 -5
  14. package/lib/drama/skills/short-drama-assets/SKILL.md +13 -3
  15. package/lib/drama/skills/short-drama-assets/references/continuity-lock.md +116 -0
  16. package/lib/drama/skills/short-drama-assets/references/identity-vs-variant.md +2 -1
  17. package/lib/drama/skills/short-drama-assets/references/prop-and-state.md +19 -0
  18. package/lib/drama/skills/short-drama-assets/references/stage-contract.md +2 -0
  19. package/lib/drama/skills/short-drama-assets/scripts/asset_check.py +1 -1
  20. package/lib/drama/skills/short-drama-image-prompts/SKILL.md +6 -2
  21. package/lib/drama/skills/short-drama-image-prompts/references/common-recipe.md +4 -3
  22. package/lib/drama/skills/short-drama-image-prompts/references/lookdev-frame.md +1 -1
  23. package/lib/drama/skills/short-drama-image-prompts/references/review-and-fixtures.md +1 -1
  24. package/lib/drama/skills/short-drama-image-prompts/references/stage-contract.md +3 -1
  25. package/lib/drama/skills/short-drama-image-prompts/scripts/image_prompt_check.py +8 -8
  26. package/lib/drama/skills/short-drama-image-prompts/scripts/selftest.py +4 -2
  27. package/lib/drama/skills/short-drama-produce/SKILL.md +46 -10
  28. package/lib/drama/skills/short-drama-produce/references/adapter-contract.md +65 -8
  29. package/lib/drama/skills/short-drama-produce/references/providers/minimax-h3-video.md +85 -0
  30. package/lib/drama/skills/short-drama-produce/references/providers/seedance.md +27 -10
  31. package/lib/drama/skills/short-drama-produce/scripts/production_tool.py +362 -3
  32. package/lib/drama/skills/short-drama-produce/scripts/provider_adapters.py +627 -40
  33. package/lib/drama/skills/short-drama-produce/scripts/selftest.py +5 -4
  34. package/lib/drama/skills/short-drama-review/references/rubric-visual-motion.md +12 -0
  35. package/lib/drama/skills/short-drama-review/scripts/review_check.py +1 -1
  36. package/lib/drama/skills/short-drama-storyboard/SKILL.md +76 -7
  37. package/lib/drama/skills/short-drama-storyboard/assets/shot-template.jsonl +1 -1
  38. package/lib/drama/skills/short-drama-storyboard/references/keyframe-craft.md +6 -2
  39. package/lib/drama/skills/short-drama-storyboard/references/production-shot-grammar.md +19 -4
  40. package/lib/drama/skills/short-drama-storyboard/references/review-and-fixtures.md +5 -2
  41. package/lib/drama/skills/short-drama-storyboard/references/screenplay-to-keyframe-example.md +16 -0
  42. package/lib/drama/skills/short-drama-storyboard/references/stage-contract.md +8 -3
  43. package/lib/drama/skills/short-drama-storyboard/scripts/storyboard_check.py +1 -1
  44. package/lib/drama/skills/short-drama-video-prompts/SKILL.md +81 -13
  45. package/lib/drama/skills/short-drama-video-prompts/assets/motion-spec.jsonl.md +6 -1
  46. package/lib/drama/skills/short-drama-video-prompts/assets/video-prompts.md +17 -1
  47. package/lib/drama/skills/short-drama-video-prompts/references/delivery-profile.md +21 -1
  48. package/lib/drama/skills/short-drama-video-prompts/references/minimax-h3.md +154 -0
  49. package/lib/drama/skills/short-drama-video-prompts/references/motion-recipe.md +24 -6
  50. package/lib/drama/skills/short-drama-video-prompts/references/production-prompt-grammar.md +11 -7
  51. package/lib/drama/skills/short-drama-video-prompts/references/seedance-2.0.md +41 -0
  52. package/lib/drama/skills/short-drama-video-prompts/references/seedance-2.5.md +66 -0
  53. package/lib/drama/skills/short-drama-video-prompts/references/stage-contract.md +5 -2
  54. package/lib/drama/skills/short-drama-video-prompts/references/target-model-profile.md +115 -0
  55. package/lib/drama/skills/short-drama-video-prompts/scripts/container_check.py +1 -1
  56. package/lib/drama/skills/short-drama-video-prompts/scripts/music_spec_check.py +1 -1
  57. package/lib/drama/skills/short-drama-write/SKILL.md +3 -2
  58. package/lib/drama/skills/short-drama-write/scripts/duration_estimate.py +1 -1
  59. package/lib/drama/skills/short-drama-write/scripts/screenplay_index.py +2 -2
  60. package/lib/drama/skills/short-drama-write/scripts/voice_sheet_check.py +1 -1
  61. package/lib/index.js +865 -33
  62. package/lib/index.js.map +4 -4
  63. package/lib/novel-to-game/LICENSE +21 -0
  64. package/lib/novel-to-game/README.md +180 -0
  65. package/lib/novel-to-game/README_ZH.md +178 -0
  66. package/lib/novel-to-game/VERSION +1 -0
  67. package/lib/novel-to-game/examples/jin-ping-mei/build/BUILD_BRIEF.md +217 -0
  68. package/lib/novel-to-game/examples/jin-ping-mei/build/app/.vercelignore +3 -0
  69. package/lib/novel-to-game/examples/jin-ping-mei/build/app/RUN.md +130 -0
  70. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/bg/compound_new_guofeng.webp +0 -0
  71. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/finale/fate_coda.webp +0 -0
  72. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/finale/meng.webp +0 -0
  73. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/finale/pan.webp +0 -0
  74. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/finale/pinger.webp +0 -0
  75. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/finale/xuee.webp +0 -0
  76. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/finale/yue.webp +0 -0
  77. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/group/inner_court_accord_five.webp +0 -0
  78. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/group/inner_court_afterglow_five.webp +0 -0
  79. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/group/inner_court_alliance.webp +0 -0
  80. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/group/public_day10.webp +0 -0
  81. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/group/public_day15.webp +0 -0
  82. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/group/public_day5.webp +0 -0
  83. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/group/title_new_guofeng.webp +0 -0
  84. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/joint/pan_pinger.webp +0 -0
  85. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/joint/pan_xuee.webp +0 -0
  86. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/joint/yue_meng.webp +0 -0
  87. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/joint/yue_pan.webp +0 -0
  88. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/joint/yue_pinger.webp +0 -0
  89. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/meng/explicit.webp +0 -0
  90. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/meng/prelude.webp +0 -0
  91. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/milestone/meng.webp +0 -0
  92. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/milestone/pan.webp +0 -0
  93. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/milestone/pinger.webp +0 -0
  94. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/milestone/xuee.webp +0 -0
  95. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/milestone/yue.webp +0 -0
  96. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/pan/explicit.webp +0 -0
  97. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/pan/prelude.webp +0 -0
  98. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/pinger/explicit.webp +0 -0
  99. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/pinger/prelude.webp +0 -0
  100. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/xuee/explicit.webp +0 -0
  101. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/xuee/prelude.webp +0 -0
  102. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/yue/explicit.webp +0 -0
  103. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/cg/yue/prelude.webp +0 -0
  104. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/heroine/meng/night.webp +0 -0
  105. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/heroine/pan/night.webp +0 -0
  106. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/heroine/pinger/night.webp +0 -0
  107. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/heroine/xuee/night.webp +0 -0
  108. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/heroine/yue/night.webp +0 -0
  109. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/household/li_jiaoer.webp +0 -0
  110. package/lib/novel-to-game/examples/jin-ping-mei/build/app/assets/scene/gate_collector.webp +0 -0
  111. package/lib/novel-to-game/examples/jin-ping-mei/build/app/css/new-guofeng.css +1105 -0
  112. package/lib/novel-to-game/examples/jin-ping-mei/build/app/css/style.css +2539 -0
  113. package/lib/novel-to-game/examples/jin-ping-mei/build/app/index.html +18 -0
  114. package/lib/novel-to-game/examples/jin-ping-mei/build/app/js/assets.js +147 -0
  115. package/lib/novel-to-game/examples/jin-ping-mei/build/app/js/audio.js +332 -0
  116. package/lib/novel-to-game/examples/jin-ping-mei/build/app/js/data.js +7472 -0
  117. package/lib/novel-to-game/examples/jin-ping-mei/build/app/js/engine.js +13077 -0
  118. package/lib/novel-to-game/examples/jin-ping-mei/build/app/js/main.js +3028 -0
  119. package/lib/novel-to-game/examples/jin-ping-mei/build/app/js/text.js +32 -0
  120. package/lib/novel-to-game/examples/jin-ping-mei/build/app/package.json +10 -0
  121. package/lib/novel-to-game/examples/jin-ping-mei/build/app/vercel.json +23 -0
  122. package/lib/novel-to-game/examples/jin-ping-mei/build/art/generated-art.json +161 -0
  123. package/lib/novel-to-game/examples/jin-ping-mei/example.json +12 -0
  124. package/lib/novel-to-game/examples/jin-ping-mei/qa/README.md +31 -0
  125. package/lib/novel-to-game/examples/jin-ping-mei/qa/playable-model.json +99 -0
  126. package/lib/novel-to-game/examples/jin-ping-mei/qa/verification.json +41 -0
  127. package/lib/novel-to-game/examples/jin-ping-mei/qa/verify_playable_model.mjs +129 -0
  128. package/lib/novel-to-game/manifest.json +508 -0
  129. package/lib/novel-to-game/skills/game-art-direction/SKILL.md +73 -0
  130. package/lib/novel-to-game/skills/game-art-direction/agents/openai.yaml +4 -0
  131. package/lib/novel-to-game/skills/game-art-direction/references/art-direction-method.md +119 -0
  132. package/lib/novel-to-game/skills/game-build/SKILL.md +84 -0
  133. package/lib/novel-to-game/skills/game-build/agents/openai.yaml +4 -0
  134. package/lib/novel-to-game/skills/game-build/references/build-brief-contract.md +109 -0
  135. package/lib/novel-to-game/skills/game-build/references/generative-media-pipeline.md +56 -0
  136. package/lib/novel-to-game/skills/game-build/references/playable-model-contract.md +81 -0
  137. package/lib/novel-to-game/skills/game-build/references/tts-production-contract.md +37 -0
  138. package/lib/novel-to-game/skills/game-concept/SKILL.md +72 -0
  139. package/lib/novel-to-game/skills/game-concept/agents/openai.yaml +4 -0
  140. package/lib/novel-to-game/skills/game-concept/references/concept-method.md +94 -0
  141. package/lib/novel-to-game/skills/game-qa/SKILL.md +50 -0
  142. package/lib/novel-to-game/skills/game-qa/agents/openai.yaml +4 -0
  143. package/lib/novel-to-game/skills/game-qa/references/qa-contract.md +66 -0
  144. package/lib/novel-to-game/skills/game-qa/references/test-design-method.md +45 -0
  145. package/lib/novel-to-game/skills/game-world-design/SKILL.md +63 -0
  146. package/lib/novel-to-game/skills/game-world-design/agents/openai.yaml +4 -0
  147. package/lib/novel-to-game/skills/game-world-design/references/dialogue-design-method.md +59 -0
  148. package/lib/novel-to-game/skills/game-world-design/references/game-writing-craft.md +53 -0
  149. package/lib/novel-to-game/skills/game-world-design/references/narrative-design-method.md +84 -0
  150. package/lib/novel-to-game/skills/game-world-design/references/numeric-design-method.md +56 -0
  151. package/lib/novel-to-game/skills/game-world-design/references/world-design-method.md +124 -0
  152. package/lib/novel-to-game/skills/novel-game-analyze/SKILL.md +77 -0
  153. package/lib/novel-to-game/skills/novel-game-analyze/agents/openai.yaml +4 -0
  154. package/lib/novel-to-game/skills/novel-game-analyze/references/gameability-protocol.md +65 -0
  155. package/lib/novel-to-game/skills/novel-to-game/SKILL.md +71 -0
  156. package/lib/novel-to-game/skills/novel-to-game/agents/openai.yaml +4 -0
  157. package/lib/novel-to-game/skills/novel-to-game/references/intake-benchmark-reference.md +42 -0
  158. package/lib/novel-to-game/skills/novel-to-game/references/intake-method.md +51 -0
  159. package/lib/novel-to-game/skills/novel-to-game/references/pipeline-contract.md +65 -0
  160. package/lib/oh-story/manifest.json +415 -305
  161. package/lib/oh-story/roles/consistency-checker.md +1 -1
  162. package/lib/oh-story/roles/narrative-writer.md +32 -33
  163. package/lib/oh-story/roles/story-architect.md +16 -26
  164. package/lib/oh-story/skills/browser-cdp/SKILL.md +1 -1
  165. package/lib/oh-story/skills/story/SKILL.md +16 -9
  166. package/lib/oh-story/skills/story/VERSION +1 -1
  167. package/lib/oh-story/skills/story/references/author-memory.md +163 -0
  168. package/lib/oh-story/skills/story/scripts/author_memory_commit.py +871 -0
  169. package/lib/oh-story/skills/story-cover/SKILL.md +1 -1
  170. package/lib/oh-story/skills/story-deslop/SKILL.md +10 -5
  171. package/lib/oh-story/skills/story-deslop/references/anti-ai-writing.md +2 -1
  172. package/lib/oh-story/skills/story-deslop/references/author-memory.md +163 -0
  173. package/lib/oh-story/skills/story-deslop/references/banned-words.md +6 -4
  174. package/lib/oh-story/skills/story-deslop/scripts/author_memory_commit.py +871 -0
  175. package/lib/oh-story/skills/story-deslop/scripts/check-ai-patterns.js +64 -1
  176. package/lib/oh-story/skills/story-import/SKILL.md +19 -10
  177. package/lib/oh-story/skills/story-import/references/format-and-structure.md +9 -10
  178. package/lib/oh-story/skills/story-import/references/structure-mapping-long.md +2 -2
  179. package/lib/oh-story/skills/story-import/references/structure-mapping-short.md +1 -1
  180. package/lib/oh-story/skills/story-import/references/tracking-transaction.md +14 -6
  181. package/lib/oh-story/skills/story-import/scripts/check-outline-contract.js +251 -0
  182. package/lib/oh-story/skills/story-import/scripts/tracking_commit.py +98 -9
  183. package/lib/oh-story/skills/story-import/scripts/wordcount_core.py +246 -0
  184. package/lib/oh-story/skills/story-long-analyze/SKILL.md +4 -4
  185. package/lib/oh-story/skills/story-long-scan/SKILL.md +1 -1
  186. package/lib/oh-story/skills/story-long-write/SKILL.md +35 -21
  187. package/lib/oh-story/skills/story-long-write/references/anti-ai-writing.md +2 -1
  188. package/lib/oh-story/skills/story-long-write/references/artifact-protocols.md +7 -3
  189. package/lib/oh-story/skills/story-long-write/references/author-memory.md +163 -0
  190. package/lib/oh-story/skills/story-long-write/references/banned-words.md +6 -4
  191. package/lib/oh-story/skills/story-long-write/references/cross-book-recall.md +6 -6
  192. package/lib/oh-story/skills/story-long-write/references/genre-prose-cards.md +1 -1
  193. package/lib/oh-story/skills/story-long-write/references/genre-readers.md +1 -1
  194. package/lib/oh-story/skills/{story-setup/references/agent-references/hooks-chapter.md → story-long-write/references/long-chapter-hooks.md} +5 -5
  195. package/lib/oh-story/skills/story-long-write/references/{quality-checklist.md → long-chapter-quality.md} +2 -1
  196. package/lib/oh-story/skills/story-long-write/references/long-format.md +42 -0
  197. package/lib/oh-story/skills/{story-setup/references/agent-references/genre-catalog.md → story-long-write/references/long-genre-catalog.md} +11 -97
  198. package/lib/oh-story/skills/{story-setup/references/agent-references/genre-core-mechanics.md → story-long-write/references/long-genre-mechanics.md} +1 -1
  199. package/lib/oh-story/skills/{story-short-write/references/reversal-toolkit.md → story-long-write/references/long-reversal.md} +18 -32
  200. package/lib/oh-story/skills/story-long-write/references/{hooks-suspense.md → long-suspense.md} +6 -6
  201. package/lib/oh-story/skills/story-long-write/references/opening-design.md +1 -1
  202. package/lib/oh-story/skills/story-long-write/references/outline-structure-theory.md +1 -1
  203. package/lib/oh-story/skills/story-long-write/references/style-genre-modules.md +1 -1
  204. package/lib/oh-story/skills/story-long-write/references/tracking-transaction.md +14 -6
  205. package/lib/oh-story/skills/story-long-write/references/workflow-chapter.md +32 -27
  206. package/lib/oh-story/skills/story-long-write/references/workflow-daily.md +4 -4
  207. package/lib/oh-story/skills/story-long-write/references/workflow-revision.md +2 -2
  208. package/lib/oh-story/skills/story-long-write/references/workflow-setup.md +14 -14
  209. package/lib/oh-story/skills/story-long-write/references/writing-craft.md +54 -54
  210. package/lib/oh-story/skills/story-long-write/scripts/author_memory_commit.py +871 -0
  211. package/lib/oh-story/skills/story-long-write/scripts/check-ai-patterns.js +64 -1
  212. package/lib/oh-story/skills/story-long-write/scripts/check-outline-contract.js +251 -0
  213. package/lib/oh-story/skills/story-long-write/scripts/storyctl.py +303 -0
  214. package/lib/oh-story/skills/story-long-write/scripts/tracking_commit.py +98 -9
  215. package/lib/oh-story/skills/story-long-write/scripts/wordcount_core.py +246 -0
  216. package/lib/oh-story/skills/story-review/SKILL.md +26 -17
  217. package/lib/oh-story/skills/story-review/references/anti-ai-writing.md +2 -1
  218. package/lib/oh-story/skills/story-review/references/author-memory.md +163 -0
  219. package/lib/oh-story/skills/story-review/references/banned-words.md +6 -4
  220. package/lib/oh-story/skills/story-review/references/{quality-checklist.md → review-quality.md} +22 -21
  221. package/lib/oh-story/skills/story-review/references/tracking-transaction.md +14 -6
  222. package/lib/oh-story/skills/story-review/scripts/author_memory_commit.py +871 -0
  223. package/lib/oh-story/skills/story-review/scripts/check-ai-patterns.js +64 -1
  224. package/lib/oh-story/skills/story-review/scripts/tracking_commit.py +98 -9
  225. package/lib/oh-story/skills/story-review/scripts/wordcount_core.py +246 -0
  226. package/lib/oh-story/skills/story-setup/SKILL.md +74 -33
  227. package/lib/oh-story/skills/story-setup/references/agent-references/agent-quality.md +72 -0
  228. package/lib/oh-story/skills/story-setup/references/agent-references/agent-reference-profiles.md +55 -0
  229. package/lib/oh-story/skills/story-setup/references/agent-references/anti-ai-writing.md +2 -1
  230. package/lib/oh-story/skills/story-setup/references/agent-references/banned-words.md +6 -4
  231. package/lib/oh-story/skills/story-setup/references/agent-references/format-and-structure.md +9 -10
  232. package/lib/oh-story/skills/story-setup/references/agent-references/genre-prose-cards.md +1 -1
  233. package/lib/oh-story/skills/story-setup/references/agent-references/genre-readers.md +1 -1
  234. package/lib/oh-story/skills/{story-short-analyze/references/hooks-chapter.md → story-setup/references/agent-references/long-chapter-hooks.md} +5 -5
  235. package/lib/oh-story/skills/story-setup/references/agent-references/long-emotional-methods.md +209 -0
  236. package/lib/oh-story/skills/{story-long-write/references/genre-catalog.md → story-setup/references/agent-references/long-genre-catalog.md} +11 -97
  237. package/lib/oh-story/skills/{story-long-write/references/genre-core-mechanics.md → story-setup/references/agent-references/long-genre-mechanics.md} +1 -1
  238. package/lib/oh-story/skills/story-setup/references/agent-references/long-quality.md +40 -0
  239. package/lib/oh-story/skills/story-setup/references/agent-references/{reversal-toolkit.md → long-reversal.md} +18 -32
  240. package/lib/oh-story/skills/{story-short-write/references/hooks-suspense.md → story-setup/references/agent-references/long-suspense.md} +6 -6
  241. package/lib/oh-story/skills/story-setup/references/agent-references/opening-design.md +1 -1
  242. package/lib/oh-story/skills/story-setup/references/agent-references/{emotional-methods.md → short-emotional-methods.md} +4 -4
  243. package/lib/oh-story/skills/{story-long-write/references/genre-writing-formulas.md → story-setup/references/agent-references/short-genre-formulas.md} +32 -44
  244. package/lib/oh-story/skills/story-setup/references/agent-references/short-quality.md +39 -0
  245. package/lib/oh-story/skills/{story-long-write/references/reversal-toolkit.md → story-setup/references/agent-references/short-reversal.md} +29 -23
  246. package/lib/oh-story/skills/story-setup/references/agent-references/{hooks-suspense.md → short-suspense.md} +31 -31
  247. package/lib/oh-story/skills/story-setup/references/agent-references/style-genre-modules.md +1 -1
  248. package/lib/oh-story/skills/story-setup/references/agent-references/writing-craft.md +55 -55
  249. package/lib/oh-story/skills/story-short-analyze/SKILL.md +28 -28
  250. package/lib/oh-story/skills/story-short-analyze/references/{character-basics.md → analysis-character-basics.md} +1 -1
  251. package/lib/oh-story/skills/story-short-analyze/references/{character-design-methods.md → analysis-character-design.md} +1 -1
  252. package/lib/oh-story/skills/story-short-analyze/references/{character-relations.md → analysis-character-relations.md} +1 -1
  253. package/lib/oh-story/skills/story-short-analyze/references/{hooks-paragraph.md → analysis-paragraph-hooks.md} +1 -1
  254. package/lib/oh-story/skills/story-short-analyze/references/{genre-readers.md → analysis-reader-profile.md} +2 -2
  255. package/lib/oh-story/skills/story-short-analyze/references/analysis-report-style.md +45 -0
  256. package/lib/oh-story/skills/story-short-analyze/references/analysis-short-genres.md +65 -0
  257. package/lib/oh-story/skills/story-short-analyze/references/analysis-short-hooks.md +77 -0
  258. package/lib/oh-story/skills/story-short-analyze/references/analysis-short-mechanics.md +82 -0
  259. package/lib/oh-story/skills/story-short-analyze/references/analysis-short-patterns.md +50 -0
  260. package/lib/oh-story/skills/story-short-analyze/references/analysis-short-suspense.md +98 -0
  261. package/lib/oh-story/skills/story-short-analyze/references/{genre-writing-techniques.md → analysis-writing-techniques.md} +21 -19
  262. package/lib/oh-story/skills/story-short-analyze/references/deconstruction-examples.md +1 -1
  263. package/lib/oh-story/skills/story-short-analyze/references/material-decomposition.md +21 -28
  264. package/lib/oh-story/skills/story-short-analyze/references/output-contract.md +1 -1
  265. package/lib/oh-story/skills/story-short-analyze/references/output-templates.md +17 -17
  266. package/lib/oh-story/skills/story-short-analyze/references/{quality-checklist.md → source-story-quality.md} +28 -49
  267. package/lib/oh-story/skills/story-short-analyze/references/zhihu-style.md +2 -2
  268. package/lib/oh-story/skills/story-short-scan/SKILL.md +1 -1
  269. package/lib/oh-story/skills/story-short-write/SKILL.md +78 -55
  270. package/lib/oh-story/skills/story-short-write/references/author-memory.md +163 -0
  271. package/lib/oh-story/skills/story-short-write/references/banned-words.md +6 -4
  272. package/lib/oh-story/skills/story-short-write/references/cross-book-recall.md +3 -3
  273. package/lib/oh-story/skills/story-short-write/references/emotional-methods.md +4 -4
  274. package/lib/oh-story/skills/story-short-write/references/genre-styles//344/270/226/346/203/205/346/211/223/350/204/270.md +3 -3
  275. package/lib/oh-story/skills/story-short-write/references/genre-styles//345/217/214/347/224/267/344/270/273.md +2 -2
  276. package/lib/oh-story/skills/story-short-write/references/genre-styles//345/244/215/344/273/207/346/211/223/350/204/270.md +3 -3
  277. package/lib/oh-story/skills/story-short-write/references/genre-styles//345/256/205/346/226/227/345/256/253/346/226/227.md +6 -6
  278. package/lib/oh-story/skills/story-short-write/references/genre-styles//346/200/273/350/243/201/350/261/252/351/227/250.md +3 -3
  279. package/lib/oh-story/skills/story-short-write/references/genre-styles//346/202/254/347/226/221.md +4 -4
  280. package/lib/oh-story/skills/story-short-write/references/genre-styles//346/260/221/344/277/227/346/200/252/350/260/210.md +7 -7
  281. package/lib/oh-story/skills/story-short-write/references/genre-styles//346/262/231/351/233/225/350/204/221/346/264/236.md +5 -5
  282. package/lib/oh-story/skills/story-short-write/references/genre-styles//347/224/234/345/256/240.md +4 -4
  283. package/lib/oh-story/skills/story-short-write/references/genre-styles//350/277/275/345/246/273/347/201/253/350/221/254/345/234/272.md +3 -3
  284. package/lib/oh-story/skills/story-short-write/references/genre-writing-formulas.md +32 -44
  285. package/lib/oh-story/skills/story-short-write/references/genre-writing-techniques.md +20 -18
  286. package/lib/oh-story/skills/story-short-write/references/output-contract.md +1 -1
  287. package/lib/oh-story/skills/story-short-write/references/short-craft.md +18 -18
  288. package/lib/oh-story/skills/story-short-write/references/short-deslop.md +1 -1
  289. package/lib/oh-story/skills/story-short-write/references/short-format.md +38 -8
  290. package/lib/oh-story/skills/story-short-write/references/{quality-checklist.md → short-prose-quality.md} +22 -21
  291. package/lib/oh-story/skills/story-short-write/references/short-reversal.md +355 -0
  292. package/lib/oh-story/skills/{story-short-analyze/references/hooks-suspense.md → story-short-write/references/short-suspense.md} +31 -31
  293. package/lib/oh-story/skills/story-short-write/references/submission-craft.md +2 -2
  294. package/lib/oh-story/skills/story-short-write/references/writing-workflow.md +31 -22
  295. package/lib/oh-story/skills/story-short-write/scripts/author_memory_commit.py +871 -0
  296. package/lib/oh-story/skills/story-short-write/scripts/check-ai-patterns.js +64 -1
  297. package/lib/oh-story/skills/story-short-write/scripts/check-delivery-contract.js +212 -0
  298. package/lib/oh-story/skills/story-short-write/scripts/check-phase2-contract.js +363 -0
  299. package/lib/types/client/drama-production-view.d.ts +34 -0
  300. package/lib/types/client/drama-production-view.d.ts.map +1 -0
  301. package/lib/types/client/drama-production.d.ts +92 -0
  302. package/lib/types/client/drama-production.d.ts.map +1 -0
  303. package/lib/types/client/file-activity.d.ts +4 -2
  304. package/lib/types/client/file-activity.d.ts.map +1 -1
  305. package/lib/types/client/index.d.ts +1 -1
  306. package/lib/types/client/index.d.ts.map +1 -1
  307. package/lib/types/client/production-intents.d.ts +9 -0
  308. package/lib/types/client/production-intents.d.ts.map +1 -0
  309. package/lib/types/client/production-prompts.d.ts +9 -0
  310. package/lib/types/client/production-prompts.d.ts.map +1 -0
  311. package/lib/types/client/production-runtime.d.ts +58 -0
  312. package/lib/types/client/production-runtime.d.ts.map +1 -0
  313. package/lib/types/client/video-studio.d.ts +41 -0
  314. package/lib/types/client/video-studio.d.ts.map +1 -0
  315. package/lib/types/client/workbench-ui.d.ts +5 -0
  316. package/lib/types/client/workbench-ui.d.ts.map +1 -0
  317. package/lib/types/game-verification.d.ts +16 -0
  318. package/lib/types/game-verification.d.ts.map +1 -0
  319. package/lib/types/index.d.ts +3 -1
  320. package/lib/types/index.d.ts.map +1 -1
  321. package/lib/types/production-intent.d.ts +21 -0
  322. package/lib/types/production-intent.d.ts.map +1 -0
  323. package/lib/types/production-tool.d.ts +5 -0
  324. package/lib/types/production-tool.d.ts.map +1 -0
  325. package/lib/types/role-tool.d.ts.map +1 -1
  326. package/lib/types/skill-provider.d.ts +7 -0
  327. package/lib/types/skill-provider.d.ts.map +1 -1
  328. package/lib/types/video-project.d.ts +42 -0
  329. package/lib/types/video-project.d.ts.map +1 -0
  330. package/lib/types/workspace-request-trust.d.ts +6 -0
  331. package/lib/types/workspace-request-trust.d.ts.map +1 -1
  332. package/lib/types/workspace-route.d.ts +20 -0
  333. package/lib/types/workspace-route.d.ts.map +1 -1
  334. package/lib/video-recap/CHANGELOG.md +282 -0
  335. package/lib/video-recap/LICENSE +21 -0
  336. package/lib/video-recap/README.en.md +257 -0
  337. package/lib/video-recap/README.md +255 -0
  338. package/lib/video-recap/manifest.json +684 -0
  339. package/lib/video-recap/skills/video-assemble/SKILL.md +97 -0
  340. package/lib/video-recap/skills/video-assemble/references/jianying/LICENSE.duo-video +21 -0
  341. package/lib/video-recap/skills/video-assemble/references/jianying/SOURCE.md +15 -0
  342. package/lib/video-recap/skills/video-assemble/references/jianying/empty_draft_meta_info.json +69 -0
  343. package/lib/video-recap/skills/video-assemble/references/jianying/empty_jy_combination_segment.json +84 -0
  344. package/lib/video-recap/skills/video-assemble/references/jianying/empty_jy_combination_video_material.json +98 -0
  345. package/lib/video-recap/skills/video-assemble/references/jianying/empty_jy_draft.json +204 -0
  346. package/lib/video-recap/skills/video-assemble/references/jianying/empty_jy_material_video.json +83 -0
  347. package/lib/video-recap/skills/video-assemble/references/jianying/empty_jy_meta_material_value.json +23 -0
  348. package/lib/video-recap/skills/video-assemble/references/jianying/empty_jy_project_info.json +133 -0
  349. package/lib/video-recap/skills/video-assemble/references/jianying/empty_jy_segment.json +70 -0
  350. package/lib/video-recap/skills/video-assemble/references/jianying/empty_jy_text_styles.json +30 -0
  351. package/lib/video-recap/skills/video-assemble/references/jianying/empty_yj_material_audio.json +41 -0
  352. package/lib/video-recap/skills/video-assemble/references/jianying/empty_yj_material_text.json +109 -0
  353. package/lib/video-recap/skills/video-assemble/scripts/artifacts.py +88 -0
  354. package/lib/video-recap/skills/video-assemble/scripts/assemble.py +345 -0
  355. package/lib/video-recap/skills/video-assemble/scripts/assemble_constants.py +34 -0
  356. package/lib/video-recap/skills/video-assemble/scripts/assembly_contract.py +305 -0
  357. package/lib/video-recap/skills/video-assemble/scripts/assembly_settings.py +94 -0
  358. package/lib/video-recap/skills/video-assemble/scripts/audio_automation.py +205 -0
  359. package/lib/video-recap/skills/video-assemble/scripts/audio_mix.py +555 -0
  360. package/lib/video-recap/skills/video-assemble/scripts/export_jianying.py +261 -0
  361. package/lib/video-recap/skills/video-assemble/scripts/jianying_builders.py +767 -0
  362. package/lib/video-recap/skills/video-assemble/scripts/jianying_model.py +111 -0
  363. package/lib/video-recap/skills/video-assemble/scripts/jianying_optional.py +24 -0
  364. package/lib/video-recap/skills/video-assemble/scripts/jianying_schema.py +109 -0
  365. package/lib/video-recap/skills/video-assemble/scripts/jianying_templates.py +37 -0
  366. package/lib/video-recap/skills/video-assemble/scripts/jianying_timeline_contract.py +191 -0
  367. package/lib/video-recap/skills/video-assemble/scripts/jianying_tracks.py +75 -0
  368. package/lib/video-recap/skills/video-assemble/scripts/jianying_writer.py +394 -0
  369. package/lib/video-recap/skills/video-assemble/scripts/lib.py +239 -0
  370. package/lib/video-recap/skills/video-assemble/scripts/media.py +243 -0
  371. package/lib/video-recap/skills/video-assemble/scripts/narration_audio.py +477 -0
  372. package/lib/video-recap/skills/video-assemble/scripts/render_preflight.py +46 -0
  373. package/lib/video-recap/skills/video-assemble/scripts/source_subtitles.py +486 -0
  374. package/lib/video-recap/skills/video-assemble/scripts/subtitle_core.py +376 -0
  375. package/lib/video-recap/skills/video-assemble/scripts/subtitle_render.py +88 -0
  376. package/lib/video-recap/skills/video-assemble/scripts/timeline.py +248 -0
  377. package/lib/video-recap/skills/video-assemble/scripts/timeline_emit.py +89 -0
  378. package/lib/video-recap/skills/video-assemble/scripts/visual_render.py +512 -0
  379. package/lib/video-recap/skills/video-cut/SKILL.md +90 -0
  380. package/lib/video-recap/skills/video-cut/scripts/cut.py +67 -0
  381. package/lib/video-recap/skills/video-cut/scripts/cut_cli.py +320 -0
  382. package/lib/video-recap/skills/video-cut/scripts/cut_contract.py +545 -0
  383. package/lib/video-recap/skills/video-cut/scripts/cut_render.py +348 -0
  384. package/lib/video-recap/skills/video-cut/scripts/lib.py +77 -0
  385. package/lib/video-recap/skills/video-cut/scripts/media_geometry.py +341 -0
  386. package/lib/video-recap/skills/video-cut/scripts/narration_mapping.py +249 -0
  387. package/lib/video-recap/skills/video-cut/scripts/sentence_boundaries.py +745 -0
  388. package/lib/video-recap/skills/video-recap/SKILL.md +216 -0
  389. package/lib/video-recap/skills/video-recap/references/config-playbook.md +61 -0
  390. package/lib/video-recap/skills/video-recap/references/creative-editing-playbook.md +225 -0
  391. package/lib/video-recap/skills/video-recap/references/data-schema.md +534 -0
  392. package/lib/video-recap/skills/video-recap/references/research-guide.md +74 -0
  393. package/lib/video-recap/skills/video-recap/references/shift-left-qc-schema.md +23 -0
  394. package/lib/video-recap/skills/video-recap/references/timeline-and-jianying.md +251 -0
  395. package/lib/video-recap/skills/video-recap/scripts/doctor.py +483 -0
  396. package/lib/video-recap/skills/video-recap/scripts/final_qc.py +737 -0
  397. package/lib/video-recap/skills/video-recap/scripts/lib.py +242 -0
  398. package/lib/video-recap/skills/video-recap/scripts/materials.py +457 -0
  399. package/lib/video-recap/skills/video-recap/scripts/mimo_qc.py +95 -0
  400. package/lib/video-recap/skills/video-recap/scripts/mimo_qc_client.py +18 -0
  401. package/lib/video-recap/skills/video-recap/scripts/mimo_qc_contract.py +9 -0
  402. package/lib/video-recap/skills/video-recap/scripts/mimo_qc_evidence.py +371 -0
  403. package/lib/video-recap/skills/video-recap/scripts/mimo_qc_observations.py +201 -0
  404. package/lib/video-recap/skills/video-recap/scripts/mimo_qc_payload.py +227 -0
  405. package/lib/video-recap/skills/video-recap/scripts/mimo_qc_report.py +362 -0
  406. package/lib/video-recap/skills/video-recap/scripts/mimo_qc_runner.py +129 -0
  407. package/lib/video-recap/skills/video-recap/scripts/qc_contract.py +338 -0
  408. package/lib/video-recap/skills/video-recap/scripts/recap.py +9 -0
  409. package/lib/video-recap/skills/video-recap/scripts/recap_cli.py +140 -0
  410. package/lib/video-recap/skills/video-recap/scripts/recap_inspect.py +550 -0
  411. package/lib/video-recap/skills/video-recap/scripts/recap_review.py +77 -0
  412. package/lib/video-recap/skills/video-recap/scripts/recap_runner.py +654 -0
  413. package/lib/video-recap/skills/video-recap/scripts/recap_runtime.py +335 -0
  414. package/lib/video-recap/skills/video-recap/scripts/recap_stage_qc.py +217 -0
  415. package/lib/video-recap/skills/video-recap/scripts/recap_timeline.py +795 -0
  416. package/lib/video-recap/skills/video-script/SKILL.md +248 -0
  417. package/lib/video-recap/skills/video-script/references/creative-editing-playbook.md +225 -0
  418. package/lib/video-recap/skills/video-script/references/research-guide.md +75 -0
  419. package/lib/video-recap/skills/video-script/scripts/agent_brief.py +399 -0
  420. package/lib/video-recap/skills/video-script/scripts/agent_text.py +410 -0
  421. package/lib/video-recap/skills/video-script/scripts/brief_context.py +403 -0
  422. package/lib/video-recap/skills/video-script/scripts/brief_inputs.py +332 -0
  423. package/lib/video-recap/skills/video-script/scripts/brief_timeline.py +442 -0
  424. package/lib/video-recap/skills/video-script/scripts/deslop_qc.py +237 -0
  425. package/lib/video-recap/skills/video-script/scripts/evidence_bundle.py +492 -0
  426. package/lib/video-recap/skills/video-script/scripts/lib.py +327 -0
  427. package/lib/video-recap/skills/video-script/scripts/narration.py +12 -0
  428. package/lib/video-recap/skills/video-script/scripts/narration_lint.py +678 -0
  429. package/lib/video-recap/skills/video-script/scripts/review.py +42 -0
  430. package/lib/video-recap/skills/video-script/scripts/review_grounding.py +262 -0
  431. package/lib/video-recap/skills/video-script/scripts/review_response.py +761 -0
  432. package/lib/video-recap/skills/video-script/scripts/review_runner.py +200 -0
  433. package/lib/video-recap/skills/video-script/scripts/speech_ownership.py +204 -0
  434. package/lib/video-recap/skills/video-script/scripts/timeline_fusion.py +199 -0
  435. package/lib/video-recap/skills/video-script/scripts/validate.py +164 -0
  436. package/lib/video-recap/skills/video-understanding/SKILL.md +75 -0
  437. package/lib/video-recap/skills/video-understanding/references/data-schema.md +299 -0
  438. package/lib/video-recap/skills/video-understanding/references/prompt-templates.md +37 -0
  439. package/lib/video-recap/skills/video-understanding/references/research-guide.md +74 -0
  440. package/lib/video-recap/skills/video-understanding/scripts/agent_brief.py +399 -0
  441. package/lib/video-recap/skills/video-understanding/scripts/agent_text.py +410 -0
  442. package/lib/video-recap/skills/video-understanding/scripts/asr.py +260 -0
  443. package/lib/video-recap/skills/video-understanding/scripts/brief.py +12 -0
  444. package/lib/video-recap/skills/video-understanding/scripts/brief_context.py +403 -0
  445. package/lib/video-recap/skills/video-understanding/scripts/brief_inputs.py +332 -0
  446. package/lib/video-recap/skills/video-understanding/scripts/brief_timeline.py +442 -0
  447. package/lib/video-recap/skills/video-understanding/scripts/consolidate.py +647 -0
  448. package/lib/video-recap/skills/video-understanding/scripts/deslop_qc.py +237 -0
  449. package/lib/video-recap/skills/video-understanding/scripts/detect.py +513 -0
  450. package/lib/video-recap/skills/video-understanding/scripts/extract.py +62 -0
  451. package/lib/video-recap/skills/video-understanding/scripts/lib.py +470 -0
  452. package/lib/video-recap/skills/video-understanding/scripts/narration_lint.py +678 -0
  453. package/lib/video-recap/skills/video-understanding/scripts/speech_ownership.py +204 -0
  454. package/lib/video-recap/skills/video-understanding/scripts/storyboard.py +507 -0
  455. package/lib/video-recap/skills/video-understanding/scripts/timeline_fusion.py +199 -0
  456. package/lib/video-recap/skills/video-understanding/scripts/understand.py +9 -0
  457. package/lib/video-recap/skills/video-understanding/scripts/understanding_brief.py +216 -0
  458. package/lib/video-recap/skills/video-understanding/scripts/understanding_cache.py +327 -0
  459. package/lib/video-recap/skills/video-understanding/scripts/understanding_runner.py +367 -0
  460. package/lib/video-recap/skills/video-understanding/scripts/understanding_storyboard.py +162 -0
  461. package/lib/video-recap/skills/video-understanding/scripts/vlm.py +705 -0
  462. package/lib/video-recap/skills/video-voiceover/SKILL.md +81 -0
  463. package/lib/video-recap/skills/video-voiceover/scripts/dub.py +637 -0
  464. package/lib/video-recap/skills/video-voiceover/scripts/fish_audio.py +109 -0
  465. package/lib/video-recap/skills/video-voiceover/scripts/lib.py +421 -0
  466. package/lib/video-recap/skills/video-voiceover/scripts/tts_audio.py +113 -0
  467. package/lib/video-recap/skills/video-voiceover/scripts/voiceover.py +782 -0
  468. package/package.json +55 -40
  469. package/lib/oh-story/skills/story-deslop/scripts/check-outline-copy.js +0 -241
  470. package/lib/oh-story/skills/story-long-write/references/format-and-structure.md +0 -169
  471. package/lib/oh-story/skills/story-setup/references/agent-references/genre-writing-formulas.md +0 -444
  472. package/lib/oh-story/skills/story-setup/references/agent-references/quality-checklist.md +0 -247
  473. package/lib/oh-story/skills/story-short-analyze/references/anti-ai-writing.md +0 -582
  474. package/lib/oh-story/skills/story-short-analyze/references/banned-words.md +0 -147
  475. package/lib/oh-story/skills/story-short-analyze/references/genre-catalog.md +0 -490
  476. package/lib/oh-story/skills/story-short-analyze/references/genre-core-mechanics.md +0 -425
  477. package/lib/oh-story/skills/story-short-analyze/references/genre-writing-formulas.md +0 -453
  478. /package/lib/oh-story/skills/{story-long-write/references/hooks-chapter.md → story-setup/references/agent-references/short-chapter-hooks.md} +0 -0
  479. /package/lib/oh-story/skills/{story-long-write/references/hooks-paragraph.md → story-setup/references/agent-references/short-paragraph-hooks.md} +0 -0
@@ -0,0 +1,871 @@
1
+ #!/usr/bin/env python3
2
+ """Maintain evidence-backed author preferences and deterministic Markdown views.
3
+
4
+ The language model supplies compact semantic transactions. This tool validates
5
+ and applies them in memory, renders every derived view, and writes the JSON state
6
+ last as the commit point. Author memory is workspace-level and deliberately
7
+ separate from each book's story-continuity tracking.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import copy
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import stat
18
+ import sys
19
+ import tempfile
20
+ from datetime import datetime, timezone
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+
25
+ INPUT_SCHEMA_VERSION = 1
26
+ STATE_SCHEMA_VERSION = 1
27
+ STATE_MAX_BYTES = 2 * 1024 * 1024
28
+ PROFILE_MAX_BYTES = 12288
29
+ PENDING_MAX_BYTES = 12288
30
+ JOURNAL_MAX_BYTES = 24576
31
+ QUERY_MAX_BYTES = 2048
32
+
33
+ KINDS = ("prose_style", "story_design", "workflow", "delivery", "interaction")
34
+ KIND_TITLES = {
35
+ "prose_style": "文风与表达",
36
+ "story_design": "故事设计",
37
+ "workflow": "创作流程",
38
+ "delivery": "交付格式",
39
+ "interaction": "协作方式",
40
+ }
41
+ SCOPE_LEVELS = ("global", "genre", "book", "workflow")
42
+ STATUSES = ("active", "pending", "conflict", "rejected", "superseded")
43
+ CONFIDENCE_LEVELS = ("low", "medium", "high")
44
+ IMPORTANCE_LEVELS = ("low", "medium", "high")
45
+ SOURCES = (
46
+ "explicit_user",
47
+ "accepted_suggestion",
48
+ "repeated_correction",
49
+ "inferred_pattern",
50
+ "manual",
51
+ )
52
+ RANK = {"low": 0, "medium": 1, "high": 2}
53
+
54
+
55
+ class AuthorMemoryError(ValueError):
56
+ """Expected validation or state error."""
57
+
58
+
59
+ def require(condition: bool, message: str) -> None:
60
+ if not condition:
61
+ raise AuthorMemoryError(message)
62
+
63
+
64
+ def as_mapping(value: object, label: str) -> dict[str, Any]:
65
+ require(isinstance(value, dict), f"{label} must be a JSON object")
66
+ return value
67
+
68
+
69
+ def as_list(value: object, label: str) -> list[Any]:
70
+ require(isinstance(value, list), f"{label} must be a JSON array")
71
+ return value
72
+
73
+
74
+ def as_int(value: object, label: str, *, minimum: int = 0) -> int:
75
+ require(isinstance(value, int) and not isinstance(value, bool), f"{label} must be an integer")
76
+ require(value >= minimum, f"{label} must be >= {minimum}")
77
+ return value
78
+
79
+
80
+ def require_known_keys(mapping: dict[str, Any], allowed: set[str], label: str) -> None:
81
+ unknown = set(mapping) - allowed
82
+ require(not unknown, f"{label} contains unsupported fields: {', '.join(sorted(unknown))}")
83
+
84
+
85
+ def clean_text(value: object, label: str, *, max_bytes: int = 768) -> str:
86
+ require(isinstance(value, str), f"{label} must be a string")
87
+ cleaned = " ".join(value.replace("|", "|").split())
88
+ require(bool(cleaned), f"{label} must not be empty")
89
+ require(len(cleaned.encode("utf-8")) <= max_bytes, f"{label} exceeds {max_bytes} bytes")
90
+ return cleaned
91
+
92
+
93
+ def optional_text(value: object, label: str, *, max_bytes: int = 768) -> str | None:
94
+ if value is None:
95
+ return None
96
+ return clean_text(value, label, max_bytes=max_bytes)
97
+
98
+
99
+ def choice(value: object, allowed: tuple[str, ...], label: str) -> str:
100
+ require(isinstance(value, str) and value in allowed, f"{label} must be one of: {', '.join(allowed)}")
101
+ return value
102
+
103
+
104
+ def clean_id_list(value: object, label: str, *, maximum: int = 32) -> list[str]:
105
+ raw = as_list(value, label)
106
+ require(len(raw) <= maximum, f"{label} may contain at most {maximum} items")
107
+ result: list[str] = []
108
+ for index, item in enumerate(raw):
109
+ item_id = clean_text(item, f"{label}[{index}]", max_bytes=32)
110
+ require(item_id.startswith("AP") and item_id[2:].isdigit() and int(item_id[2:]) >= 1, f"{label}[{index}] is not an author-memory id")
111
+ if item_id not in result:
112
+ result.append(item_id)
113
+ return result
114
+
115
+
116
+ def emit(document: object, *, error: bool = False) -> None:
117
+ payload = json.dumps(document, ensure_ascii=False, sort_keys=True)
118
+ stream = sys.stderr if error else sys.stdout
119
+ stream.flush()
120
+ stream.buffer.write((payload + "\n").encode("utf-8"))
121
+ stream.buffer.flush()
122
+
123
+
124
+ def json_payload(document: object) -> str:
125
+ return json.dumps(document, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
126
+
127
+
128
+ def read_json(path: Path) -> object:
129
+ try:
130
+ require(path.stat().st_size <= STATE_MAX_BYTES, f"{path} exceeds {STATE_MAX_BYTES} bytes")
131
+ return json.loads(path.read_text(encoding="utf-8"))
132
+ except (OSError, json.JSONDecodeError) as exc:
133
+ raise AuthorMemoryError(f"unable to read JSON {path}: {exc}") from exc
134
+
135
+
136
+ def atomic_write_text(path: Path, payload: str) -> None:
137
+ path.parent.mkdir(parents=True, exist_ok=True)
138
+ mode = stat.S_IMODE(path.stat().st_mode) if path.exists() else 0o644
139
+ fd, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
140
+ temporary = Path(temporary_name)
141
+ try:
142
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
143
+ handle.write(payload)
144
+ handle.flush()
145
+ os.fsync(handle.fileno())
146
+ os.chmod(temporary, mode)
147
+ os.replace(temporary, path)
148
+ finally:
149
+ temporary.unlink(missing_ok=True)
150
+
151
+
152
+ def write_if_changed(path: Path, payload: str) -> None:
153
+ try:
154
+ if path.read_text(encoding="utf-8") == payload:
155
+ return
156
+ except FileNotFoundError:
157
+ pass
158
+ atomic_write_text(path, payload)
159
+
160
+
161
+ def memory_root(workspace: Path) -> Path:
162
+ return workspace.resolve() / ".story" / "作者记忆"
163
+
164
+
165
+ def state_path(workspace: Path) -> Path:
166
+ return memory_root(workspace) / "_author-memory-state.json"
167
+
168
+
169
+ def empty_state() -> dict[str, Any]:
170
+ return {
171
+ "schema_version": STATE_SCHEMA_VERSION,
172
+ "state_revision": 0,
173
+ "next_item_number": 1,
174
+ "items": {},
175
+ "journal": [],
176
+ "applied_transactions": {},
177
+ }
178
+
179
+
180
+ def normalize_scope(value: object, label: str) -> dict[str, str | None]:
181
+ scope = as_mapping(value, label)
182
+ require_known_keys(scope, {"level", "value"}, label)
183
+ level = choice(scope.get("level"), SCOPE_LEVELS, f"{label}.level")
184
+ raw_value = scope.get("value")
185
+ if level == "global":
186
+ require(raw_value is None, f"{label}.value must be null for global scope")
187
+ normalized_value = None
188
+ else:
189
+ normalized_value = clean_text(raw_value, f"{label}.value", max_bytes=180)
190
+ return {"level": level, "value": normalized_value}
191
+
192
+
193
+ def normalize_evidence(value: object, label: str) -> dict[str, str | None]:
194
+ evidence = as_mapping(value, label)
195
+ require_known_keys(evidence, {"quote", "source_ref"}, label)
196
+ return {
197
+ "quote": clean_text(evidence.get("quote"), f"{label}.quote", max_bytes=768),
198
+ "source_ref": optional_text(evidence.get("source_ref"), f"{label}.source_ref", max_bytes=240),
199
+ }
200
+
201
+
202
+ def normalize_item(value: object, label: str) -> dict[str, Any]:
203
+ item = as_mapping(value, label)
204
+ allowed = {
205
+ "id", "kind", "scope", "assertion", "confidence", "importance", "status", "source",
206
+ "reason", "conflicts_with", "confirmation_count", "evidence", "created_revision",
207
+ "updated_revision", "superseded_by",
208
+ }
209
+ require_known_keys(item, allowed, label)
210
+ item_id = clean_text(item.get("id"), f"{label}.id", max_bytes=32)
211
+ require(item_id.startswith("AP") and item_id[2:].isdigit() and int(item_id[2:]) >= 1, f"{label}.id is invalid")
212
+ evidence = [normalize_evidence(entry, f"{label}.evidence[{index}]") for index, entry in enumerate(as_list(item.get("evidence"), f"{label}.evidence"))]
213
+ require(bool(evidence), f"{label}.evidence must not be empty")
214
+ status = choice(item.get("status"), STATUSES, f"{label}.status")
215
+ conflicts = clean_id_list(item.get("conflicts_with"), f"{label}.conflicts_with")
216
+ superseded_by = optional_text(item.get("superseded_by"), f"{label}.superseded_by", max_bytes=32)
217
+ if superseded_by is not None:
218
+ require(superseded_by.startswith("AP") and superseded_by[2:].isdigit(), f"{label}.superseded_by is invalid")
219
+ return {
220
+ "id": item_id,
221
+ "kind": choice(item.get("kind"), KINDS, f"{label}.kind"),
222
+ "scope": normalize_scope(item.get("scope"), f"{label}.scope"),
223
+ "assertion": clean_text(item.get("assertion"), f"{label}.assertion", max_bytes=768),
224
+ "confidence": choice(item.get("confidence"), CONFIDENCE_LEVELS, f"{label}.confidence"),
225
+ "importance": choice(item.get("importance"), IMPORTANCE_LEVELS, f"{label}.importance"),
226
+ "status": status,
227
+ "source": choice(item.get("source"), SOURCES, f"{label}.source"),
228
+ "reason": clean_text(item.get("reason"), f"{label}.reason", max_bytes=480),
229
+ "conflicts_with": conflicts,
230
+ "confirmation_count": as_int(item.get("confirmation_count"), f"{label}.confirmation_count", minimum=1),
231
+ "evidence": evidence,
232
+ "created_revision": as_int(item.get("created_revision"), f"{label}.created_revision", minimum=1),
233
+ "updated_revision": as_int(item.get("updated_revision"), f"{label}.updated_revision", minimum=1),
234
+ "superseded_by": superseded_by,
235
+ }
236
+
237
+
238
+ def validate_state(value: object) -> dict[str, Any]:
239
+ state = as_mapping(value, "state")
240
+ allowed = {"schema_version", "state_revision", "next_item_number", "items", "journal", "applied_transactions"}
241
+ require_known_keys(state, allowed, "state")
242
+ require(state.get("schema_version") == STATE_SCHEMA_VERSION, f"state.schema_version must be {STATE_SCHEMA_VERSION}")
243
+ revision = as_int(state.get("state_revision"), "state.state_revision")
244
+ next_number = as_int(state.get("next_item_number"), "state.next_item_number", minimum=1)
245
+ raw_items = as_mapping(state.get("items"), "state.items")
246
+ items: dict[str, Any] = {}
247
+ max_number = 0
248
+ for raw_id, raw_item in raw_items.items():
249
+ normalized = normalize_item(raw_item, f"state.items.{raw_id}")
250
+ require(raw_id == normalized["id"], f"state.items key {raw_id} does not match item id")
251
+ max_number = max(max_number, int(raw_id[2:]))
252
+ require(normalized["created_revision"] <= normalized["updated_revision"] <= revision, f"state.items.{raw_id} revision is ahead of state")
253
+ items[raw_id] = normalized
254
+ require(next_number > max_number, "state.next_item_number must be greater than every allocated item id")
255
+ for item_id, item in items.items():
256
+ for conflict_id in item["conflicts_with"]:
257
+ require(conflict_id in items and conflict_id != item_id, f"state.items.{item_id} has an invalid conflict id")
258
+ if item["superseded_by"] is not None:
259
+ require(item["superseded_by"] in items and item["superseded_by"] != item_id, f"state.items.{item_id} has an invalid superseded_by id")
260
+ if item["status"] == "active":
261
+ require(not item["conflicts_with"], f"active item {item_id} cannot retain conflicts")
262
+ if item["status"] == "pending":
263
+ require(not item["conflicts_with"], f"pending item {item_id} cannot retain conflicts")
264
+ if item["status"] == "conflict":
265
+ require(bool(item["conflicts_with"]), f"conflict item {item_id} must reference an active item")
266
+ require(all(items[conflict_id]["status"] == "active" for conflict_id in item["conflicts_with"]), f"conflict item {item_id} must reference only active items")
267
+ if item["status"] != "superseded":
268
+ require(item["superseded_by"] is None, f"only superseded item {item_id} may set superseded_by")
269
+ journal = as_list(state.get("journal"), "state.journal")
270
+ require(len(journal) == revision, "state.journal length must equal state.state_revision")
271
+ journal_revisions: dict[str, int] = {}
272
+ for index, entry in enumerate(journal):
273
+ mapping = as_mapping(entry, f"state.journal[{index}]")
274
+ require_known_keys(mapping, {"revision", "transaction_id", "committed_at", "summaries"}, f"state.journal[{index}]")
275
+ entry_revision = as_int(mapping.get("revision"), f"state.journal[{index}].revision", minimum=1)
276
+ require(entry_revision == index + 1, f"state.journal[{index}].revision must be {index + 1}")
277
+ transaction_id = clean_text(mapping.get("transaction_id"), f"state.journal[{index}].transaction_id", max_bytes=128)
278
+ require(transaction_id not in journal_revisions, f"state.journal repeats transaction_id {transaction_id}")
279
+ journal_revisions[transaction_id] = entry_revision
280
+ clean_text(mapping.get("committed_at"), f"state.journal[{index}].committed_at", max_bytes=64)
281
+ summaries = as_list(mapping.get("summaries"), f"state.journal[{index}].summaries")
282
+ require(bool(summaries), f"state.journal[{index}].summaries must not be empty")
283
+ for summary_index, summary in enumerate(summaries):
284
+ clean_text(summary, f"state.journal[{index}].summaries[{summary_index}]", max_bytes=768)
285
+ transactions = as_mapping(state.get("applied_transactions"), "state.applied_transactions")
286
+ require(set(transactions) == set(journal_revisions), "state.applied_transactions must match state.journal transaction ids")
287
+ for transaction_id, record in transactions.items():
288
+ clean_text(transaction_id, "state.applied_transactions key", max_bytes=128)
289
+ mapping = as_mapping(record, f"state.applied_transactions.{transaction_id}")
290
+ require_known_keys(mapping, {"revision", "digest", "item_ids"}, f"state.applied_transactions.{transaction_id}")
291
+ transaction_revision = as_int(mapping.get("revision"), f"state.applied_transactions.{transaction_id}.revision", minimum=1)
292
+ require(transaction_revision == journal_revisions[transaction_id], f"state.applied_transactions.{transaction_id}.revision does not match journal")
293
+ digest = clean_text(mapping.get("digest"), f"state.applied_transactions.{transaction_id}.digest", max_bytes=64)
294
+ require(len(digest) == 64 and all(char in "0123456789abcdef" for char in digest), f"state.applied_transactions.{transaction_id}.digest is invalid")
295
+ item_ids = clean_id_list(mapping.get("item_ids"), f"state.applied_transactions.{transaction_id}.item_ids")
296
+ require(bool(item_ids), f"state.applied_transactions.{transaction_id}.item_ids must not be empty")
297
+ require(all(item_id in items for item_id in item_ids), f"state.applied_transactions.{transaction_id}.item_ids references an unknown item")
298
+ return {
299
+ "schema_version": STATE_SCHEMA_VERSION,
300
+ "state_revision": revision,
301
+ "next_item_number": next_number,
302
+ "items": items,
303
+ "journal": copy.deepcopy(journal),
304
+ "applied_transactions": copy.deepcopy(transactions),
305
+ }
306
+
307
+
308
+ def normalize_preference(value: object, label: str, *, allow_status: bool) -> dict[str, Any]:
309
+ preference = as_mapping(value, label)
310
+ allowed = {"kind", "scope", "assertion", "quote", "source_ref", "source", "confidence", "importance", "reason"}
311
+ if allow_status:
312
+ allowed |= {"status", "conflicts_with"}
313
+ require_known_keys(preference, allowed, label)
314
+ source = choice(preference.get("source"), SOURCES, f"{label}.source")
315
+ status = choice(preference.get("status"), ("active", "pending", "conflict"), f"{label}.status") if allow_status else "active"
316
+ conflicts = clean_id_list(preference.get("conflicts_with", []), f"{label}.conflicts_with") if allow_status else []
317
+ if status == "active":
318
+ require(not conflicts, f"{label}.conflicts_with must be empty for active status")
319
+ require(source not in {"repeated_correction", "inferred_pattern"}, f"{label} inferred evidence must remain pending")
320
+ elif status == "conflict":
321
+ require(bool(conflicts), f"{label}.conflicts_with is required for conflict status")
322
+ else:
323
+ require(not conflicts, f"{label}.conflicts_with is only valid for conflict status")
324
+ return {
325
+ "kind": choice(preference.get("kind"), KINDS, f"{label}.kind"),
326
+ "scope": normalize_scope(preference.get("scope"), f"{label}.scope"),
327
+ "assertion": clean_text(preference.get("assertion"), f"{label}.assertion", max_bytes=768),
328
+ "quote": clean_text(preference.get("quote"), f"{label}.quote", max_bytes=768),
329
+ "source_ref": optional_text(preference.get("source_ref"), f"{label}.source_ref", max_bytes=240),
330
+ "source": source,
331
+ "confidence": choice(preference.get("confidence"), CONFIDENCE_LEVELS, f"{label}.confidence"),
332
+ "importance": choice(preference.get("importance"), IMPORTANCE_LEVELS, f"{label}.importance"),
333
+ "status": status,
334
+ "reason": clean_text(preference.get("reason"), f"{label}.reason", max_bytes=480),
335
+ "conflicts_with": conflicts,
336
+ }
337
+
338
+
339
+ def normalize_transaction(value: object) -> dict[str, Any]:
340
+ transaction = as_mapping(value, "transaction")
341
+ require_known_keys(transaction, {"schema_version", "transaction_id", "expected_state_revision", "operations"}, "transaction")
342
+ require(transaction.get("schema_version") == INPUT_SCHEMA_VERSION, f"transaction.schema_version must be {INPUT_SCHEMA_VERSION}")
343
+ transaction_id = clean_text(transaction.get("transaction_id"), "transaction.transaction_id", max_bytes=128)
344
+ operations = as_list(transaction.get("operations"), "transaction.operations")
345
+ require(1 <= len(operations) <= 32, "transaction.operations must contain 1-32 operations")
346
+ normalized_operations: list[dict[str, Any]] = []
347
+ for index, raw_operation in enumerate(operations):
348
+ label = f"transaction.operations[{index}]"
349
+ operation = as_mapping(raw_operation, label)
350
+ action = operation.get("action")
351
+ if action == "remember":
352
+ require_known_keys(operation, {"action", "preference"}, label)
353
+ normalized_operations.append({"action": action, "preference": normalize_preference(operation.get("preference"), f"{label}.preference", allow_status=True)})
354
+ elif action == "decide":
355
+ require_known_keys(operation, {"action", "item_id", "decision", "quote", "reason"}, label)
356
+ normalized_operations.append({
357
+ "action": action,
358
+ "item_id": clean_id_list([operation.get("item_id")], f"{label}.item_id", maximum=1)[0],
359
+ "decision": choice(operation.get("decision"), ("activate", "reject"), f"{label}.decision"),
360
+ "quote": clean_text(operation.get("quote"), f"{label}.quote", max_bytes=768),
361
+ "reason": clean_text(operation.get("reason"), f"{label}.reason", max_bytes=480),
362
+ })
363
+ elif action == "replace":
364
+ require_known_keys(operation, {"action", "old_ids", "preference"}, label)
365
+ old_ids = clean_id_list(operation.get("old_ids"), f"{label}.old_ids")
366
+ require(bool(old_ids), f"{label}.old_ids must not be empty")
367
+ normalized_operations.append({"action": action, "old_ids": old_ids, "preference": normalize_preference(operation.get("preference"), f"{label}.preference", allow_status=False)})
368
+ elif action == "forget":
369
+ require_known_keys(operation, {"action", "item_id", "quote", "reason"}, label)
370
+ normalized_operations.append({
371
+ "action": action,
372
+ "item_id": clean_id_list([operation.get("item_id")], f"{label}.item_id", maximum=1)[0],
373
+ "quote": clean_text(operation.get("quote"), f"{label}.quote", max_bytes=768),
374
+ "reason": clean_text(operation.get("reason"), f"{label}.reason", max_bytes=480),
375
+ })
376
+ else:
377
+ raise AuthorMemoryError(f"{label}.action must be one of: remember, decide, replace, forget")
378
+ return {
379
+ "schema_version": INPUT_SCHEMA_VERSION,
380
+ "transaction_id": transaction_id,
381
+ "expected_state_revision": as_int(transaction.get("expected_state_revision"), "transaction.expected_state_revision"),
382
+ "operations": normalized_operations,
383
+ }
384
+
385
+
386
+ def normalize_record_event(value: object) -> dict[str, Any]:
387
+ event = as_mapping(value, "event")
388
+ require_known_keys(event, {"schema_version", "event_id", "operation"}, "event")
389
+ require(event.get("schema_version") == INPUT_SCHEMA_VERSION, f"event.schema_version must be {INPUT_SCHEMA_VERSION}")
390
+ event_id = clean_text(event.get("event_id"), "event.event_id", max_bytes=120)
391
+ normalized = normalize_transaction({
392
+ "schema_version": INPUT_SCHEMA_VERSION,
393
+ "transaction_id": f"record:{event_id}",
394
+ "expected_state_revision": 0,
395
+ "operations": [event.get("operation")],
396
+ })
397
+ return {"event_id": event_id, "operation": normalized["operations"][0]}
398
+
399
+
400
+ def transaction_digest(transaction: dict[str, Any]) -> str:
401
+ canonical = json.dumps(transaction, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
402
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
403
+
404
+
405
+ def fingerprint(preference: dict[str, Any]) -> str:
406
+ value = {
407
+ "kind": preference["kind"],
408
+ "scope": preference["scope"],
409
+ "assertion": preference["assertion"].casefold(),
410
+ }
411
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
412
+
413
+
414
+ def allocate_item(state: dict[str, Any], preference: dict[str, Any], revision: int) -> dict[str, Any]:
415
+ item_id = f"AP{state['next_item_number']:03d}"
416
+ state["next_item_number"] += 1
417
+ return {
418
+ "id": item_id,
419
+ "kind": preference["kind"],
420
+ "scope": copy.deepcopy(preference["scope"]),
421
+ "assertion": preference["assertion"],
422
+ "confidence": preference["confidence"],
423
+ "importance": preference["importance"],
424
+ "status": preference["status"],
425
+ "source": preference["source"],
426
+ "reason": preference["reason"],
427
+ "conflicts_with": list(preference["conflicts_with"]),
428
+ "confirmation_count": 1,
429
+ "evidence": [{"quote": preference["quote"], "source_ref": preference["source_ref"]}],
430
+ "created_revision": revision,
431
+ "updated_revision": revision,
432
+ "superseded_by": None,
433
+ }
434
+
435
+
436
+ def best_level(first: str, second: str) -> str:
437
+ return first if RANK[first] >= RANK[second] else second
438
+
439
+
440
+ def add_evidence(item: dict[str, Any], quote: str, source_ref: str | None) -> None:
441
+ evidence = {"quote": quote, "source_ref": source_ref}
442
+ if evidence not in item["evidence"]:
443
+ item["evidence"].append(evidence)
444
+
445
+
446
+ def require_item(state: dict[str, Any], item_id: str, label: str) -> dict[str, Any]:
447
+ require(item_id in state["items"], f"{label} references unknown item {item_id}")
448
+ return state["items"][item_id]
449
+
450
+
451
+ def apply_remember(state: dict[str, Any], preference: dict[str, Any], revision: int) -> str:
452
+ for conflict_id in preference["conflicts_with"]:
453
+ conflict = require_item(state, conflict_id, "remember")
454
+ require(conflict["status"] == "active", f"remember conflict {conflict_id} must be active")
455
+ preference_fingerprint = fingerprint(preference)
456
+ for item in state["items"].values():
457
+ if item["status"] not in {"active", "pending", "conflict"} or fingerprint(item) != preference_fingerprint:
458
+ continue
459
+ require(not (item["status"] == "conflict" and preference["status"] == "active"), f"conflict item {item['id']} must be resolved with replace or rejected")
460
+ require(not (item["status"] == "active" and preference["status"] == "conflict"), f"active item {item['id']} cannot be recategorized as its own conflict")
461
+ add_evidence(item, preference["quote"], preference["source_ref"])
462
+ item["confirmation_count"] += 1
463
+ item["confidence"] = best_level(item["confidence"], preference["confidence"])
464
+ item["importance"] = best_level(item["importance"], preference["importance"])
465
+ item["updated_revision"] = revision
466
+ item["reason"] = preference["reason"]
467
+ if item["status"] == "pending" and preference["status"] == "active":
468
+ item["status"] = "active"
469
+ elif item["status"] == "pending" and preference["status"] == "conflict":
470
+ item["status"] = "conflict"
471
+ item["conflicts_with"] = list(preference["conflicts_with"])
472
+ elif item["status"] == "conflict" and preference["status"] == "conflict":
473
+ item["conflicts_with"] = sorted(set(item["conflicts_with"]) | set(preference["conflicts_with"]))
474
+ return f"强化 {item['id']}:{item['assertion']}"
475
+ item = allocate_item(state, preference, revision)
476
+ state["items"][item["id"]] = item
477
+ return f"新增 {item['id']}({item['status']}):{item['assertion']}"
478
+
479
+
480
+ def apply_decide(state: dict[str, Any], operation: dict[str, Any], revision: int) -> str:
481
+ item = require_item(state, operation["item_id"], "decide")
482
+ require(item["status"] in {"pending", "conflict"}, f"decide requires pending/conflict item, got {item['status']}")
483
+ if operation["decision"] == "activate":
484
+ require(item["status"] == "pending" and not item["conflicts_with"], "conflict candidates must be activated with replace")
485
+ item["status"] = "active"
486
+ verb = "确认"
487
+ else:
488
+ item["status"] = "rejected"
489
+ verb = "拒绝"
490
+ add_evidence(item, operation["quote"], None)
491
+ item["reason"] = operation["reason"]
492
+ item["updated_revision"] = revision
493
+ return f"{verb} {item['id']}:{item['assertion']}"
494
+
495
+
496
+ def apply_replace(state: dict[str, Any], operation: dict[str, Any], revision: int) -> str:
497
+ old_items = [require_item(state, item_id, "replace") for item_id in operation["old_ids"]]
498
+ for item in old_items:
499
+ require(item["status"] in {"active", "conflict", "pending"}, f"replace target {item['id']} is already {item['status']}")
500
+ replacement = allocate_item(state, operation["preference"], revision)
501
+ replacement["status"] = "active"
502
+ replacement["conflicts_with"] = []
503
+ state["items"][replacement["id"]] = replacement
504
+ for item in old_items:
505
+ item["status"] = "superseded"
506
+ item["superseded_by"] = replacement["id"]
507
+ item["updated_revision"] = revision
508
+ old_ids = {item["id"] for item in old_items}
509
+ released = 0
510
+ for candidate in state["items"].values():
511
+ if candidate["status"] != "conflict":
512
+ continue
513
+ retained = [item_id for item_id in candidate["conflicts_with"] if item_id not in old_ids]
514
+ if retained == candidate["conflicts_with"]:
515
+ continue
516
+ candidate["conflicts_with"] = retained
517
+ candidate["updated_revision"] = revision
518
+ if not retained:
519
+ candidate["status"] = "pending"
520
+ released += 1
521
+ replaced = ", ".join(item["id"] for item in old_items)
522
+ suffix = f";{released} 个其他冲突候选退回待确认" if released else ""
523
+ return f"用 {replacement['id']} 替代 {replaced}:{replacement['assertion']}{suffix}"
524
+
525
+
526
+ def apply_forget(state: dict[str, Any], operation: dict[str, Any], revision: int) -> str:
527
+ item = require_item(state, operation["item_id"], "forget")
528
+ require(item["status"] in {"active", "pending", "conflict"}, f"forget target {item['id']} is already {item['status']}")
529
+ item["status"] = "superseded"
530
+ item["superseded_by"] = None
531
+ item["reason"] = operation["reason"]
532
+ item["updated_revision"] = revision
533
+ add_evidence(item, operation["quote"], None)
534
+ released = 0
535
+ for candidate in state["items"].values():
536
+ if candidate["status"] != "conflict" or item["id"] not in candidate["conflicts_with"]:
537
+ continue
538
+ candidate["conflicts_with"] = [conflict_id for conflict_id in candidate["conflicts_with"] if conflict_id != item["id"]]
539
+ candidate["updated_revision"] = revision
540
+ if not candidate["conflicts_with"]:
541
+ candidate["status"] = "pending"
542
+ released += 1
543
+ suffix = f";{released} 个冲突候选退回待确认" if released else ""
544
+ return f"忘记 {item['id']}:{item['assertion']}{suffix}"
545
+
546
+
547
+ def apply_transaction(state: dict[str, Any], transaction: dict[str, Any], digest: str) -> tuple[dict[str, Any], list[str]]:
548
+ applied = state["applied_transactions"].get(transaction["transaction_id"])
549
+ if applied is not None:
550
+ require(applied["digest"] == digest, "transaction_id was already used with different content")
551
+ return state, [f"事务已应用于修订 {applied['revision']},本次为幂等重放"]
552
+ require(transaction["expected_state_revision"] == state["state_revision"], f"stale state revision: expected {transaction['expected_state_revision']}, current {state['state_revision']}")
553
+ updated = copy.deepcopy(state)
554
+ revision = updated["state_revision"] + 1
555
+ summaries: list[str] = []
556
+ for operation in transaction["operations"]:
557
+ if operation["action"] == "remember":
558
+ summaries.append(apply_remember(updated, operation["preference"], revision))
559
+ elif operation["action"] == "decide":
560
+ summaries.append(apply_decide(updated, operation, revision))
561
+ elif operation["action"] == "replace":
562
+ summaries.append(apply_replace(updated, operation, revision))
563
+ else:
564
+ summaries.append(apply_forget(updated, operation, revision))
565
+ committed_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
566
+ updated["state_revision"] = revision
567
+ updated["journal"].append({
568
+ "revision": revision,
569
+ "transaction_id": transaction["transaction_id"],
570
+ "committed_at": committed_at,
571
+ "summaries": summaries,
572
+ })
573
+ item_ids = sorted(
574
+ (item_id for item_id, item in updated["items"].items() if item["updated_revision"] == revision),
575
+ key=lambda item_id: int(item_id[2:]),
576
+ )
577
+ require(bool(item_ids), "transaction did not update any author-memory item")
578
+ updated["applied_transactions"][transaction["transaction_id"]] = {
579
+ "revision": revision,
580
+ "digest": digest,
581
+ "item_ids": item_ids,
582
+ }
583
+ return validate_state(updated), summaries
584
+
585
+
586
+ def scope_label(scope: dict[str, str | None]) -> str:
587
+ if scope["level"] == "global":
588
+ return "全局"
589
+ labels = {"genre": "题材", "book": "本书", "workflow": "流程"}
590
+ return f"{labels[scope['level']]}:{scope['value']}"
591
+
592
+
593
+ def render_profile(state: dict[str, Any]) -> str:
594
+ lines = [
595
+ "# 作者画像",
596
+ "",
597
+ "<!-- 由 author_memory_commit.py 生成,请勿手改;修改请提交事务。 -->",
598
+ "",
599
+ f"> 状态修订:{state['state_revision']}。仅列出已确认偏好;当前明确要求、本书设定与硬性门禁优先。",
600
+ "",
601
+ ]
602
+ active = [item for item in state["items"].values() if item["status"] == "active"]
603
+ for kind in KINDS:
604
+ lines.extend([f"## {KIND_TITLES[kind]}", ""])
605
+ items = sorted((item for item in active if item["kind"] == kind), key=lambda item: int(item["id"][2:]))
606
+ if not items:
607
+ lines.extend(["- 暂无", ""])
608
+ continue
609
+ for item in items:
610
+ lines.append(f"- **{item['id']}**〔{scope_label(item['scope'])}|{item['confidence']}|确认 {item['confirmation_count']} 次〕{item['assertion']}")
611
+ lines.append("")
612
+ return "\n".join(lines).rstrip() + "\n"
613
+
614
+
615
+ def render_pending(state: dict[str, Any]) -> str:
616
+ lines = [
617
+ "# 待确认的作者习惯",
618
+ "",
619
+ "<!-- 由 author_memory_commit.py 生成,请勿手改;修改请提交事务。 -->",
620
+ "",
621
+ f"> 状态修订:{state['state_revision']}。待确认项不参与创作约束,也不应打断当前任务。",
622
+ "",
623
+ ]
624
+ items = sorted((item for item in state["items"].values() if item["status"] in {"pending", "conflict"}), key=lambda item: int(item["id"][2:]))
625
+ if not items:
626
+ lines.extend(["暂无待确认项。", ""])
627
+ for item in items:
628
+ lines.extend([
629
+ f"## {item['id']} · {'冲突' if item['status'] == 'conflict' else '待确认'}",
630
+ "",
631
+ f"- 候选习惯:{item['assertion']}",
632
+ f"- 范围:{scope_label(item['scope'])}",
633
+ f"- 原话:\u201c{item['evidence'][-1]['quote']}\u201d",
634
+ f"- 依据:{item['reason']}",
635
+ f"- 置信度 / 重要度:{item['confidence']} / {item['importance']}",
636
+ ])
637
+ if item["conflicts_with"]:
638
+ lines.append(f"- 冲突对象:{', '.join(item['conflicts_with'])}")
639
+ lines.append("")
640
+ return "\n".join(lines).rstrip() + "\n"
641
+
642
+
643
+ def render_journal(state: dict[str, Any]) -> str:
644
+ lines = [
645
+ "# 作者记忆变更记录",
646
+ "",
647
+ "<!-- 由 author_memory_commit.py 生成,请勿手改;最近记录在前。 -->",
648
+ "",
649
+ ]
650
+ if not state["journal"]:
651
+ lines.extend(["暂无变更。", ""])
652
+ for entry in reversed(state["journal"][-100:]):
653
+ lines.extend([f"## r{entry['revision']} · {entry['committed_at']}", "", f"- 事务:`{entry['transaction_id']}`"])
654
+ lines.extend(f"- {summary}" for summary in entry["summaries"])
655
+ lines.append("")
656
+ return "\n".join(lines).rstrip() + "\n"
657
+
658
+
659
+ def render_views(state: dict[str, Any]) -> dict[str, str]:
660
+ views = {
661
+ "作者画像.md": render_profile(state),
662
+ "待确认.md": render_pending(state),
663
+ "变更记录.md": render_journal(state),
664
+ }
665
+ limits = {"作者画像.md": PROFILE_MAX_BYTES, "待确认.md": PENDING_MAX_BYTES, "变更记录.md": JOURNAL_MAX_BYTES}
666
+ for name, payload in views.items():
667
+ require(len(payload.encode("utf-8")) <= limits[name], f"{name} exceeds {limits[name]} bytes; consolidate old memory first")
668
+ return views
669
+
670
+
671
+ def write_snapshot(workspace: Path, state: dict[str, Any]) -> None:
672
+ root = memory_root(workspace)
673
+ views = render_views(state)
674
+ state_payload = json_payload(state)
675
+ require(len(state_payload.encode("utf-8")) <= STATE_MAX_BYTES, f"_author-memory-state.json exceeds {STATE_MAX_BYTES} bytes")
676
+ for name, payload in views.items():
677
+ write_if_changed(root / name, payload)
678
+ # State is the authority and therefore the last commit point.
679
+ write_if_changed(state_path(workspace), state_payload)
680
+
681
+
682
+ def command_init(workspace: Path) -> dict[str, Any]:
683
+ require(workspace.exists() and workspace.is_dir(), f"workspace does not exist: {workspace}")
684
+ path = state_path(workspace)
685
+ if path.exists():
686
+ state = validate_state(read_json(path))
687
+ else:
688
+ state = empty_state()
689
+ write_snapshot(workspace, state)
690
+ return {"ok": True, "command": "init", "revision": state["state_revision"], "root": str(memory_root(workspace))}
691
+
692
+
693
+ def command_commit(workspace: Path, input_path: Path) -> dict[str, Any]:
694
+ require(state_path(workspace).exists(), "author memory is not initialized; run init first")
695
+ state = validate_state(read_json(state_path(workspace)))
696
+ transaction = normalize_transaction(read_json(input_path))
697
+ digest = transaction_digest(transaction)
698
+ updated, summaries = apply_transaction(state, transaction, digest)
699
+ replayed = updated is state
700
+ if not replayed:
701
+ write_snapshot(workspace, updated)
702
+ else:
703
+ # Repair missing or stale views during an idempotent retry.
704
+ write_snapshot(workspace, state)
705
+ return {
706
+ "ok": True,
707
+ "command": "commit",
708
+ "revision": updated["state_revision"],
709
+ "transaction_id": transaction["transaction_id"],
710
+ "replayed": replayed,
711
+ "item_ids": updated["applied_transactions"][transaction["transaction_id"]]["item_ids"],
712
+ "summaries": summaries,
713
+ }
714
+
715
+
716
+ def command_record(workspace: Path, input_path: Path) -> dict[str, Any]:
717
+ require(workspace.exists() and workspace.is_dir(), f"workspace does not exist: {workspace}")
718
+ event = normalize_record_event(read_json(input_path))
719
+ path = state_path(workspace)
720
+ state = validate_state(read_json(path)) if path.exists() else empty_state()
721
+ transaction_id = f"record:{event['event_id']}"
722
+ applied = state["applied_transactions"].get(transaction_id)
723
+ expected_revision = applied["revision"] - 1 if applied is not None else state["state_revision"]
724
+ transaction = {
725
+ "schema_version": INPUT_SCHEMA_VERSION,
726
+ "transaction_id": transaction_id,
727
+ "expected_state_revision": expected_revision,
728
+ "operations": [event["operation"]],
729
+ }
730
+ digest = transaction_digest(transaction)
731
+ updated, summaries = apply_transaction(state, transaction, digest)
732
+ replayed = updated is state
733
+ write_snapshot(workspace, updated)
734
+ record = updated["applied_transactions"][transaction_id]
735
+ item_ids = record["item_ids"]
736
+ receipt = f"Author Memory Receipt: r{record['revision']} · {', '.join(item_ids)}"
737
+ return {
738
+ "ok": True,
739
+ "command": "record",
740
+ "revision": updated["state_revision"],
741
+ "applied_revision": record["revision"],
742
+ "event_id": event["event_id"],
743
+ "replayed": replayed,
744
+ "item_ids": item_ids,
745
+ "receipt": receipt,
746
+ "summaries": summaries,
747
+ }
748
+
749
+
750
+ def same_scope_value(item_value: str | None, requested: str | None) -> bool:
751
+ return requested is not None and item_value is not None and item_value.casefold() == requested.casefold()
752
+
753
+
754
+ def command_query(
755
+ workspace: Path,
756
+ kinds: list[str] | None,
757
+ book: str | None,
758
+ genre: str | None,
759
+ workflow: str | None,
760
+ ) -> dict[str, Any]:
761
+ require(workspace.exists() and workspace.is_dir(), f"workspace does not exist: {workspace}")
762
+ path = state_path(workspace)
763
+ if not path.exists():
764
+ return {"ok": True, "command": "query", "initialized": False, "revision": 0, "items": [], "omitted": 0}
765
+ state = validate_state(read_json(path))
766
+ requested_kinds = set(kinds or KINDS)
767
+ requested_scopes = {
768
+ "book": optional_text(book, "query.book", max_bytes=180),
769
+ "genre": optional_text(genre, "query.genre", max_bytes=180),
770
+ "workflow": optional_text(workflow, "query.workflow", max_bytes=180),
771
+ }
772
+
773
+ def relevant(item: dict[str, Any]) -> bool:
774
+ if item["status"] != "active" or item["kind"] not in requested_kinds:
775
+ return False
776
+ level = item["scope"]["level"]
777
+ return level == "global" or same_scope_value(item["scope"]["value"], requested_scopes[level])
778
+
779
+ scope_rank = {"book": 0, "genre": 1, "workflow": 2, "global": 3}
780
+ candidates = sorted(
781
+ (item for item in state["items"].values() if relevant(item)),
782
+ key=lambda item: (
783
+ scope_rank[item["scope"]["level"]],
784
+ -RANK[item["importance"]],
785
+ -item["confirmation_count"],
786
+ int(item["id"][2:]),
787
+ ),
788
+ )
789
+ result: dict[str, Any] = {
790
+ "ok": True,
791
+ "command": "query",
792
+ "initialized": True,
793
+ "revision": state["state_revision"],
794
+ "items": [],
795
+ "omitted": len(candidates),
796
+ }
797
+ for item in candidates:
798
+ compact = {
799
+ "id": item["id"],
800
+ "kind": item["kind"],
801
+ "scope": item["scope"],
802
+ "assertion": item["assertion"],
803
+ }
804
+ result["items"].append(compact)
805
+ result["omitted"] = len(candidates) - len(result["items"])
806
+ payload = json.dumps(result, ensure_ascii=False, sort_keys=True) + "\n"
807
+ if len(payload.encode("utf-8")) > QUERY_MAX_BYTES:
808
+ result["items"].pop()
809
+ result["omitted"] += 1
810
+ break
811
+ require(len((json.dumps(result, ensure_ascii=False, sort_keys=True) + "\n").encode("utf-8")) <= QUERY_MAX_BYTES, "query result exceeds its fixed byte budget")
812
+ return result
813
+
814
+
815
+ def command_check(workspace: Path) -> dict[str, Any]:
816
+ path = state_path(workspace)
817
+ require(path.exists(), "author memory is not initialized")
818
+ state = validate_state(read_json(path))
819
+ views = render_views(state)
820
+ root = memory_root(workspace)
821
+ for name, expected in views.items():
822
+ view_path = root / name
823
+ require(view_path.exists(), f"missing derived view: {view_path}")
824
+ require(view_path.read_text(encoding="utf-8") == expected, f"derived view is stale or edited: {view_path}")
825
+ counts = {status: sum(1 for item in state["items"].values() if item["status"] == status) for status in STATUSES}
826
+ return {"ok": True, "command": "check", "revision": state["state_revision"], "counts": counts}
827
+
828
+
829
+ def build_parser() -> argparse.ArgumentParser:
830
+ parser = argparse.ArgumentParser(description=__doc__)
831
+ subparsers = parser.add_subparsers(dest="command", required=True)
832
+ for command in ("init", "check"):
833
+ child = subparsers.add_parser(command)
834
+ child.add_argument("--workspace", required=True, type=Path)
835
+ commit = subparsers.add_parser("commit")
836
+ commit.add_argument("--workspace", required=True, type=Path)
837
+ commit.add_argument("--input", required=True, type=Path)
838
+ record = subparsers.add_parser("record")
839
+ record.add_argument("--workspace", required=True, type=Path)
840
+ record.add_argument("--input", required=True, type=Path)
841
+ query = subparsers.add_parser("query")
842
+ query.add_argument("--workspace", required=True, type=Path)
843
+ query.add_argument("--kind", action="append", choices=KINDS)
844
+ query.add_argument("--book")
845
+ query.add_argument("--genre")
846
+ query.add_argument("--workflow")
847
+ return parser
848
+
849
+
850
+ def main() -> int:
851
+ args = build_parser().parse_args()
852
+ try:
853
+ if args.command == "init":
854
+ result = command_init(args.workspace)
855
+ elif args.command == "commit":
856
+ result = command_commit(args.workspace, args.input)
857
+ elif args.command == "record":
858
+ result = command_record(args.workspace, args.input)
859
+ elif args.command == "query":
860
+ result = command_query(args.workspace, args.kind, args.book, args.genre, args.workflow)
861
+ else:
862
+ result = command_check(args.workspace)
863
+ emit(result)
864
+ return 0
865
+ except AuthorMemoryError as exc:
866
+ emit({"ok": False, "error": str(exc)}, error=True)
867
+ return 2
868
+
869
+
870
+ if __name__ == "__main__":
871
+ raise SystemExit(main())