@zergai/ztc 0.4.0-beta.1 → 0.5.0-beta.1

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 (718) hide show
  1. package/README.md +398 -45
  2. package/RUST_THIRD_PARTY_LICENSES.txt +1080 -822
  3. package/THIRD_PARTY_NOTICES.md +273 -12
  4. package/bin/zmux-darwin-arm64 +0 -0
  5. package/bin/ztc-audio-darwin-arm64 +0 -0
  6. package/bin/ztc-capture-darwin-arm64 +0 -0
  7. package/bin/ztc-computer-darwin-arm64 +0 -0
  8. package/bin/ztc-llm-darwin-arm64 +0 -0
  9. package/bin/ztc-tts-darwin-arm64 +0 -0
  10. package/bin/ztc-tui-darwin-arm64 +0 -0
  11. package/bin/ztc-zlicky-overlay-darwin-arm64 +0 -0
  12. package/bin/zterm-darwin-arm64 +0 -0
  13. package/dist/App.js +1206 -209
  14. package/dist/agent/agent.d.ts +74 -8
  15. package/dist/agent/agent.js +1073 -184
  16. package/dist/agent/backends/account_rotation.d.ts +4 -0
  17. package/dist/agent/backends/account_rotation.js +8 -2
  18. package/dist/agent/backends/anthropic.d.ts +13 -0
  19. package/dist/agent/backends/anthropic.js +169 -28
  20. package/dist/agent/backends/claude_cli.js +18 -8
  21. package/dist/agent/backends/codex_app_server.d.ts +1 -0
  22. package/dist/agent/backends/codex_app_server.js +55 -3
  23. package/dist/agent/backends/codex_auth.d.ts +1 -0
  24. package/dist/agent/backends/codex_auth.js +67 -13
  25. package/dist/agent/backends/codex_buffered_recovery.d.ts +27 -0
  26. package/dist/agent/backends/codex_buffered_recovery.js +293 -0
  27. package/dist/agent/backends/gemini.js +3 -1
  28. package/dist/agent/backends/http_error.d.ts +26 -0
  29. package/dist/agent/backends/http_error.js +221 -0
  30. package/dist/agent/backends/index.d.ts +9 -2
  31. package/dist/agent/backends/index.js +22 -2
  32. package/dist/agent/backends/openai.d.ts +0 -6
  33. package/dist/agent/backends/openai.js +5 -2
  34. package/dist/agent/backends/openai_compatible.d.ts +5 -4
  35. package/dist/agent/backends/openai_compatible.js +26 -19
  36. package/dist/agent/backends/openai_responses.d.ts +8 -3
  37. package/dist/agent/backends/openai_responses.js +77 -33
  38. package/dist/agent/backends/provider_ids.d.ts +1 -0
  39. package/dist/agent/backends/provider_ids.js +4 -0
  40. package/dist/agent/backends/request_metrics.js +12 -2
  41. package/dist/agent/backends/types.d.ts +109 -6
  42. package/dist/agent/backends/types.js +5 -1
  43. package/dist/agent/backends/zrouter_stream.d.ts +6 -1
  44. package/dist/agent/backends/zrouter_stream.js +160 -42
  45. package/dist/agent/background_registry.d.ts +2 -0
  46. package/dist/agent/background_registry.js +1 -0
  47. package/dist/agent/claim_observation.d.ts +6 -0
  48. package/dist/agent/claim_observation.js +54 -0
  49. package/dist/agent/commands/accounts.js +46 -177
  50. package/dist/agent/commands/attention.d.ts +2 -0
  51. package/dist/agent/commands/attention.js +67 -0
  52. package/dist/agent/commands/auth.js +18 -2
  53. package/dist/agent/commands/board.d.ts +2 -0
  54. package/dist/agent/commands/board.js +169 -0
  55. package/dist/agent/commands/clipboard.js +50 -1
  56. package/dist/agent/commands/compact.js +21 -13
  57. package/dist/agent/commands/config.js +4 -1
  58. package/dist/agent/commands/context.js +6 -1
  59. package/dist/agent/commands/desktop.d.ts +2 -0
  60. package/dist/agent/commands/desktop.js +29 -0
  61. package/dist/agent/commands/effort.js +14 -6
  62. package/dist/agent/commands/environment.d.ts +3 -0
  63. package/dist/agent/commands/environment.js +109 -0
  64. package/dist/agent/commands/evidence.d.ts +2 -0
  65. package/dist/agent/commands/evidence.js +9 -0
  66. package/dist/agent/commands/fork.js +4 -3
  67. package/dist/agent/commands/goal.d.ts +33 -1
  68. package/dist/agent/commands/goal.js +174 -14
  69. package/dist/agent/commands/goal_exit.d.ts +36 -0
  70. package/dist/agent/commands/goal_exit.js +120 -0
  71. package/dist/agent/commands/help.js +3 -1
  72. package/dist/agent/commands/history.js +3 -1
  73. package/dist/agent/commands/inbox.d.ts +2 -0
  74. package/dist/agent/commands/inbox.js +148 -0
  75. package/dist/agent/commands/index.js +16 -1
  76. package/dist/agent/commands/input_mode.js +8 -6
  77. package/dist/agent/commands/job.d.ts +2 -0
  78. package/dist/agent/commands/job.js +93 -0
  79. package/dist/agent/commands/keybindings.js +4 -1
  80. package/dist/agent/commands/label.d.ts +2 -0
  81. package/dist/agent/commands/label.js +77 -0
  82. package/dist/agent/commands/layout.d.ts +2 -0
  83. package/dist/agent/commands/layout.js +20 -0
  84. package/dist/agent/commands/mirror.js +16 -1
  85. package/dist/agent/commands/model.js +12 -2
  86. package/dist/agent/commands/permissions.d.ts +3 -1
  87. package/dist/agent/commands/permissions.js +79 -89
  88. package/dist/agent/commands/plan.js +5 -15
  89. package/dist/agent/commands/profile.js +21 -2
  90. package/dist/agent/commands/provider_selection.js +20 -1
  91. package/dist/agent/commands/rename.js +1 -1
  92. package/dist/agent/commands/resources.d.ts +2 -0
  93. package/dist/agent/commands/resources.js +67 -0
  94. package/dist/agent/commands/rewind.d.ts +3 -0
  95. package/dist/agent/commands/rewind.js +16 -0
  96. package/dist/agent/commands/runbooks.d.ts +2 -0
  97. package/dist/agent/commands/runbooks.js +73 -0
  98. package/dist/agent/commands/runbooks_lazy.d.ts +2 -0
  99. package/dist/agent/commands/runbooks_lazy.js +8 -0
  100. package/dist/agent/commands/sessions.d.ts +1 -1
  101. package/dist/agent/commands/sessions.js +33 -5
  102. package/dist/agent/commands/settings.js +185 -39
  103. package/dist/agent/commands/setup.d.ts +2 -0
  104. package/dist/agent/commands/setup.js +78 -0
  105. package/dist/agent/commands/share.d.ts +2 -0
  106. package/dist/agent/commands/share.js +64 -0
  107. package/dist/agent/commands/status.js +14 -2
  108. package/dist/agent/commands/types.d.ts +99 -6
  109. package/dist/agent/commands/update.js +8 -0
  110. package/dist/agent/commands/usage.d.ts +2 -0
  111. package/dist/agent/commands/usage.js +8 -0
  112. package/dist/agent/factory.d.ts +11 -0
  113. package/dist/agent/factory.js +113 -88
  114. package/dist/agent/loop_policy.d.ts +6 -3
  115. package/dist/agent/loop_policy.js +12 -3
  116. package/dist/agent/measurement_guidance.d.ts +2 -0
  117. package/dist/agent/measurement_guidance.js +5 -0
  118. package/dist/agent/request_encoder.d.ts +8 -1
  119. package/dist/agent/request_encoder.js +95 -23
  120. package/dist/agent/runtime/benchmark_comparison.d.ts +30 -0
  121. package/dist/agent/runtime/benchmark_comparison.js +94 -0
  122. package/dist/agent/runtime/benchmark_contract.d.ts +48 -0
  123. package/dist/agent/runtime/benchmark_contract.js +90 -0
  124. package/dist/agent/runtime/checked_commands.d.ts +32 -0
  125. package/dist/agent/runtime/checked_commands.js +119 -0
  126. package/dist/agent/runtime/command_execution_policy.d.ts +26 -0
  127. package/dist/agent/runtime/command_execution_policy.js +91 -0
  128. package/dist/agent/runtime/command_jobs.d.ts +36 -18
  129. package/dist/agent/runtime/command_jobs.js +151 -13
  130. package/dist/agent/runtime/command_panes.d.ts +59 -0
  131. package/dist/agent/runtime/command_panes.js +398 -0
  132. package/dist/agent/runtime/command_wait.d.ts +19 -0
  133. package/dist/agent/runtime/command_wait.js +167 -0
  134. package/dist/agent/runtime/cpu_benchmark.d.ts +30 -0
  135. package/dist/agent/runtime/cpu_benchmark.js +126 -0
  136. package/dist/agent/runtime/delegated_evidence.d.ts +26 -0
  137. package/dist/agent/runtime/delegated_evidence.js +80 -0
  138. package/dist/agent/runtime/evidence.d.ts +127 -0
  139. package/dist/agent/runtime/evidence.js +468 -0
  140. package/dist/agent/runtime/execution_context.d.ts +7 -0
  141. package/dist/agent/runtime/execution_context.js +39 -3
  142. package/dist/agent/runtime/json_verifier_recipe.d.ts +8 -0
  143. package/dist/agent/runtime/json_verifier_recipe.js +66 -0
  144. package/dist/agent/runtime/measurements.d.ts +110 -0
  145. package/dist/agent/runtime/measurements.js +317 -0
  146. package/dist/agent/runtime/policy.d.ts +4 -0
  147. package/dist/agent/runtime/policy.js +31 -20
  148. package/dist/agent/runtime/provider_native_evidence.d.ts +20 -0
  149. package/dist/agent/runtime/provider_native_evidence.js +86 -0
  150. package/dist/agent/runtime/recovery.d.ts +2 -0
  151. package/dist/agent/runtime/recovery.js +45 -2
  152. package/dist/agent/runtime/remote_broker_transport.d.ts +10 -0
  153. package/dist/agent/runtime/remote_broker_transport.js +84 -0
  154. package/dist/agent/runtime/remote_deletion_receipts.d.ts +3 -0
  155. package/dist/agent/runtime/remote_deletion_receipts.js +43 -0
  156. package/dist/agent/runtime/remote_journal_replay.d.ts +13 -0
  157. package/dist/agent/runtime/remote_journal_replay.js +233 -0
  158. package/dist/agent/runtime/remote_mutation_journal.d.ts +25 -0
  159. package/dist/agent/runtime/remote_mutation_journal.js +208 -0
  160. package/dist/agent/runtime/remote_resource_endpoint.d.ts +7 -0
  161. package/dist/agent/runtime/remote_resource_endpoint.js +6 -0
  162. package/dist/agent/runtime/remote_resource_errors.d.ts +5 -0
  163. package/dist/agent/runtime/remote_resource_errors.js +9 -0
  164. package/dist/agent/runtime/remote_resource_script.d.ts +2 -0
  165. package/dist/agent/runtime/remote_resource_script.js +1009 -0
  166. package/dist/agent/runtime/remote_resources.d.ts +29 -0
  167. package/dist/agent/runtime/remote_resources.js +160 -0
  168. package/dist/agent/runtime/source_verification.d.ts +12 -0
  169. package/dist/agent/runtime/source_verification.js +210 -0
  170. package/dist/agent/runtime/source_verification_contract.d.ts +75 -0
  171. package/dist/agent/runtime/source_verification_contract.js +203 -0
  172. package/dist/agent/runtime/tool_checkpoints.d.ts +11 -0
  173. package/dist/agent/runtime/tool_checkpoints.js +26 -0
  174. package/dist/agent/runtime/tool_effects.d.ts +5 -0
  175. package/dist/agent/runtime/tool_progress.d.ts +12 -0
  176. package/dist/agent/runtime/tool_progress.js +76 -0
  177. package/dist/agent/runtime/tool_runtime.d.ts +16 -1
  178. package/dist/agent/runtime/tool_runtime.js +204 -10
  179. package/dist/agent/runtime/tracing.d.ts +1 -1
  180. package/dist/agent/runtime/verifier_capture.d.ts +9 -0
  181. package/dist/agent/runtime/verifier_capture.js +100 -0
  182. package/dist/agent/runtime/verifier_contract.d.ts +24 -0
  183. package/dist/agent/runtime/verifier_contract.js +41 -0
  184. package/dist/agent/subagent.d.ts +20 -10
  185. package/dist/agent/subagent.js +266 -29
  186. package/dist/agent/tool_response_directory.d.ts +24 -0
  187. package/dist/agent/tool_response_directory.js +61 -0
  188. package/dist/agent/tool_response_source.d.ts +8 -0
  189. package/dist/agent/tool_response_source.js +49 -0
  190. package/dist/agent/tool_response_store.d.ts +75 -4
  191. package/dist/agent/tool_response_store.js +583 -64
  192. package/dist/agent/tools/ask_user.d.ts +3 -1
  193. package/dist/agent/tools/ask_user.js +30 -11
  194. package/dist/agent/tools/background.js +1 -0
  195. package/dist/agent/tools/benchmark_cpu.d.ts +2 -0
  196. package/dist/agent/tools/benchmark_cpu.js +102 -0
  197. package/dist/agent/tools/compare_benchmarks.d.ts +2 -0
  198. package/dist/agent/tools/compare_benchmarks.js +53 -0
  199. package/dist/agent/tools/deferred.js +1 -0
  200. package/dist/agent/tools/delegate.js +18 -2
  201. package/dist/agent/tools/helper_requirements.d.ts +7 -0
  202. package/dist/agent/tools/helper_requirements.js +19 -0
  203. package/dist/agent/tools/index.d.ts +1 -0
  204. package/dist/agent/tools/index.js +3 -0
  205. package/dist/agent/tools/measurement_report.d.ts +22 -0
  206. package/dist/agent/tools/measurement_report.js +190 -0
  207. package/dist/agent/tools/pane.d.ts +0 -7
  208. package/dist/agent/tools/pane.js +5 -4
  209. package/dist/agent/tools/project_context.d.ts +3 -0
  210. package/dist/agent/tools/project_context.js +45 -0
  211. package/dist/agent/tools/recall_tool_response.d.ts +3 -5
  212. package/dist/agent/tools/recall_tool_response.js +19 -29
  213. package/dist/agent/tools/registry.d.ts +1 -0
  214. package/dist/agent/tools/registry.js +23 -0
  215. package/dist/agent/tools/related_sessions.d.ts +2 -0
  216. package/dist/agent/tools/related_sessions.js +156 -0
  217. package/dist/agent/tools/routine.js +13 -3
  218. package/dist/agent/tools/session_evidence.d.ts +3 -0
  219. package/dist/agent/tools/session_evidence.js +72 -0
  220. package/dist/agent/tools/shell.d.ts +4 -3
  221. package/dist/agent/tools/shell.js +174 -47
  222. package/dist/agent/tools/tool_search.js +3 -2
  223. package/dist/agent/tools/types.d.ts +28 -0
  224. package/dist/agent/tools/verify_artifact.d.ts +2 -0
  225. package/dist/agent/tools/verify_artifact.js +60 -0
  226. package/dist/agent/tools/workflow.js +1 -0
  227. package/dist/app/activity.d.ts +6 -1
  228. package/dist/app/activity.js +81 -12
  229. package/dist/app/agent_runner.d.ts +6 -1
  230. package/dist/app/agent_runner.js +34 -19
  231. package/dist/app/command_context.js +106 -10
  232. package/dist/app/controller.d.ts +15 -4
  233. package/dist/app/controller.js +29 -3
  234. package/dist/app/escape_stop.d.ts +11 -0
  235. package/dist/app/escape_stop.js +15 -0
  236. package/dist/app/liveness.d.ts +6 -4
  237. package/dist/app/liveness.js +13 -3
  238. package/dist/app/model_catalog_cache.d.ts +5 -0
  239. package/dist/app/model_catalog_cache.js +138 -0
  240. package/dist/app/ordered_transcript.js +43 -4
  241. package/dist/app/prompt_turn.d.ts +14 -0
  242. package/dist/app/prompt_turn.js +53 -0
  243. package/dist/app/recap.d.ts +3 -0
  244. package/dist/app/recap.js +9 -3
  245. package/dist/app/restart.d.ts +3 -2
  246. package/dist/app/restart.js +22 -7
  247. package/dist/app/rewind.d.ts +3 -3
  248. package/dist/app/rewind.js +3 -3
  249. package/dist/app/selection_completion.d.ts +17 -2
  250. package/dist/app/selection_completion.js +84 -9
  251. package/dist/app/session_manager.d.ts +38 -6
  252. package/dist/app/session_manager.js +263 -60
  253. package/dist/app/session_messages.d.ts +3 -0
  254. package/dist/app/session_messages.js +60 -0
  255. package/dist/app/task_scope_router.d.ts +20 -0
  256. package/dist/app/task_scope_router.js +173 -0
  257. package/dist/app/transcript_window.d.ts +2 -0
  258. package/dist/app/transcript_window.js +4 -0
  259. package/dist/app/workspace_admission_details.d.ts +3 -0
  260. package/dist/app/workspace_admission_details.js +26 -0
  261. package/dist/app/workspace_layout_controller.d.ts +11 -0
  262. package/dist/app/workspace_layout_controller.js +88 -0
  263. package/dist/app/workspace_monitor.d.ts +1 -0
  264. package/dist/app/workspace_monitor.js +216 -0
  265. package/dist/app/workspace_presets.d.ts +29 -0
  266. package/dist/app/workspace_presets.js +192 -0
  267. package/dist/attention/queue.d.ts +37 -0
  268. package/dist/attention/queue.js +183 -0
  269. package/dist/bench/rf_shared.d.ts +2 -0
  270. package/dist/board/binding.d.ts +42 -0
  271. package/dist/board/binding.js +38 -0
  272. package/dist/board/client.d.ts +42 -0
  273. package/dist/board/client.js +60 -0
  274. package/dist/cli.js +1 -1
  275. package/dist/cli_args.js +19 -17
  276. package/dist/cli_main.js +110 -13
  277. package/dist/cli_ratatui.d.ts +183 -16
  278. package/dist/cli_ratatui.js +3989 -1255
  279. package/dist/components/ActivityLine.d.ts +3 -2
  280. package/dist/components/ActivityLine.js +2 -2
  281. package/dist/components/InputArea.d.ts +19 -1
  282. package/dist/components/InputArea.js +264 -190
  283. package/dist/components/MessageList.d.ts +2 -0
  284. package/dist/components/MessageList.js +3 -1
  285. package/dist/components/SingleMessage.d.ts +2 -0
  286. package/dist/components/SingleMessage.js +4 -2
  287. package/dist/components/StatusBar.d.ts +4 -2
  288. package/dist/components/StatusBar.js +3 -1
  289. package/dist/conductor_branch.js +3 -0
  290. package/dist/config/api_retry.d.ts +6 -1
  291. package/dist/config/api_retry.js +19 -1
  292. package/dist/config/defaults.d.ts +2 -1
  293. package/dist/config/defaults.js +9 -2
  294. package/dist/config/message_display.d.ts +1 -0
  295. package/dist/config/message_display.js +17 -2
  296. package/dist/config/permissions.d.ts +21 -0
  297. package/dist/config/permissions.js +89 -0
  298. package/dist/config/resolved.d.ts +2 -2
  299. package/dist/config/types.d.ts +32 -5
  300. package/dist/config.d.ts +38 -4
  301. package/dist/config.js +290 -42
  302. package/dist/context/project_intelligence.d.ts +44 -0
  303. package/dist/context/project_intelligence.js +246 -0
  304. package/dist/desktop/cli_launch.d.ts +8 -0
  305. package/dist/desktop/cli_launch.js +6 -0
  306. package/dist/desktop/cli_shim.d.ts +8 -0
  307. package/dist/desktop/cli_shim.js +120 -0
  308. package/dist/desktop/runtime.d.ts +16 -0
  309. package/dist/desktop/runtime.js +161 -0
  310. package/dist/desktop/worker_launch.d.ts +7 -0
  311. package/dist/desktop/worker_launch.js +7 -0
  312. package/dist/diagnostics/cargo_mutants_selection.d.ts +27 -0
  313. package/dist/diagnostics/cargo_mutants_selection.js +48 -0
  314. package/dist/diagnostics/native_terminal_benchmark.d.ts +58 -0
  315. package/dist/diagnostics/native_terminal_benchmark.js +1247 -0
  316. package/dist/diagnostics/session_evidence_package.d.ts +40 -0
  317. package/dist/diagnostics/session_evidence_package.js +234 -0
  318. package/dist/diagnostics/session_export.d.ts +93 -0
  319. package/dist/diagnostics/session_export.js +634 -0
  320. package/dist/emulation/tool_adapters.js +48 -18
  321. package/dist/emulation/ztc_addendum.d.ts +1 -0
  322. package/dist/emulation/ztc_addendum.js +13 -12
  323. package/dist/environment/service_runner.d.ts +1 -0
  324. package/dist/environment/service_runner.js +68 -0
  325. package/dist/environment/store.d.ts +120 -0
  326. package/dist/environment/store.js +387 -0
  327. package/dist/events.d.ts +40 -1
  328. package/dist/events.js +10 -17
  329. package/dist/goal_contract.d.ts +25 -0
  330. package/dist/goal_contract.js +44 -0
  331. package/dist/headless.d.ts +31 -0
  332. package/dist/headless.js +578 -70
  333. package/dist/headless_cli.js +8 -0
  334. package/dist/headless_cli_args.d.ts +1 -0
  335. package/dist/headless_cli_args.js +1 -0
  336. package/dist/intake/cli.d.ts +1 -0
  337. package/dist/intake/cli.js +33 -0
  338. package/dist/intake/format.d.ts +2 -0
  339. package/dist/intake/format.js +14 -0
  340. package/dist/intake/notifications.d.ts +16 -0
  341. package/dist/intake/notifications.js +132 -0
  342. package/dist/intake/store.d.ts +56 -0
  343. package/dist/intake/store.js +238 -0
  344. package/dist/library.d.ts +8 -0
  345. package/dist/library.js +19 -10
  346. package/dist/mcp/client.d.ts +1 -0
  347. package/dist/mcp/client.js +20 -0
  348. package/dist/modes/builtin/plan.yaml +2 -2
  349. package/dist/modes/handlers.js +1 -1
  350. package/dist/onboarding/first_run.d.ts +3 -0
  351. package/dist/onboarding/first_run.js +33 -25
  352. package/dist/onboarding/setup.d.ts +32 -0
  353. package/dist/onboarding/setup.js +133 -0
  354. package/dist/onboarding/setup_agent_health.d.ts +17 -0
  355. package/dist/onboarding/setup_agent_health.js +79 -0
  356. package/dist/onboarding/setup_environment.d.ts +66 -0
  357. package/dist/onboarding/setup_environment.js +219 -0
  358. package/dist/onboarding/setup_workspace.d.ts +17 -0
  359. package/dist/onboarding/setup_workspace.js +129 -0
  360. package/dist/optimize/adapters/index.d.ts +4 -1
  361. package/dist/optimize/adapters/index.js +7 -0
  362. package/dist/optimize/adapters/kernelbench.js +14 -5
  363. package/dist/optimize/adapters/popcorn.js +3 -2
  364. package/dist/optimize/adapters/profile_benchmark.js +13 -7
  365. package/dist/optimize/adapters/rfbench.js +25 -14
  366. package/dist/optimize/adapters/types.d.ts +3 -0
  367. package/dist/optimize/adapters/zergpod.js +5 -2
  368. package/dist/optimize/baseline.js +10 -21
  369. package/dist/optimize/branch.js +9 -12
  370. package/dist/optimize/combine.js +2 -3
  371. package/dist/optimize/executor.js +34 -48
  372. package/dist/optimize/measurements.d.ts +55 -0
  373. package/dist/optimize/measurements.js +173 -0
  374. package/dist/optimize/results.d.ts +1 -0
  375. package/dist/optimize/results.js +11 -33
  376. package/dist/optimize/tge.js +2 -1
  377. package/dist/panes/initial_input.d.ts +19 -0
  378. package/dist/panes/initial_input.js +206 -0
  379. package/dist/panes/labels.d.ts +16 -0
  380. package/dist/panes/labels.js +42 -0
  381. package/dist/panes/model_catalog.d.ts +3 -3
  382. package/dist/panes/model_catalog.js +28 -4
  383. package/dist/panes/pane_registry.js +6 -2
  384. package/dist/panes/types.d.ts +3 -0
  385. package/dist/panes/ztc_launch.js +19 -0
  386. package/dist/plugin/optimization.d.ts +2 -0
  387. package/dist/plugin/optimization.js +1 -0
  388. package/dist/plugin/runtime.d.ts +2 -0
  389. package/dist/plugin/simulation.d.ts +6 -1
  390. package/dist/plugin/simulation_contract.d.ts +836 -1
  391. package/dist/plugin/simulation_documents.d.ts +22 -0
  392. package/dist/plugin/simulation_documents.js +1 -0
  393. package/dist/plugin/simulation_interventions.d.ts +103 -0
  394. package/dist/plugin/simulation_interventions.js +1 -0
  395. package/dist/plugin/simulation_living.d.ts +1 -0
  396. package/dist/plugin/simulation_living.js +3 -0
  397. package/dist/plugin/simulation_meetings.d.ts +121 -0
  398. package/dist/plugin/simulation_meetings.js +1 -0
  399. package/dist/plugin/simulation_story_review.d.ts +111 -0
  400. package/dist/plugin/simulation_story_review.js +1 -0
  401. package/dist/plugin/simulation_storyteller.d.ts +91 -0
  402. package/dist/plugin/simulation_storyteller.js +1 -0
  403. package/dist/plugin/simulation_structured.d.ts +2 -0
  404. package/dist/plugin/simulation_structured.js +2 -0
  405. package/dist/plugin/simulation_toolkit.d.ts +21 -0
  406. package/dist/plugin/simulation_toolkit.js +24 -0
  407. package/dist/prompts/tool_delegate_task.j2 +1 -1
  408. package/dist/remote-broker/Dockerfile +10 -0
  409. package/dist/remote-broker/archive.py +1227 -0
  410. package/dist/remote-broker/cutover.py +761 -0
  411. package/dist/remote-broker/requirements.txt +5 -0
  412. package/dist/remote-broker/resources.json +6 -0
  413. package/dist/remote-broker/resources.write-staging.example.json +18 -0
  414. package/dist/remote-broker/retained.py +686 -0
  415. package/dist/remote-broker/retained_cleanup.py +550 -0
  416. package/dist/remote-broker/server.py +648 -0
  417. package/dist/remote-broker/worker.py +1007 -0
  418. package/dist/router_auth.d.ts +31 -0
  419. package/dist/router_auth.js +155 -9
  420. package/dist/runbooks/catalog.d.ts +3 -0
  421. package/dist/runbooks/catalog.js +26 -0
  422. package/dist/runbooks/library.d.ts +11 -0
  423. package/dist/runbooks/library.js +95 -0
  424. package/dist/runbooks/package.d.ts +43 -0
  425. package/dist/runbooks/package.js +102 -0
  426. package/dist/session.d.ts +65 -13
  427. package/dist/session.js +548 -43
  428. package/dist/session_handoff.d.ts +25 -0
  429. package/dist/session_handoff.js +322 -0
  430. package/dist/session_handoff_contract.d.ts +89 -0
  431. package/dist/session_handoff_contract.js +179 -0
  432. package/dist/session_media.d.ts +41 -0
  433. package/dist/session_media.js +357 -0
  434. package/dist/session_ownership.d.ts +16 -0
  435. package/dist/session_ownership.js +221 -0
  436. package/dist/session_public.d.ts +10 -2
  437. package/dist/session_public.js +6 -1
  438. package/dist/simulation/dynamic_history.d.ts +42 -0
  439. package/dist/simulation/dynamic_history.js +173 -0
  440. package/dist/simulation/engines/swarm/pane_manager.js +7 -6
  441. package/dist/simulation/inference.d.ts +3 -1
  442. package/dist/simulation/inference.js +19 -1
  443. package/dist/simulation/intervention_generation.d.ts +27 -0
  444. package/dist/simulation/intervention_generation.js +246 -0
  445. package/dist/simulation/intervention_material.d.ts +4 -0
  446. package/dist/simulation/intervention_material.js +81 -0
  447. package/dist/simulation/living/context.d.ts +3130 -0
  448. package/dist/simulation/living/context.js +944 -0
  449. package/dist/simulation/living/definer.d.ts +12 -0
  450. package/dist/simulation/living/definer.js +223 -0
  451. package/dist/simulation/living/definition.d.ts +257 -0
  452. package/dist/simulation/living/definition.js +341 -0
  453. package/dist/simulation/living/frame.d.ts +259 -0
  454. package/dist/simulation/living/frame.js +223 -0
  455. package/dist/simulation/living/identifiers.d.ts +2 -0
  456. package/dist/simulation/living/identifiers.js +12 -0
  457. package/dist/simulation/living/index.d.ts +15 -0
  458. package/dist/simulation/living/index.js +15 -0
  459. package/dist/simulation/living/inference.d.ts +219 -0
  460. package/dist/simulation/living/inference.js +576 -0
  461. package/dist/simulation/living/mechanics.d.ts +54 -0
  462. package/dist/simulation/living/mechanics.js +588 -0
  463. package/dist/simulation/living/model-input.d.ts +25 -0
  464. package/dist/simulation/living/model-input.js +215 -0
  465. package/dist/simulation/living/open-world.d.ts +257 -0
  466. package/dist/simulation/living/open-world.js +102 -0
  467. package/dist/simulation/living/projection.d.ts +7 -0
  468. package/dist/simulation/living/projection.js +31 -0
  469. package/dist/simulation/living/recall.d.ts +17 -0
  470. package/dist/simulation/living/recall.js +25 -0
  471. package/dist/simulation/living/reduce.d.ts +15 -0
  472. package/dist/simulation/living/reduce.js +1853 -0
  473. package/dist/simulation/living/replay.d.ts +6 -0
  474. package/dist/simulation/living/replay.js +22 -0
  475. package/dist/simulation/living/runtime.d.ts +140 -0
  476. package/dist/simulation/living/runtime.js +3020 -0
  477. package/dist/simulation/living/shared-kinds.d.ts +24 -0
  478. package/dist/simulation/living/shared-kinds.js +96 -0
  479. package/dist/simulation/living/types.d.ts +2785 -0
  480. package/dist/simulation/living/types.js +669 -0
  481. package/dist/simulation/llm.d.ts +3 -1
  482. package/dist/simulation/llm.js +90 -30
  483. package/dist/simulation/memory/embedding.d.ts +1 -1
  484. package/dist/simulation/memory/embedding.js +9 -3
  485. package/dist/simulation/memory/filesystem.d.ts +2 -0
  486. package/dist/simulation/memory/filesystem.js +5 -1
  487. package/dist/simulation/memory/filesystem_file_tree.d.ts +4 -1
  488. package/dist/simulation/memory/filesystem_file_tree.js +41 -10
  489. package/dist/simulation/memory/filesystem_invariants.js +1 -2
  490. package/dist/simulation/memory/filesystem_types.d.ts +1 -0
  491. package/dist/simulation/memory/memory.d.ts +2 -0
  492. package/dist/simulation/memory/memory.js +5 -1
  493. package/dist/simulation/orchestration/intent.js +0 -2
  494. package/dist/simulation/orchestration/lifecycle.js +0 -2
  495. package/dist/simulation/plugin_host.d.ts +25 -1
  496. package/dist/simulation/plugin_host.js +334 -17
  497. package/dist/simulation/session_documents.d.ts +20 -0
  498. package/dist/simulation/session_documents.js +62 -0
  499. package/dist/simulation/session_input_validation.d.ts +43 -0
  500. package/dist/simulation/session_input_validation.js +364 -0
  501. package/dist/simulation/session_inputs.d.ts +32 -0
  502. package/dist/simulation/session_inputs.js +154 -0
  503. package/dist/simulation/telemetry.d.ts +11 -14
  504. package/dist/simulation/telemetry.js +177 -54
  505. package/dist/simulation/toolkit/bounded_turns.d.ts +13 -0
  506. package/dist/simulation/toolkit/bounded_turns.js +80 -0
  507. package/dist/simulation/toolkit/dynamic_agents.d.ts +25 -0
  508. package/dist/simulation/toolkit/dynamic_agents.js +218 -0
  509. package/dist/simulation/toolkit/dynamic_digest.d.ts +1 -0
  510. package/dist/simulation/toolkit/dynamic_digest.js +8 -0
  511. package/dist/simulation/toolkit/dynamic_documents.d.ts +7 -0
  512. package/dist/simulation/toolkit/dynamic_documents.js +71 -0
  513. package/dist/simulation/toolkit/dynamic_driver.d.ts +8 -0
  514. package/dist/simulation/toolkit/dynamic_driver.js +269 -0
  515. package/dist/simulation/toolkit/dynamic_game.d.ts +53 -0
  516. package/dist/simulation/toolkit/dynamic_game.js +805 -0
  517. package/dist/simulation/toolkit/dynamic_knowledge.d.ts +15 -0
  518. package/dist/simulation/toolkit/dynamic_knowledge.js +91 -0
  519. package/dist/simulation/toolkit/dynamic_mechanics.d.ts +22 -0
  520. package/dist/simulation/toolkit/dynamic_mechanics.js +910 -0
  521. package/dist/simulation/toolkit/dynamic_meetings.d.ts +239 -0
  522. package/dist/simulation/toolkit/dynamic_meetings.js +350 -0
  523. package/dist/simulation/toolkit/dynamic_progress.d.ts +131 -0
  524. package/dist/simulation/toolkit/dynamic_progress.js +214 -0
  525. package/dist/simulation/toolkit/dynamic_projection.d.ts +9 -0
  526. package/dist/simulation/toolkit/dynamic_projection.js +219 -0
  527. package/dist/simulation/toolkit/dynamic_runtime.d.ts +412 -0
  528. package/dist/simulation/toolkit/dynamic_runtime.js +6536 -0
  529. package/dist/simulation/toolkit/dynamic_state.d.ts +111 -0
  530. package/dist/simulation/toolkit/dynamic_state.js +1967 -0
  531. package/dist/simulation/toolkit/dynamic_story_review.d.ts +508 -0
  532. package/dist/simulation/toolkit/dynamic_story_review.js +333 -0
  533. package/dist/simulation/toolkit/dynamic_storyteller.d.ts +77 -0
  534. package/dist/simulation/toolkit/dynamic_storyteller.js +114 -0
  535. package/dist/simulation/toolkit/dynamic_storyteller_runtime.d.ts +26 -0
  536. package/dist/simulation/toolkit/dynamic_storyteller_runtime.js +126 -0
  537. package/dist/simulation/toolkit/dynamic_world.d.ts +22 -0
  538. package/dist/simulation/toolkit/dynamic_world.js +377 -0
  539. package/dist/simulation/toolkit/structured_output.d.ts +5 -0
  540. package/dist/simulation/toolkit/structured_output.js +321 -0
  541. package/dist/simulation/types/world.d.ts +2 -0
  542. package/dist/simulation/world/artifact_store.js +1 -1
  543. package/dist/simulation/world/memory_manager.d.ts +5 -0
  544. package/dist/simulation/world/memory_manager.js +17 -2
  545. package/dist/simulation/world/state.d.ts +3 -2
  546. package/dist/simulation/world/state.js +15 -5
  547. package/dist/skills/bundled/measurement-validation/SKILL.md +144 -0
  548. package/dist/terminal_attach.d.ts +1 -0
  549. package/dist/terminal_attach.js +113 -0
  550. package/dist/tool_progress.d.ts +3 -0
  551. package/dist/tool_progress.js +27 -0
  552. package/dist/types.d.ts +145 -10
  553. package/dist/types.js +3 -0
  554. package/dist/ui/core/input.d.ts +3 -0
  555. package/dist/ui/core/input_segments.d.ts +18 -1
  556. package/dist/ui/core/input_segments.js +131 -47
  557. package/dist/ui/core/input_state.d.ts +12 -0
  558. package/dist/ui/core/layout_yoga.d.ts +1 -1
  559. package/dist/ui/core/turn_metadata.d.ts +5 -0
  560. package/dist/ui/core/turn_metadata.js +22 -0
  561. package/dist/ui/ink/render.d.ts +2 -1
  562. package/dist/ui/ink/render.js +6 -5
  563. package/dist/ui/ratatui/headless_pane_manager.d.ts +14 -1
  564. package/dist/ui/ratatui/headless_pane_manager.js +293 -104
  565. package/dist/ui/ratatui/index.d.ts +1 -0
  566. package/dist/ui/ratatui/input.d.ts +4 -0
  567. package/dist/ui/ratatui/input.js +15 -0
  568. package/dist/ui/ratatui/ipc_path.d.ts +2 -0
  569. package/dist/ui/ratatui/ipc_path.js +29 -1
  570. package/dist/ui/ratatui/mux_persistence.d.ts +3 -1
  571. package/dist/ui/ratatui/mux_persistence.js +139 -1
  572. package/dist/ui/ratatui/pane_relay.d.ts +1 -1
  573. package/dist/ui/ratatui/pane_relay.js +55 -27
  574. package/dist/ui/ratatui/process.d.ts +17 -1
  575. package/dist/ui/ratatui/process.js +80 -7
  576. package/dist/ui/ratatui/protocol.d.ts +236 -1
  577. package/dist/ui/ratatui/protocol.js +90 -0
  578. package/dist/ui/scrollback.d.ts +2 -1
  579. package/dist/ui/scrollback.js +9 -4
  580. package/dist/ui/stream_typewriter.d.ts +8 -3
  581. package/dist/ui/stream_typewriter.js +30 -1
  582. package/dist/ui/streaming_scrollback.d.ts +1 -0
  583. package/dist/ui/streaming_scrollback.js +1 -1
  584. package/dist/ui/transcript_render_cache.js +10 -0
  585. package/dist/ui/views/activity_line.d.ts +5 -3
  586. package/dist/ui/views/activity_line.js +65 -7
  587. package/dist/ui/views/app.d.ts +6 -3
  588. package/dist/ui/views/app.js +17 -6
  589. package/dist/ui/views/completion_menu.js +10 -5
  590. package/dist/ui/views/input_area.d.ts +7 -3
  591. package/dist/ui/views/input_area.js +15 -9
  592. package/dist/ui/views/message_list.d.ts +4 -1
  593. package/dist/ui/views/message_list.js +89 -19
  594. package/dist/ui/views/queue_panel.d.ts +3 -1
  595. package/dist/ui/views/queue_panel.js +9 -2
  596. package/dist/ui/views/status_bar.d.ts +4 -2
  597. package/dist/ui/views/status_bar.js +28 -13
  598. package/dist/ui/views/theme.d.ts +2 -0
  599. package/dist/ui/views/theme.js +2 -0
  600. package/dist/ui/widgets/color_panel.js +18 -0
  601. package/dist/ui/widgets/form.js +8 -0
  602. package/dist/ui/widgets/log_view.js +7 -0
  603. package/dist/ui/widgets/navigator_panel.js +8 -0
  604. package/dist/ui/widgets/prompt_viewer.js +2 -0
  605. package/dist/ui/widgets/questionnaire.d.ts +2 -0
  606. package/dist/ui/widgets/questionnaire.js +79 -16
  607. package/dist/ui/widgets/resume_panel.d.ts +2 -0
  608. package/dist/ui/widgets/resume_panel.js +26 -15
  609. package/dist/ui/widgets/rewind_panel.d.ts +2 -2
  610. package/dist/ui/widgets/rewind_panel.js +4 -2
  611. package/dist/ui/widgets/select.js +16 -27
  612. package/dist/ui/widgets/settings_panel.js +16 -0
  613. package/dist/ui/widgets/status_line_panel.d.ts +1 -0
  614. package/dist/ui/widgets/status_line_panel.js +30 -4
  615. package/dist/ui/widgets/text_input.d.ts +2 -0
  616. package/dist/ui/widgets/text_input.js +15 -1
  617. package/dist/ui/widgets/types.d.ts +2 -0
  618. package/dist/usage_projection.d.ts +24 -0
  619. package/dist/usage_projection.js +130 -0
  620. package/dist/usage_snapshot.d.ts +36 -0
  621. package/dist/usage_snapshot.js +131 -0
  622. package/dist/utils/assistant_message.d.ts +2 -0
  623. package/dist/utils/assistant_message.js +5 -0
  624. package/dist/utils/atomic_write.d.ts +6 -2
  625. package/dist/utils/atomic_write.js +29 -4
  626. package/dist/utils/checked_shell.d.ts +25 -0
  627. package/dist/utils/checked_shell.js +107 -0
  628. package/dist/utils/compaction.d.ts +4 -1
  629. package/dist/utils/compaction.js +31 -7
  630. package/dist/utils/context.d.ts +4 -4
  631. package/dist/utils/context.js +14 -12
  632. package/dist/utils/deepseek.d.ts +2 -2
  633. package/dist/utils/deepseek.js +13 -5
  634. package/dist/utils/ephemeral.js +4 -0
  635. package/dist/utils/ephemeral_tools.d.ts +18 -0
  636. package/dist/utils/ephemeral_tools.js +97 -0
  637. package/dist/utils/jev_client.d.ts +4 -0
  638. package/dist/utils/jev_client.js +15 -0
  639. package/dist/utils/model_cache.d.ts +15 -0
  640. package/dist/utils/model_cache.js +143 -0
  641. package/dist/utils/models.d.ts +4 -2
  642. package/dist/utils/models.js +12 -16
  643. package/dist/utils/reasoning.d.ts +8 -1
  644. package/dist/utils/reasoning.js +31 -11
  645. package/dist/utils/router_catalog.d.ts +49 -0
  646. package/dist/utils/router_catalog.js +271 -0
  647. package/dist/utils/sandbox.d.ts +9 -0
  648. package/dist/utils/sandbox.js +118 -15
  649. package/dist/utils/shell.d.ts +7 -0
  650. package/dist/utils/shell.js +98 -34
  651. package/dist/utils/subprocess_env.d.ts +3 -0
  652. package/dist/utils/subprocess_env.js +27 -1
  653. package/dist/web/accounts_mirror.d.ts +3 -1
  654. package/dist/web/accounts_mirror.js +13 -9
  655. package/dist/web/child_publication.d.ts +17 -0
  656. package/dist/web/child_publication.js +45 -0
  657. package/dist/web/mirror_authenticator.d.ts +31 -11
  658. package/dist/web/mirror_authenticator.js +67 -17
  659. package/dist/web/mirror_client.d.ts +31 -4
  660. package/dist/web/mirror_client.js +189 -23
  661. package/dist/web/mirror_stream.d.ts +84 -22
  662. package/dist/web/mirror_stream.js +676 -95
  663. package/dist/web/observer_query_redaction.d.ts +6 -0
  664. package/dist/web/observer_query_redaction.js +58 -0
  665. package/dist/web/pane_registry.d.ts +2 -0
  666. package/dist/web/pane_registry.js +86 -22
  667. package/dist/web/tool_image.d.ts +6 -0
  668. package/dist/web/tool_image.js +17 -0
  669. package/dist/web/view_plugin.d.ts +14 -0
  670. package/dist/web/view_plugin.js +23 -1
  671. package/dist/worker/executor.js +31 -12
  672. package/dist/worker/index.d.ts +1 -0
  673. package/dist/worker/toolsets.js +3 -1
  674. package/dist/worker/types.d.ts +12 -1
  675. package/dist/workflows/registry.js +1 -0
  676. package/dist/workflows/registry_handle.d.ts +2 -0
  677. package/dist/workflows/runtime.d.ts +2 -0
  678. package/dist/workflows/runtime.js +1 -0
  679. package/dist/workspace_agent.d.ts +7 -0
  680. package/dist/workspace_agent.js +36 -0
  681. package/dist/workspace_collision.d.ts +76 -0
  682. package/dist/workspace_collision.js +688 -0
  683. package/dist/workspace_layout.d.ts +18 -0
  684. package/dist/workspace_layout.js +121 -0
  685. package/dist/workspace_runtime.d.ts +44 -0
  686. package/dist/workspace_runtime.js +82 -0
  687. package/dist/workspace_session_context.d.ts +62 -0
  688. package/dist/workspace_session_context.js +160 -0
  689. package/dist/zlm-embed.mjs +32518 -9615
  690. package/dist/zlm.js +1 -0
  691. package/node_modules/@zerg/model-contracts/LICENSE.md +375 -0
  692. package/node_modules/@zerg/model-contracts/README.md +90 -0
  693. package/node_modules/@zerg/model-contracts/index.d.ts +20 -0
  694. package/node_modules/@zerg/model-contracts/index.js +223 -0
  695. package/node_modules/@zerg/model-contracts/package.json +8 -0
  696. package/node_modules/glob/node_modules/brace-expansion/index.js +78 -22
  697. package/node_modules/glob/node_modules/brace-expansion/package.json +1 -1
  698. package/node_modules/readdir-glob/node_modules/brace-expansion/index.js +78 -22
  699. package/node_modules/readdir-glob/node_modules/brace-expansion/package.json +1 -1
  700. package/package.json +45 -24
  701. package/packages/model-contracts/LICENSE.md +375 -0
  702. package/packages/model-contracts/README.md +90 -0
  703. package/packages/model-contracts/index.d.ts +20 -0
  704. package/packages/model-contracts/index.js +223 -0
  705. package/packages/model-contracts/package.json +8 -0
  706. package/remote-broker/Dockerfile +10 -0
  707. package/remote-broker/README.md +308 -0
  708. package/remote-broker/archive.py +1227 -0
  709. package/remote-broker/cutover.py +761 -0
  710. package/remote-broker/requirements.txt +5 -0
  711. package/remote-broker/resources.example.json +6 -0
  712. package/remote-broker/resources.write-staging.example.json +18 -0
  713. package/remote-broker/retained.py +686 -0
  714. package/remote-broker/retained_cleanup.py +550 -0
  715. package/remote-broker/server.py +648 -0
  716. package/scripts/build-remote-broker.mjs +13 -0
  717. package/scripts/ensure-local-packages.mjs +6 -0
  718. package/scripts/node-pty-helpers.mjs +103 -0
@@ -0,0 +1,1967 @@
1
+ import { storyReviewReceiptSchema, storyReviewViewSchema, storyEpisodeSchema, storyReviewView, storyReviewFailed } from './dynamic_story_review.js';
2
+ import { createHash } from 'node:crypto';
3
+ import { activeDynamicHistoryStorage, readDynamicHistory, dynamicHistory, dynamicMemoryHistory, dynamicBeliefEvidenceHistory, stageDynamicHistoryTransition, DYNAMIC_HISTORY_WINDOW } from '../dynamic_history.js';
4
+ import { initialInteraction, interactionSchema, locationSchema, positionSchema, meetingSchema, moveDynamicActors, validateMeetingHistory } from './dynamic_meetings.js';
5
+ import { storytellerSelectionSchema, dynamicInitializationSchema } from './dynamic_storyteller.js';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { z } from 'zod';
8
+ import { applyDynamicAgentUpdates, validFailedAdjudicationCauses, DYNAMIC_MEMORY_WINDOW, DYNAMIC_BELIEF_EVIDENCE_WINDOW } from './dynamic_agents.js';
9
+ import { digestDynamicText } from './dynamic_digest.js';
10
+ import { dynamicActionObjectGraph, dynamicObjectGraph } from './dynamic_mechanics.js';
11
+ import { projectDynamicAgents, projectDynamicDomainObjectsForActor, projectDynamicEffectsForActor, projectDynamicPlayerDecision, projectDynamicTimeline, } from './dynamic_projection.js';
12
+ import { applyDynamicWorldEffects } from './dynamic_world.js';
13
+ /**
14
+ * A generation name such as native-v7-r2 names a whole rule set by number. Older names chained one suffix per feature
15
+ * and every reader matched them by pattern; a generation carries every feature of the last chained name, plus its own.
16
+ */
17
+ export function isRulesGeneration(rulesVersion) {
18
+ return /^native-v[0-9]+-r[0-9]+$/u.test(rulesVersion);
19
+ }
20
+ export const MAX_DYNAMIC_STATE_BYTES = 2_097_152;
21
+ const MAX_REVISIONS = 100;
22
+ const identifier = z.string().trim().min(1).max(128);
23
+ const proposalIdentifier = z.string().trim().min(1).max(128);
24
+ const boundedText = (maximum) => z.string().trim().min(1).max(maximum);
25
+ const visibility = z.enum(['public', 'player-known', 'private']);
26
+ const publicVisibility = z.enum(['public', 'player-known', 'redacted']);
27
+ const finiteResourceMap = z.record(identifier, z.number().finite().min(-1_000_000).max(1_000_000)).refine(value => Object.keys(value).length <= 64);
28
+ const resourceVisibilityMap = z.record(identifier, visibility)
29
+ .refine(value => Object.keys(value).length <= 64);
30
+ const parameters = z.record(z.string(), z.unknown());
31
+ const jsonValueSchema = z.lazy(() => z.union([
32
+ z.string().max(2_000),
33
+ z.number().finite(),
34
+ z.boolean(),
35
+ z.null(),
36
+ z.array(jsonValueSchema).max(32),
37
+ z.record(z.string().trim().min(1).max(128), jsonValueSchema)
38
+ .refine(value => Object.keys(value).length <= 32),
39
+ ]));
40
+ const objectVisibilitySchema = z.discriminatedUnion('scope', [
41
+ z.object({ scope: z.literal('world') }).strict(),
42
+ z.object({
43
+ scope: z.literal('shared'),
44
+ actorIds: z.array(identifier).min(1).max(8),
45
+ }).strict(),
46
+ z.object({ scope: z.literal('private') }).strict(),
47
+ ]);
48
+ const domainObjectSchema = z.object({
49
+ id: identifier,
50
+ kind: identifier,
51
+ label: boundedText(160),
52
+ status: boundedText(80),
53
+ version: z.number().int().min(1).max(100_000),
54
+ ownerActorId: identifier.nullable(),
55
+ visibility: objectVisibilitySchema,
56
+ data: z.record(z.string().trim().min(1).max(128), jsonValueSchema)
57
+ .refine(value => Object.keys(value).length <= 32),
58
+ links: z.array(z.object({
59
+ relation: identifier,
60
+ targetType: z.enum(['actor', 'object', 'event', 'document']),
61
+ targetId: identifier,
62
+ }).strict()).max(16),
63
+ provenance: z.object({
64
+ createdRevision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
65
+ updatedRevision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
66
+ eventId: identifier,
67
+ actionId: identifier,
68
+ }).strict(),
69
+ }).strict();
70
+ const worldEffectSchema = z.discriminatedUnion('operation', [
71
+ z.object({
72
+ operation: z.literal('resource.change'),
73
+ actionId: identifier,
74
+ resourceId: identifier,
75
+ delta: z.number().finite(),
76
+ }).strict(),
77
+ z.object({
78
+ operation: z.literal('fact.add'),
79
+ actionId: identifier,
80
+ fact: boundedText(240),
81
+ }).strict(),
82
+ z.object({
83
+ operation: z.literal('fact.remove'),
84
+ actionId: identifier,
85
+ fact: boundedText(240),
86
+ }).strict(),
87
+ z.object({
88
+ operation: z.literal('object.put'),
89
+ actionId: identifier,
90
+ expectedVersion: z.number().int().min(1).max(100_000).nullable(),
91
+ sceneRetention: z.object({ version: z.literal(1), retiredIds: z.array(identifier).max(128) }).strict().optional(),
92
+ object: domainObjectSchema,
93
+ }).strict(),
94
+ ]);
95
+ export const intentSchema = z.object({
96
+ mechanic: identifier,
97
+ goalId: identifier,
98
+ summary: boundedText(400),
99
+ targetActorId: identifier.optional(),
100
+ }).strict();
101
+ const goalSchema = z.object({
102
+ id: identifier,
103
+ description: boundedText(500),
104
+ priority: z.number().int().min(0).max(100),
105
+ status: z.enum(['active', 'satisfied', 'blocked', 'abandoned']),
106
+ visibility,
107
+ }).strict();
108
+ const beliefSchema = z.object({
109
+ id: identifier,
110
+ subject: boundedText(240),
111
+ claim: boundedText(500),
112
+ confidence: z.number().int().min(0).max(100),
113
+ evidenceEventIds: z.array(identifier).max(MAX_REVISIONS),
114
+ visibility,
115
+ }).strict();
116
+ const relationshipSchema = z.object({
117
+ targetActorId: identifier,
118
+ trust: z.number().finite().min(0).max(100),
119
+ affinity: z.number().finite().min(0).max(100),
120
+ obligation: z.number().finite().min(-100).max(100),
121
+ conflictNotes: z.array(boundedText(400)).max(16),
122
+ changedByEventId: identifier.optional(),
123
+ visibility,
124
+ }).strict();
125
+ const memorySchema = z.object({
126
+ id: identifier,
127
+ eventId: identifier,
128
+ kind: z.enum(['observation', 'promise', 'conflict', 'cooperation', 'outcome']),
129
+ summary: boundedText(400),
130
+ salience: z.number().int().min(0).max(100),
131
+ visibility,
132
+ }).strict();
133
+ export const agentSchema = z.object({
134
+ actorId: identifier,
135
+ name: boundedText(160),
136
+ role: boundedText(160),
137
+ humanControlled: z.boolean(),
138
+ capabilities: z.array(identifier).min(1).max(24),
139
+ goals: z.array(goalSchema).min(1).max(16),
140
+ beliefs: z.array(beliefSchema).min(1).max(32),
141
+ relationships: z.array(relationshipSchema).max(16),
142
+ memories: z.array(memorySchema).max(32),
143
+ resources: finiteResourceMap,
144
+ resourceVisibility: resourceVisibilityMap,
145
+ currentIntent: intentSchema.nullable(),
146
+ }).strict().superRefine((agent, context) => {
147
+ const resourceIds = Object.keys(agent.resources).sort();
148
+ const visibilityIds = Object.keys(agent.resourceVisibility).sort();
149
+ if (!isDeepStrictEqual(resourceIds, visibilityIds)) {
150
+ context.addIssue({
151
+ code: z.ZodIssueCode.custom,
152
+ path: ['resourceVisibility'],
153
+ message: 'Resource visibility must match the personal resource keys',
154
+ });
155
+ }
156
+ });
157
+ const domainActionSchema = z.object({
158
+ id: proposalIdentifier,
159
+ mechanic: identifier,
160
+ actorId: identifier.optional(),
161
+ targetActorId: identifier.optional(),
162
+ sourceCharacterProposalId: proposalIdentifier.optional(),
163
+ sourceAttemptedActionId: proposalIdentifier.optional(),
164
+ sourcePlayerActionId: proposalIdentifier.optional(),
165
+ parameters,
166
+ reason: boundedText(500),
167
+ }).strict();
168
+ const characterActionMotivationSchema = z.object({
169
+ goalId: identifier,
170
+ beliefId: identifier,
171
+ memoryId: identifier,
172
+ relationshipTargetActorId: identifier,
173
+ resourceId: identifier,
174
+ }).strict();
175
+ const characterActionSchema = domainActionSchema.omit({
176
+ sourceCharacterProposalId: true,
177
+ sourceAttemptedActionId: true,
178
+ sourcePlayerActionId: true,
179
+ }).extend({
180
+ actorId: identifier,
181
+ motivation: characterActionMotivationSchema.nullable(),
182
+ }).strict();
183
+ const characterProposalSchema = z.object({
184
+ schemaVersion: z.literal(1),
185
+ proposalId: proposalIdentifier,
186
+ basedOnRevision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
187
+ actorId: identifier,
188
+ intent: intentSchema.nullable(),
189
+ discussionInvitation: z.object({ recipientActorId: identifier, topic: boundedText(240) }).strict().nullable().optional(),
190
+ attemptedActions: z.array(characterActionSchema).max(4),
191
+ internalReason: boundedText(800),
192
+ }).strict();
193
+ const playerActionSchema = z.object({
194
+ id: proposalIdentifier,
195
+ label: boundedText(120),
196
+ intent: boundedText(240),
197
+ description: boundedText(500),
198
+ mechanic: identifier,
199
+ targetActorId: identifier.optional(),
200
+ parameters,
201
+ risks: z.array(boundedText(300)).max(6),
202
+ requirements: z.array(boundedText(300)).max(6),
203
+ authoredBy: z.enum(['game-master', 'fallback', 'player']),
204
+ }).strict();
205
+ const agentUpdateSchema = z.object({
206
+ actorId: identifier,
207
+ sourceEventId: identifier,
208
+ sourceActionIds: z.array(identifier).max(16),
209
+ sourceAdjudicationProposalIds: z.array(identifier).length(1).optional(),
210
+ goalUpdates: z.array(z.object({
211
+ goalId: identifier,
212
+ priority: z.number().int().min(0).max(100).optional(),
213
+ status: z.enum(['active', 'satisfied', 'blocked', 'abandoned']).optional(),
214
+ }).strict()).max(16),
215
+ goalsToAppend: z.array(goalSchema).max(2),
216
+ beliefUpdates: z.array(z.object({
217
+ beliefId: identifier,
218
+ confidence: z.number().int().min(0).max(100),
219
+ evidenceEventIds: z.array(identifier).max(MAX_REVISIONS),
220
+ }).strict()).max(32),
221
+ beliefsToAppend: z.array(beliefSchema).max(4),
222
+ relationshipDeltas: z.array(z.object({
223
+ targetActorId: identifier,
224
+ trust: z.number().finite().min(-100).max(100),
225
+ affinity: z.number().finite().min(-100).max(100),
226
+ obligation: z.number().finite().min(-100).max(100),
227
+ reason: boundedText(300),
228
+ }).strict()).max(16),
229
+ memoriesToAppend: z.array(memorySchema).max(6),
230
+ resourceDeltas: finiteResourceMap,
231
+ nextIntent: intentSchema.nullable(),
232
+ }).strict();
233
+ const endingSchema = z.object({
234
+ endingBasis: z.object({
235
+ predicateId: identifier,
236
+ witnesses: z.array(z.object({ objectId: identifier, version: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER), actionId: identifier, eventId: identifier }).strict()).min(1).max(16),
237
+ actorIds: z.array(identifier).min(1).max(8),
238
+ }).strict().optional(),
239
+ title: boundedText(160),
240
+ narrative: boundedText(2_000),
241
+ outcome: z.enum(['triumph', 'mixed', 'collapse']),
242
+ causalEventIds: z.array(identifier).min(1).max(MAX_REVISIONS).refine(eventIds => new Set(eventIds).size === eventIds.length, 'Ending causes must be unique'),
243
+ }).strict();
244
+ const gmProposalSchema = z.object({
245
+ schemaVersion: z.literal(1),
246
+ proposalId: proposalIdentifier,
247
+ basedOnRevision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
248
+ event: z.object({
249
+ id: proposalIdentifier,
250
+ title: boundedText(160),
251
+ narrative: boundedText(2_000),
252
+ urgency: z.enum(['low', 'medium', 'high', 'critical']),
253
+ openQuestions: z.array(boundedText(240)).max(6),
254
+ }).strict(),
255
+ availableActions: z.array(playerActionSchema).max(4),
256
+ characterResponses: z.array(z.object({
257
+ actorId: identifier,
258
+ text: boundedText(600),
259
+ mood: boundedText(80),
260
+ }).strict()).max(8),
261
+ adjudications: z.array(z.object({
262
+ characterProposalId: proposalIdentifier,
263
+ outcome: z.enum(['succeeded', 'partial', 'failed', 'deferred']),
264
+ meetingId: identifier.optional(),
265
+ reason: boundedText(500),
266
+ actionIds: z.array(proposalIdentifier).max(16),
267
+ }).strict()).max(8),
268
+ playerAdjudication: z.object({
269
+ playerActionId: proposalIdentifier,
270
+ outcome: z.enum(['succeeded', 'partial', 'failed']),
271
+ reason: boundedText(500),
272
+ actionIds: z.array(proposalIdentifier).max(16),
273
+ }).strict().nullable(),
274
+ domainActions: z.array(domainActionSchema).max(16),
275
+ agentUpdates: z.array(agentUpdateSchema).max(8),
276
+ pacing: z.object({
277
+ mode: z.enum(['continue', 'resolve']),
278
+ tension: z.number().finite().min(0).max(100),
279
+ timeAdvance: boundedText(100),
280
+ advanceSteps: z.number().int().min(1).max(12),
281
+ }).strict(),
282
+ ending: endingSchema.nullable(),
283
+ }).strict();
284
+ const historyKindSchema = z.enum([
285
+ 'player-action',
286
+ 'agent-action',
287
+ 'agent-interaction',
288
+ 'gm-event',
289
+ 'adjudication',
290
+ 'world-change',
291
+ 'ending',
292
+ 'story-review',
293
+ ]);
294
+ const storytellerReceiptSchema = z.object({
295
+ recovery: z.object({
296
+ version: z.literal(2),
297
+ setbacks: z.array(z.object({
298
+ id: identifier, revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
299
+ actionIds: z.array(identifier).max(16), effectIndexes: z.array(z.number().int().min(0).max(63)).max(64),
300
+ objectIds: z.array(identifier).max(64), resourceIds: z.array(identifier).max(32),
301
+ mechanic: identifier, private: z.boolean(), major: z.boolean(),
302
+ }).strict()).max(64),
303
+ opportunities: z.array(z.object({
304
+ causeId: identifier, revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER), choiceId: identifier.nullable(), actionId: identifier.nullable(),
305
+ relation: z.string().min(1).max(80),
306
+ targets: z.array(z.object({ id: identifier, version: z.number().int().min(1) }).strict()).max(64),
307
+ personal: z.object({ resourceId: identifier, minimumRequired: z.number().int().min(0), cost: z.number().int().min(0), available: z.number().int().min(0) }).strict().nullable(),
308
+ worldCosts: z.array(z.object({ resourceId: identifier, required: z.number().int().min(0), available: z.number().int().min(0) }).strict()).max(32),
309
+ }).strict()).max(6400),
310
+ }).strict().optional(),
311
+ decision: z.object({
312
+ basedOnRevision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
313
+ mode: z.enum(['quiet', 'recovery', 'pressure']), strengthTier: z.number().int().min(0).max(3),
314
+ offerRecovery: z.boolean(), quietLimit: z.union([z.literal(3), z.literal(6)]),
315
+ inputDigest: z.string().regex(/^[a-f0-9]{64}$/),
316
+ }).strict(),
317
+ proposedPressure: z.array(domainActionSchema).max(3),
318
+ proposedRecovery: z.array(domainActionSchema).max(1),
319
+ acceptedPressureActionIds: z.array(identifier).max(16), majorCrisis: z.boolean(),
320
+ setbackResourceIds: z.array(identifier).max(32), recoveryChoiceIds: z.array(identifier).max(1),
321
+ recoveryForRevisions: z.array(z.number().int().min(1).max(Number.MAX_SAFE_INTEGER)).max(100),
322
+ }).strict();
323
+ const historySchema = z.object({
324
+ storyteller: storytellerReceiptSchema.optional(),
325
+ storyReview: z.lazy(() => storyReviewReceiptSchema).optional(),
326
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
327
+ eventId: proposalIdentifier,
328
+ kind: historyKindSchema,
329
+ title: boundedText(160),
330
+ summary: boundedText(2_000),
331
+ playerActionId: proposalIdentifier.nullable(),
332
+ playerIntent: boundedText(2000).optional(),
333
+ characterProposals: z.array(characterProposalSchema).max(4),
334
+ gmProposal: gmProposalSchema,
335
+ acceptedActionIds: z.array(proposalIdentifier).max(16),
336
+ effects: z.array(worldEffectSchema).max(64),
337
+ objectGraphBefore: z.array(z.object({
338
+ id: identifier,
339
+ ownerActorId: identifier.nullable(),
340
+ links: z.array(z.object({
341
+ relation: identifier,
342
+ targetType: z.enum(['actor', 'object', 'event', 'document']),
343
+ targetId: identifier,
344
+ }).strict()).max(16),
345
+ }).strict()).max(128).optional(),
346
+ usedFallback: z.boolean(),
347
+ meetings: z.array(meetingSchema).max(1).optional(),
348
+ }).strict();
349
+ const nativeCallSchema = z.object({
350
+ callId: z.number().int().min(1),
351
+ requestSha256: z.string().regex(/^[a-f0-9]{64}$/),
352
+ requestedAtMs: z.number().finite().min(0),
353
+ timeoutMs: z.number().finite().positive().max(Number.MAX_SAFE_INTEGER),
354
+ providerStartedAtMs: z.number().finite().min(0),
355
+ terminal: z.object({ type: z.enum(['inference-response', 'inference-failed']), sha256: z.string().regex(/^[a-f0-9]{64}$/), atMs: z.number().finite().min(0) }).strict().optional(),
356
+ decode: z.object({ type: z.enum(['inference-decoded', 'inference-decode-failed']), sha256: z.string().regex(/^[a-f0-9]{64}$/), atMs: z.number().finite().min(0) }).strict().optional(),
357
+ settlement: z.object({ startedAtMs: z.number().finite().min(0), settledAtMs: z.number().finite().min(0),
358
+ outcome: z.enum(['completed', 'failed', 'timeout']), failureCode: identifier.optional(), sha256: z.string().regex(/^[a-f0-9]{64}$/) }).strict().optional(),
359
+ }).strict();
360
+ function validNativeCallClocks(call) {
361
+ return call.providerStartedAtMs >= call.requestedAtMs
362
+ && (!call.terminal || call.terminal.atMs >= call.providerStartedAtMs)
363
+ && (!call.decode || (call.terminal?.type === 'inference-response' && call.decode.atMs >= call.terminal.atMs))
364
+ && (!call.settlement || (call.settlement.startedAtMs <= call.requestedAtMs && call.settlement.settledAtMs >= call.providerStartedAtMs));
365
+ }
366
+ const auditSchema = z.object({
367
+ mainIdentity: z.object({ version: z.union([z.literal(1), z.literal(2)]), proposalId: proposalIdentifier, eventId: identifier }).strict().optional(),
368
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
369
+ proposalId: proposalIdentifier,
370
+ status: z.enum(['accepted', 'rejected', 'fallback']),
371
+ codes: z.array(identifier).max(16),
372
+ characterRoute: z.enum(['gpt-5.6-luna:low', 'zergrouter:modal/deepseek-v4.1-flash']),
373
+ gameMasterRoute: z.enum(['gpt-5.6-luna:low', 'gpt-5.6-sol:low', 'gpt-5.6-sol:none', 'zergrouter:modal/deepseek-v4.1-flash']),
374
+ inputDigest: z.string().regex(/^[a-f0-9]{8}$/),
375
+ outputDigest: z.string().regex(/^[a-f0-9]{8}$/),
376
+ outputBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
377
+ outputScope: z.enum(['full', 'legacy-prefix']),
378
+ fallbackReason: z.string().max(300).nullable(),
379
+ nativeGmCalls: z.array(nativeCallSchema.extend({ phase: z.enum(['main', 'actor-update', 'choice-authoring', 'choice-repair', 'story-review']) }).refine(validNativeCallClocks))
380
+ .max(14).refine(calls => new Set(calls.map(call => call.callId)).size === calls.length).optional(),
381
+ nativeParticipantCalls: z.array(nativeCallSchema.extend({ phase: z.enum(['character', 'meeting-turn']) }).refine(validNativeCallClocks))
382
+ .max(19).refine(calls => new Set(calls.map(call => call.callId)).size === calls.length).optional(),
383
+ characterCalls: z.array(z.object({
384
+ deadlineVersion: z.literal(2).optional(),
385
+ requestVersion: z.union([z.literal(2), z.literal(3), z.literal(4), z.literal(5)]).optional(),
386
+ privacyVersion: z.literal(3).optional(),
387
+ actorId: identifier,
388
+ status: z.enum(['accepted', 'rejected']),
389
+ failureCode: identifier.optional(),
390
+ inputDigest: z.string().regex(/^[a-f0-9]{8}$/),
391
+ systemDigest: z.string().regex(/^[a-f0-9]{8}$/),
392
+ outputDigest: z.string().regex(/^[a-f0-9]{8}$/),
393
+ outputBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
394
+ fullProposalDigest: z.string().regex(/^[a-f0-9]{8}$/).optional(),
395
+ proposalDigest: z.string().regex(/^[a-f0-9]{8}$/).optional(),
396
+ timing: z.object({ startedAtMs: z.number().finite().min(0), settledAtMs: z.number().finite().min(0) }).strict(),
397
+ }).strict().refine(item => item.timing.settledAtMs >= item.timing.startedAtMs
398
+ && (item.status === 'accepted' ? item.failureCode === undefined && item.fullProposalDigest !== undefined : item.failureCode !== undefined)
399
+ && (item.fullProposalDigest === undefined) === (item.proposalDigest === undefined))).max(16).optional(),
400
+ characterRepairs: z.array(z.object({
401
+ actorId: identifier,
402
+ proposalId: proposalIdentifier,
403
+ cause: z.enum(['input_privacy_violation', 'private-knowledge-leak']),
404
+ status: z.enum(['accepted', 'rejected']),
405
+ requested: z.boolean(),
406
+ failureCode: identifier.optional(),
407
+ inputDigest: z.string().regex(/^[a-f0-9]{8}$/),
408
+ initialSystemDigest: z.string().regex(/^[a-f0-9]{8}$/),
409
+ repairSystemDigest: z.string().regex(/^[a-f0-9]{8}$/),
410
+ repairInputDigest: z.string().regex(/^[a-f0-9]{8}$/).optional(),
411
+ repairMode: z.enum(['bounded-rewrite', 'legacy']).optional(),
412
+ instructionVersion: z.union([z.literal(2), z.literal(3), z.literal(4)]).optional(),
413
+ initialPromptBytes: z.number().int().min(1).max(70_000),
414
+ repairPromptBytes: z.number().int().min(1).max(70_000),
415
+ firstOutputDigest: z.string().regex(/^[a-f0-9]{8}$/),
416
+ firstOutputBytes: z.number().int().min(1).max(4096),
417
+ firstElapsedMs: z.number().finite().min(0),
418
+ timing: z.object({ startedAtMs: z.number().finite().min(0), settledAtMs: z.number().finite().min(0) }).strict().optional(),
419
+ timeoutMs: z.number().int().min(0).max(20_000),
420
+ maxTokens: z.literal(768),
421
+ outputDigest: z.string().regex(/^[a-f0-9]{8}$/),
422
+ outputBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
423
+ proposalDigest: z.string().regex(/^[a-f0-9]{8}$/).optional(),
424
+ fullProposalDigest: z.string().regex(/^[a-f0-9]{8}$/).optional(),
425
+ }).strict().refine(item => (item.instructionVersion === 3 || item.instructionVersion === 4 || item.cause === 'input_privacy_violation')
426
+ && item.repairPromptBytes <= item.initialPromptBytes
427
+ && (item.timing === undefined || (item.timing.settledAtMs - item.timing.startedAtMs >= item.firstElapsedMs
428
+ && (item.status !== 'accepted' || item.timing.settledAtMs - item.timing.startedAtMs < 20_000)))
429
+ && item.requested === (item.timeoutMs > 0)
430
+ && (!item.requested || item.firstElapsedMs + item.timeoutMs <= 20_000)
431
+ && (item.status === 'accepted'
432
+ ? item.requested && item.failureCode === undefined && item.proposalDigest !== undefined && item.outputBytes > 0
433
+ : item.failureCode !== undefined && item.proposalDigest === undefined && item.fullProposalDigest === undefined), 'Character repair budget or outcome is invalid')).min(1).max(4).optional(),
434
+ publicRepairs: z.array(z.object({
435
+ version: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(5), z.literal(6)]), format: z.literal('public-text-patch-1'), phase: z.enum(['main', 'choice-authoring']),
436
+ initialInputDigest: z.string().regex(/^[a-f0-9]{8}$/), initialOutputDigest: z.string().regex(/^[a-f0-9]{8}$/), initialOutputBytes: z.number().int().min(1).max(20480), cause: z.enum(['input_privacy_violation', 'private-knowledge-leak']), requested: z.boolean(),
437
+ status: z.enum(['accepted', 'rejected']), failureCode: identifier.optional(),
438
+ inputDigest: z.string().regex(/^[a-f0-9]{8}$/), systemDigest: z.string().regex(/^[a-f0-9]{8}$/),
439
+ outputDigest: z.string().regex(/^[a-f0-9]{8}$/), outputBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
440
+ maxTokens: z.number().int().min(1).max(2560), timeoutMs: z.number().int().min(0).max(120_000),
441
+ deadlineAtMs: z.number().int().min(0),
442
+ timing: z.object({ startedAtMs: z.number().int().min(0), settledAtMs: z.number().int().min(0) }).strict(),
443
+ initialSystemDigest: z.string().regex(/^[a-f0-9]{8}$/),
444
+ initialPromptBytes: z.number().int().min(1).max(264000), repairPromptBytes: z.number().int().min(1).max(264000),
445
+ }).strict().refine(item => (item.version !== 6 || item.phase === 'choice-authoring') && item.maxTokens <= (item.phase === 'main' ? 1536 : 1024)
446
+ && item.repairPromptBytes <= item.initialPromptBytes
447
+ && item.timing.settledAtMs >= item.timing.startedAtMs
448
+ && item.timeoutMs === Math.max(0, item.deadlineAtMs - item.timing.startedAtMs)
449
+ && item.requested === (item.timeoutMs > 0)
450
+ && (item.requested || (item.outputBytes === 0 && item.outputDigest === digestDynamicText('')))
451
+ && (item.status === 'accepted' ? item.requested && item.failureCode === undefined && item.outputBytes > 0 && item.timing.settledAtMs < item.deadlineAtMs
452
+ : item.failureCode !== undefined), 'Public repair outcome or budget is invalid')).max(2).refine(items => new Set(items.map(item => item.phase)).size === items.length && items.reduce((sum, item) => sum + item.maxTokens, 0) <= 2560, 'Public repair pool is invalid').optional(),
453
+ actorUpdates: z.object({
454
+ byteAllocation: z.literal('receipt-pool-v1').optional(),
455
+ status: z.enum(['accepted', 'fallback']),
456
+ entries: z.array(z.object({
457
+ instructionVersion: z.union([z.literal(2), z.literal(3), z.literal(4), z.literal(5), z.literal(6), z.literal(7), z.literal(8), z.literal(9), z.literal(10), z.literal(11)]).optional(),
458
+ causeBindingVersion: z.literal(3).optional(),
459
+ actorId: identifier,
460
+ sourceEventId: identifier,
461
+ sourceActionIds: z.array(identifier).max(16),
462
+ sourceAdjudicationProposalIds: z.array(identifier).length(1).optional(),
463
+ model: z.enum(['gpt-5.6-luna', 'gpt-5.6-sol', 'modal/deepseek-v4.1-flash']),
464
+ reasoningEffort: z.enum(['low', 'none']),
465
+ requested: z.boolean(),
466
+ status: z.enum(['accepted', 'rejected']),
467
+ failureCode: identifier.optional(),
468
+ inputDigest: z.string().regex(/^[a-f0-9]{8}$/),
469
+ outputDigest: z.string().regex(/^[a-f0-9]{8}$/),
470
+ outputBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
471
+ maxTokens: z.number().int().min(1).max(2560),
472
+ repair: z.object({
473
+ version: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]), cause: z.enum(['input_privacy_violation', 'private-knowledge-leak']), requested: z.boolean(),
474
+ status: z.enum(['accepted', 'rejected']), failureCode: identifier.optional(),
475
+ inputDigest: z.string().regex(/^[a-f0-9]{8}$/), systemDigest: z.string().regex(/^[a-f0-9]{8}$/),
476
+ outputDigest: z.string().regex(/^[a-f0-9]{8}$/), outputBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
477
+ maxTokens: z.number().int().min(1).max(2560), timeoutMs: z.number().int().min(0).max(120_000),
478
+ deadlineAtMs: z.number().int().min(0),
479
+ timing: z.object({ startedAtMs: z.number().int().min(0), settledAtMs: z.number().int().min(0) }).strict(),
480
+ initialSystemDigest: z.string().regex(/^[a-f0-9]{8}$/),
481
+ // Actor requests use the 256 KiB GM input budget plus their fixed system text.
482
+ initialPromptBytes: z.number().int().min(1).max(262_144 + 4_096), repairPromptBytes: z.number().int().min(1).max(262_144 + 4_096),
483
+ }).strict().refine(item => (item.version !== 1 || item.cause === 'input_privacy_violation')
484
+ && item.repairPromptBytes <= item.initialPromptBytes
485
+ && item.timing.settledAtMs >= item.timing.startedAtMs
486
+ && item.timeoutMs === Math.max(0, item.deadlineAtMs - item.timing.startedAtMs)
487
+ && item.requested === (item.timeoutMs > 0)
488
+ && (item.requested || (item.outputBytes === 0 && item.outputDigest === digestDynamicText('')))
489
+ && (item.status === 'accepted' ? item.requested && item.failureCode === undefined && item.outputBytes > 0 && item.timing.settledAtMs < item.deadlineAtMs
490
+ : item.failureCode !== undefined), 'Actor repair outcome or budget is invalid').optional(),
491
+ }).strict()).max(8),
492
+ }).strict().optional(),
493
+ choiceAuthoring: z.object({
494
+ status: z.enum(['accepted', 'fallback']),
495
+ failureCode: identifier.optional(),
496
+ inputDigest: z.string().regex(/^[a-f0-9]{8}$/),
497
+ outputDigest: z.string().regex(/^[a-f0-9]{8}$/),
498
+ outputBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
499
+ }).strict().optional(),
500
+ choiceRepair: z.object({
501
+ cause: identifier,
502
+ status: z.enum(['accepted', 'rejected', 'topped-up']),
503
+ failureCode: identifier.optional(),
504
+ inputDigest: z.string().regex(/^[a-f0-9]{8}$/),
505
+ outputDigest: z.string().regex(/^[a-f0-9]{8}$/),
506
+ outputBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
507
+ }).strict().refine(value => (value.status === 'accepted' ? value.failureCode === undefined : value.failureCode !== undefined), 'Choice repair status must match its failure metadata').optional(),
508
+ redacted: z.number().int().min(1).max(64).optional(),
509
+ shed: z.array(z.object({
510
+ actionId: proposalIdentifier,
511
+ actorId: identifier.optional(),
512
+ mechanic: identifier,
513
+ code: identifier,
514
+ }).strict()).min(1).max(16).optional(),
515
+ }).strict().refine(audit => (audit.characterRepairs ?? []).every(repair => (repair.instructionVersion === 3 || repair.instructionVersion === 4)
516
+ === (audit.characterCalls?.find(call => call.actorId === repair.actorId)?.privacyVersion === 3)
517
+ && ((repair.instructionVersion !== 3 && repair.instructionVersion !== 4) || audit.characterCalls?.find(call => call.actorId === repair.actorId)?.failureCode === repair.cause)), 'Character privacy versions differ')
518
+ .refine(audit => ['main', 'choice-authoring', 'choice-repair'].every(phase => (audit.nativeGmCalls?.filter(call => call.phase === phase).length ?? 0) <= (audit.publicRepairs?.some(item => item.phase === phase && item.requested) ? 2 : 1)), 'GM calls need their bounded repair receipt');
519
+ const knowledgeViewSchema = z.object({
520
+ id: identifier,
521
+ text: boundedText(500),
522
+ value: z.number().finite().optional(),
523
+ visibility: publicVisibility,
524
+ sourceEventId: identifier.optional(),
525
+ }).strict();
526
+ const domainObjectViewSchema = z.object({
527
+ id: identifier,
528
+ kind: identifier,
529
+ label: boundedText(160),
530
+ status: boundedText(80),
531
+ version: z.number().int().min(1).max(100_000),
532
+ ownerActorId: identifier.nullable(),
533
+ data: z.record(z.string().trim().min(1).max(128), jsonValueSchema)
534
+ .refine(value => Object.keys(value).length <= 32),
535
+ links: z.array(z.object({
536
+ relation: identifier,
537
+ targetType: z.enum(['actor', 'object', 'event', 'document']),
538
+ targetId: identifier,
539
+ }).strict()).max(16),
540
+ updatedRevision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
541
+ }).strict();
542
+ const worldEffectViewSchema = z.discriminatedUnion('operation', [
543
+ z.object({
544
+ operation: z.literal('resource.change'),
545
+ resourceId: identifier,
546
+ resourceLabel: boundedText(160),
547
+ delta: z.number().finite(),
548
+ cause: z.object({
549
+ actor: boundedText(160),
550
+ action: boundedText(200),
551
+ reason: boundedText(500),
552
+ }).strict().optional(),
553
+ }).strict(),
554
+ z.object({
555
+ operation: z.literal('fact.add'),
556
+ fact: boundedText(240),
557
+ }).strict(),
558
+ z.object({
559
+ operation: z.literal('fact.remove'),
560
+ fact: boundedText(240),
561
+ }).strict(),
562
+ z.object({
563
+ operation: z.literal('object.put'),
564
+ objectId: identifier,
565
+ objectKind: identifier,
566
+ objectLabel: boundedText(160),
567
+ status: boundedText(80),
568
+ version: z.number().int().min(1).max(100_000),
569
+ expectedVersion: z.number().int().min(1).max(100_000).nullable(),
570
+ ownerActorId: identifier.nullable(),
571
+ }).strict(),
572
+ ]);
573
+ const frameSchema = z.object({
574
+ storyReview: z.lazy(() => storyReviewViewSchema).optional(),
575
+ schemaVersion: z.literal(5),
576
+ locations: z.array(locationSchema).max(32),
577
+ positions: z.array(positionSchema).min(3).max(8),
578
+ meetings: z.array(meetingSchema).max(1),
579
+ storyteller: storytellerSelectionSchema.nullable(),
580
+ gameKind: identifier,
581
+ revision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
582
+ status: z.enum(['active', 'ended', 'safety-stopped']),
583
+ safetyCeiling: z.object({
584
+ current: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
585
+ maximum: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
586
+ }).strict(),
587
+ situation: z.object({
588
+ id: proposalIdentifier.optional(),
589
+ title: boundedText(160),
590
+ narrative: boundedText(2_000),
591
+ urgency: z.enum(['low', 'medium', 'high', 'critical']),
592
+ openQuestions: z.array(boundedText(240)).max(6),
593
+ }).strict(),
594
+ safeMode: z.object({
595
+ active: z.boolean(),
596
+ reason: z.string().max(300).nullable(),
597
+ }).strict(),
598
+ pacing: gmProposalSchema.shape.pacing,
599
+ availableActions: z.array(playerActionSchema).max(4),
600
+ characterResponses: gmProposalSchema.shape.characterResponses,
601
+ agents: z.array(z.object({
602
+ id: identifier,
603
+ name: boundedText(160),
604
+ role: boundedText(160),
605
+ humanControlled: z.boolean(),
606
+ mood: boundedText(80),
607
+ currentIntent: z.string().max(400).nullable(),
608
+ goals: z.array(knowledgeViewSchema).max(16),
609
+ beliefs: z.array(knowledgeViewSchema).max(32),
610
+ relationships: z.array(knowledgeViewSchema).max(16),
611
+ memories: z.array(knowledgeViewSchema).max(64),
612
+ resources: z.array(knowledgeViewSchema).max(64),
613
+ recentAutonomousActions: z.array(knowledgeViewSchema).max(16),
614
+ }).strict()).min(3).max(8),
615
+ worldFacts: z.array(z.string().max(500)).max(MAX_REVISIONS),
616
+ world: z.array(z.object({
617
+ id: identifier,
618
+ label: boundedText(160),
619
+ value: z.number().finite(),
620
+ minimum: z.number().finite(),
621
+ maximum: z.number().finite(),
622
+ initial: z.number().finite().optional(),
623
+ dangerDirection: z.enum(['low', 'high', 'none']),
624
+ }).strict()).max(64),
625
+ domainObjects: z.array(domainObjectViewSchema).max(128),
626
+ latestEffects: z.array(worldEffectViewSchema).max(64),
627
+ timeline: z.array(z.object({
628
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
629
+ eventId: identifier,
630
+ kind: historyKindSchema,
631
+ title: boundedText(160),
632
+ summary: boundedText(2_000),
633
+ }).strict()).max(MAX_REVISIONS * 7),
634
+ adjudications: z.array(z.object({
635
+ proposalId: proposalIdentifier,
636
+ outcome: z.enum(['succeeded', 'partial', 'failed', 'deferred']),
637
+ reason: boundedText(500),
638
+ actionIds: z.array(proposalIdentifier).max(16),
639
+ }).strict()).max(8),
640
+ ending: endingSchema.nullable(),
641
+ playerDecision: z.object({
642
+ label: boundedText(120),
643
+ playerActionId: identifier,
644
+ outcome: z.enum(['succeeded', 'partial', 'failed']),
645
+ reason: boundedText(500),
646
+ }).strict().nullable().optional(),
647
+ }).strict();
648
+ const historyReferenceSchema = z.object({ version: z.literal(1), identity: z.string().regex(/^[a-f0-9]{64}$/), revision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
649
+ const storyWorldSchema = z.object({
650
+ resources: finiteResourceMap,
651
+ facts: z.array(z.string().max(500)).max(MAX_REVISIONS),
652
+ domainObjects: z.array(domainObjectSchema).max(128),
653
+ }).strict();
654
+ const stateSchema = z.object({
655
+ episode: z.lazy(() => storyEpisodeSchema(storyWorldSchema)).optional(),
656
+ agencyVersion: z.literal('emergent-v1').optional(),
657
+ historyArchive: z.object({ version: z.literal(1), genesis: historyReferenceSchema, head: historyReferenceSchema }).strict().optional(),
658
+ schemaVersion: z.literal(11),
659
+ interaction: interactionSchema,
660
+ initialization: dynamicInitializationSchema.nullable(),
661
+ gameKind: identifier,
662
+ rulesVersion: identifier,
663
+ seed: identifier,
664
+ revision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
665
+ status: z.enum(['active', 'ended', 'safety-stopped']),
666
+ safetyCeiling: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
667
+ world: storyWorldSchema,
668
+ agents: z.array(agentSchema).min(3).max(8),
669
+ history: z.array(historySchema).max(MAX_REVISIONS),
670
+ audit: z.array(auditSchema).max(MAX_REVISIONS),
671
+ frame: frameSchema,
672
+ }).strict();
673
+ export class DynamicStateContractError extends Error {
674
+ code;
675
+ constructor(code, message) {
676
+ super(message);
677
+ this.code = code;
678
+ this.name = 'DynamicStateContractError';
679
+ }
680
+ }
681
+ export function parseDynamicCharacterProposal(value) {
682
+ return parseProposal(value, characterProposalSchema);
683
+ }
684
+ export function parseDynamicGmWorldConsequences(value) {
685
+ return parseProposal(value, gmProposalSchema.omit({ availableActions: true, agentUpdates: true }));
686
+ }
687
+ export function parseDynamicGmConsequences(value) {
688
+ return parseProposal(value, gmProposalSchema.omit({ availableActions: true }));
689
+ }
690
+ export function parseDynamicGmProposal(value) {
691
+ return parseProposal(value, gmProposalSchema);
692
+ }
693
+ export function parseDynamicHistoryEntry(value) {
694
+ return parseProposal(value, historySchema);
695
+ }
696
+ export function parseDynamicAuditEntry(value) {
697
+ return parseProposal(value, auditSchema);
698
+ }
699
+ const parsedOwnedStates = new WeakMap();
700
+ export function retainedParsedDynamicStates() {
701
+ const source = activeDynamicHistoryStorage();
702
+ return source ? parsedOwnedStates.get(source)?.length ?? 0 : 0;
703
+ }
704
+ export function parseDynamicSimulationState(value) {
705
+ const normalized = normalizeBoundedJson(value);
706
+ const ownedStorage = jsonRecord(normalized)?.historyArchive === undefined ? undefined : activeDynamicHistoryStorage();
707
+ const key = ownedStorage ? createHash('sha256').update(JSON.stringify(normalized)).digest('hex') : undefined;
708
+ const retained = ownedStorage ? parsedOwnedStates.get(ownedStorage) ?? [] : [];
709
+ const prior = key === undefined ? undefined : retained.find(item => item.key === key);
710
+ if (prior)
711
+ return structuredClone(prior.state);
712
+ const migrated = normalizeBoundedJson(migrateLegacyDynamicState(normalized));
713
+ const result = stateSchema.safeParse(migrated);
714
+ if (!result.success) {
715
+ const path = result.error.issues[0]?.path.join('.') || 'root';
716
+ fail('state-shape-invalid', `Dynamic state is invalid at ${path}`);
717
+ }
718
+ const state = result.data;
719
+ if (state.historyArchive === undefined && state.revision > MAX_REVISIONS)
720
+ fail('state-shape-invalid', 'Unarchived state revision exceeds its bound');
721
+ if (state.historyArchive !== undefined) {
722
+ if (!(isRulesGeneration(state.rulesVersion) || /-adaptive-v[34](?:-progress-v1)?(?:-duration-v1(?:-invitations-v1(?:-restoration-v1)?)?)?(?:-story-review-v1(?:-player-bindings-v1(?:-meeting-v2)?)?)?$/u.test(state.rulesVersion)) || state.historyArchive.head.revision !== state.revision)
723
+ fail('state-shape-invalid', 'Archived state rules or revision is invalid');
724
+ const archived = readDynamicHistory(state);
725
+ parseDynamicSimulationState(archived.genesis);
726
+ // The archive reader parses each immutable entry with these exact schemas.
727
+ if (!sameJson(state.history, archived.history.slice(-DYNAMIC_HISTORY_WINDOW)) || !sameJson(state.audit, archived.audit.slice(-DYNAMIC_HISTORY_WINDOW)))
728
+ fail('state-lineage-invalid', 'Retained history differs from its original archive');
729
+ const evidence = dynamicBeliefEvidenceHistory(state);
730
+ if (state.agents.some(actor => actor.beliefs.some(belief => !sameJson(belief.evidenceEventIds, evidence[actor.actorId]?.[belief.id]?.slice(-DYNAMIC_BELIEF_EVIDENCE_WINDOW)))))
731
+ fail('state-lineage-invalid', 'Working belief evidence differs from its exact archive');
732
+ const memories = dynamicMemoryHistory(state);
733
+ if (state.agents.some(actor => !sameJson(actor.memories, memories[actor.actorId]?.slice(-DYNAMIC_MEMORY_WINDOW))))
734
+ fail('state-lineage-invalid', 'Working memories differ from their exact archive');
735
+ }
736
+ validateStateRelationships(state);
737
+ const player = state.agents.find(agent => agent.humanControlled);
738
+ const parsed = structuredClone({
739
+ ...state,
740
+ frame: {
741
+ ...state.frame,
742
+ latestEffects: projectDynamicEffectsForActor(state.history.at(-1)?.effects ?? [], state.frame.world, player.actorId, state.history.at(-1)?.gmProposal.domainActions ?? [], state.agents),
743
+ },
744
+ });
745
+ if (ownedStorage && key !== undefined)
746
+ parsedOwnedStates.set(ownedStorage, [{ key, state: structuredClone(parsed) }, ...retained.slice(0, 1)]);
747
+ return parsed;
748
+ }
749
+ function migrateLegacyDynamicState(value) {
750
+ const state = jsonRecord(value);
751
+ if (state === null)
752
+ return value;
753
+ const versionWithResourceVisibility = typeof state.schemaVersion === 'number'
754
+ && state.schemaVersion >= 2
755
+ && state.schemaVersion < 10
756
+ ? migrateLegacyAgentResourceVisibility(state)
757
+ : state;
758
+ const versionThree = versionWithResourceVisibility.schemaVersion === 2
759
+ ? migrateStateV2ToV3(versionWithResourceVisibility)
760
+ : versionWithResourceVisibility;
761
+ const versionFour = versionThree.schemaVersion === 3
762
+ ? migrateStateV3ToV4(versionThree)
763
+ : versionThree;
764
+ const versionFive = versionFour.schemaVersion === 4
765
+ ? migrateStateV4ToV5(versionFour)
766
+ : versionFour;
767
+ const versionSix = versionFive.schemaVersion === 5
768
+ ? migrateStateV5ToV6(versionFive)
769
+ : versionFive;
770
+ const versionSeven = versionSix.schemaVersion === 6
771
+ ? migrateStateV6ToV7(versionSix)
772
+ : versionSix;
773
+ const versionEight = versionSeven.schemaVersion === 7
774
+ ? migrateStateV7ToV8(versionSeven)
775
+ : versionSeven;
776
+ const versionNine = versionEight.schemaVersion === 8
777
+ ? migrateStateV8ToV9(versionEight)
778
+ : versionEight;
779
+ const versionTen = versionNine.schemaVersion === 9
780
+ ? migrateStateV9ToV10(versionNine)
781
+ : versionNine;
782
+ const legacy = migrateFrameV3ToV4(versionTen);
783
+ if (legacy.schemaVersion !== 10)
784
+ return legacy;
785
+ if (typeof legacy.safetyCeiling === 'number' && legacy.safetyCeiling > 100)
786
+ fail('state-shape-invalid', 'Legacy safety ceiling is out of bounds');
787
+ if (Object.hasOwn(legacy, 'interaction'))
788
+ fail('state-lineage-invalid', 'A legacy state cannot claim an interaction policy');
789
+ if ((Object.hasOwn(legacy, 'initialization') && legacy.initialization !== null) || (Array.isArray(legacy.history) && legacy.history.some(entry => {
790
+ const record = jsonRecord(entry);
791
+ return record !== null && Object.hasOwn(record, 'storyteller');
792
+ })))
793
+ fail('state-shape-invalid', 'Legacy state cannot opt into storyteller behavior');
794
+ const frame = jsonRecord(legacy.frame);
795
+ if (frame === null || frame.schemaVersion !== 4 || Object.hasOwn(frame, 'locations') || Object.hasOwn(frame, 'positions') || Object.hasOwn(frame, 'meetings'))
796
+ return legacy;
797
+ const agents = Array.isArray(legacy.agents) ? legacy.agents : [];
798
+ const interaction = initialInteraction(undefined, agents.map(value => ({ actorId: String(jsonRecord(value)?.actorId ?? '') })));
799
+ return { ...legacy, schemaVersion: 11, initialization: null, interaction, frame: { ...frame, schemaVersion: 5, storyteller: null, locations: [], positions: interaction.positions, meetings: [] } };
800
+ }
801
+ // Frame version four projects one timeline entry per autonomous action. A stored
802
+ // version-three frame is rebuilt from its committed history instead of rejected.
803
+ function migrateFrameV3ToV4(state) {
804
+ const frame = jsonRecord(state.frame);
805
+ if (frame === null || frame.schemaVersion !== 3)
806
+ return state;
807
+ const rebuilt = jsonRecord(canonicalizeLegacyFrame(state)) ?? frame;
808
+ return { ...state, frame: { ...rebuilt, schemaVersion: 4 } };
809
+ }
810
+ function migrateLegacyAgentResourceVisibility(state) {
811
+ if (!Array.isArray(state.agents))
812
+ return state;
813
+ return {
814
+ ...state,
815
+ agents: state.agents.map((agentValue) => {
816
+ const agent = jsonRecord(agentValue);
817
+ const resources = jsonRecord(agent?.resources);
818
+ if (agent === null
819
+ || resources === null
820
+ || Object.hasOwn(agent, 'resourceVisibility'))
821
+ return agentValue;
822
+ const visibility = agent.humanControlled === true ? 'player-known' : 'private';
823
+ return {
824
+ ...agent,
825
+ resourceVisibility: Object.fromEntries(Object.keys(resources).map(resourceId => [
826
+ resourceId,
827
+ visibility,
828
+ ])),
829
+ };
830
+ }),
831
+ };
832
+ }
833
+ function migrateStateV2ToV3(state) {
834
+ if (!Array.isArray(state.history))
835
+ return state;
836
+ return {
837
+ ...state,
838
+ schemaVersion: 3,
839
+ frame: sanitizeLegacyFrame(state.frame),
840
+ history: state.history.map((entryValue) => {
841
+ const entry = jsonRecord(entryValue);
842
+ const proposal = jsonRecord(entry?.gmProposal);
843
+ if (entry === null || proposal === null || !Array.isArray(proposal.agentUpdates)) {
844
+ return entryValue;
845
+ }
846
+ return {
847
+ ...entry,
848
+ gmProposal: {
849
+ ...proposal,
850
+ agentUpdates: proposal.agentUpdates.map((updateValue) => {
851
+ const update = jsonRecord(updateValue);
852
+ if (update === null)
853
+ return updateValue;
854
+ return {
855
+ ...update,
856
+ ...(!Object.prototype.hasOwnProperty.call(update, 'goalsToAppend')
857
+ ? { goalsToAppend: [] }
858
+ : {}),
859
+ ...(!Object.prototype.hasOwnProperty.call(update, 'beliefsToAppend')
860
+ ? { beliefsToAppend: [] }
861
+ : {}),
862
+ };
863
+ }),
864
+ },
865
+ };
866
+ }),
867
+ };
868
+ }
869
+ function migrateStateV3ToV4(state) {
870
+ if (!Array.isArray(state.history))
871
+ return state;
872
+ const world = jsonRecord(state.world);
873
+ if (world === null)
874
+ return state;
875
+ const history = state.history.map((entryValue) => {
876
+ const entry = jsonRecord(entryValue);
877
+ if (entry === null)
878
+ return entryValue;
879
+ return {
880
+ ...entry,
881
+ effects: legacyEffects(entry),
882
+ };
883
+ });
884
+ const migrated = {
885
+ ...state,
886
+ schemaVersion: 4,
887
+ world: {
888
+ ...world,
889
+ domainObjects: [],
890
+ },
891
+ history,
892
+ };
893
+ return {
894
+ ...migrated,
895
+ frame: canonicalizeLegacyFrame(migrated),
896
+ };
897
+ }
898
+ function migrateStateV4ToV5(state) {
899
+ if (!Array.isArray(state.history))
900
+ return state;
901
+ return {
902
+ ...state,
903
+ schemaVersion: 5,
904
+ history: state.history.map((entryValue) => {
905
+ const entry = jsonRecord(entryValue);
906
+ const proposal = jsonRecord(entry?.gmProposal);
907
+ if (entry === null || proposal === null || !Array.isArray(proposal.agentUpdates)) {
908
+ return entryValue;
909
+ }
910
+ const event = jsonRecord(proposal.event);
911
+ const domainActions = Array.isArray(proposal.domainActions)
912
+ ? proposal.domainActions.map(jsonRecord).filter((action) => (action !== null))
913
+ : [];
914
+ return {
915
+ ...entry,
916
+ gmProposal: {
917
+ ...proposal,
918
+ agentUpdates: proposal.agentUpdates.map((updateValue) => {
919
+ const update = jsonRecord(updateValue);
920
+ if (update === null)
921
+ return updateValue;
922
+ const actorId = update.actorId;
923
+ return {
924
+ ...update,
925
+ sourceEventId: event?.id,
926
+ sourceActionIds: domainActions
927
+ .filter(action => (action.actorId === undefined
928
+ || action.actorId === actorId
929
+ || action.targetActorId === actorId))
930
+ .map(action => action.id),
931
+ };
932
+ }),
933
+ },
934
+ };
935
+ }),
936
+ };
937
+ }
938
+ function migrateStateV5ToV6(state) {
939
+ return {
940
+ ...state,
941
+ schemaVersion: 6,
942
+ rulesVersion: 'legacy-v5',
943
+ };
944
+ }
945
+ function migrateStateV6ToV7(state) {
946
+ const frame = jsonRecord(state.frame);
947
+ const world = jsonRecord(state.world);
948
+ if (frame === null
949
+ || world === null
950
+ || !Array.isArray(state.agents)
951
+ || !Array.isArray(state.history)
952
+ || !Array.isArray(world.domainObjects)
953
+ || !Array.isArray(frame.world)) {
954
+ return { ...state, schemaVersion: 7 };
955
+ }
956
+ try {
957
+ const agents = state.agents;
958
+ const history = state.history;
959
+ const player = agents.find(agent => agent.humanControlled);
960
+ if (player === undefined)
961
+ return { ...state, schemaVersion: 7 };
962
+ const latestProposal = history.at(-1)?.gmProposal;
963
+ const publicResources = frame.world;
964
+ return {
965
+ ...state,
966
+ schemaVersion: 7,
967
+ frame: {
968
+ ...frame,
969
+ schemaVersion: 3,
970
+ agents: projectDynamicAgents(agents, history, latestProposal?.characterResponses ?? []),
971
+ domainObjects: projectDynamicDomainObjectsForActor(world.domainObjects, player.actorId),
972
+ latestEffects: projectDynamicEffectsForActor(history.at(-1)?.effects ?? [], publicResources, player.actorId),
973
+ },
974
+ };
975
+ }
976
+ catch {
977
+ return {
978
+ ...state,
979
+ schemaVersion: 7,
980
+ frame: {
981
+ ...frame,
982
+ schemaVersion: 3,
983
+ domainObjects: [],
984
+ latestEffects: [],
985
+ },
986
+ };
987
+ }
988
+ }
989
+ function migrateStateV7ToV8(state) {
990
+ if (Array.isArray(state.history) && state.history.length > 0) {
991
+ fail('state-version-incompatible', 'A progressed schema-seven run cannot prove autonomous action citations');
992
+ }
993
+ return { ...state, schemaVersion: 8 };
994
+ }
995
+ function migrateStateV8ToV9(state) {
996
+ if (!Array.isArray(state.audit))
997
+ return { ...state, schemaVersion: 9 };
998
+ return {
999
+ ...state,
1000
+ schemaVersion: 9,
1001
+ audit: state.audit.map((entryValue) => {
1002
+ const entry = jsonRecord(entryValue);
1003
+ if (entry === null)
1004
+ return entryValue;
1005
+ if (typeof entry.rawCompletion !== 'string')
1006
+ return entryValue;
1007
+ const { rawCompletion, ...rest } = entry;
1008
+ return {
1009
+ ...rest,
1010
+ outputDigest: digestDynamicText(rawCompletion),
1011
+ outputBytes: Buffer.byteLength(rawCompletion, 'utf8'),
1012
+ outputScope: 'legacy-prefix',
1013
+ };
1014
+ }),
1015
+ };
1016
+ }
1017
+ function migrateStateV9ToV10(state) {
1018
+ if (!Array.isArray(state.agents) || !Array.isArray(state.history)) {
1019
+ return { ...state, schemaVersion: 10 };
1020
+ }
1021
+ const frame = jsonRecord(state.frame);
1022
+ if (frame === null)
1023
+ return { ...state, schemaVersion: 10 };
1024
+ try {
1025
+ const agents = state.agents;
1026
+ const history = state.history;
1027
+ return {
1028
+ ...state,
1029
+ schemaVersion: 10,
1030
+ frame: {
1031
+ ...frame,
1032
+ agents: projectDynamicAgents(agents, history, history.at(-1)?.gmProposal.characterResponses ?? []),
1033
+ },
1034
+ };
1035
+ }
1036
+ catch {
1037
+ return { ...state, schemaVersion: 10 };
1038
+ }
1039
+ }
1040
+ function legacyEffects(entry) {
1041
+ const proposal = jsonRecord(entry.gmProposal);
1042
+ if (proposal === null || !Array.isArray(proposal.domainActions))
1043
+ return [];
1044
+ return proposal.domainActions.flatMap((actionValue) => {
1045
+ const action = jsonRecord(actionValue);
1046
+ const actionId = typeof action?.id === 'string' ? action.id : null;
1047
+ const actionParameters = jsonRecord(action?.parameters);
1048
+ if (actionId === null || actionParameters === null)
1049
+ return [];
1050
+ const effects = [];
1051
+ const deltas = jsonRecord(actionParameters.worldDeltas);
1052
+ if (deltas !== null) {
1053
+ for (const [resourceId, delta] of Object.entries(deltas)) {
1054
+ if (typeof delta === 'number' && Number.isFinite(delta)) {
1055
+ effects.push({ operation: 'resource.change', actionId, resourceId, delta });
1056
+ }
1057
+ }
1058
+ }
1059
+ if (Array.isArray(actionParameters.factsToRemove)) {
1060
+ for (const fact of actionParameters.factsToRemove) {
1061
+ if (typeof fact === 'string')
1062
+ effects.push({ operation: 'fact.remove', actionId, fact });
1063
+ }
1064
+ }
1065
+ if (Array.isArray(actionParameters.factsToAdd)) {
1066
+ for (const fact of actionParameters.factsToAdd) {
1067
+ if (typeof fact === 'string')
1068
+ effects.push({ operation: 'fact.add', actionId, fact });
1069
+ }
1070
+ }
1071
+ return effects;
1072
+ });
1073
+ }
1074
+ function canonicalizeLegacyFrame(state) {
1075
+ const frame = jsonRecord(sanitizeLegacyFrame(state.frame));
1076
+ const world = jsonRecord(state.world);
1077
+ if (frame === null || world === null || !Array.isArray(state.history))
1078
+ return state.frame;
1079
+ const latestEntry = jsonRecord(state.history.at(-1));
1080
+ const proposal = jsonRecord(latestEntry?.gmProposal);
1081
+ const audits = Array.isArray(state.audit) ? state.audit : [];
1082
+ const audit = jsonRecord(audits.at(-1));
1083
+ if (latestEntry === null || proposal === null || audit === null)
1084
+ return frame;
1085
+ const status = state.status;
1086
+ const event = jsonRecord(proposal.event);
1087
+ if (event === null)
1088
+ return frame;
1089
+ const situation = status === 'safety-stopped'
1090
+ ? {
1091
+ title: 'Safety ceiling reached',
1092
+ narrative: 'The run stops without inventing a win or loss. Its full history remains available for review.',
1093
+ urgency: 'low',
1094
+ openQuestions: [],
1095
+ }
1096
+ : event;
1097
+ const adjudications = Array.isArray(proposal.adjudications)
1098
+ ? proposal.adjudications.map((value) => {
1099
+ const adjudication = jsonRecord(value);
1100
+ if (adjudication === null)
1101
+ return value;
1102
+ return {
1103
+ proposalId: adjudication.characterProposalId,
1104
+ outcome: adjudication.outcome,
1105
+ reason: adjudication.reason,
1106
+ actionIds: adjudication.actionIds,
1107
+ };
1108
+ })
1109
+ : [];
1110
+ const playerAdjudication = jsonRecord(proposal.playerAdjudication);
1111
+ if (playerAdjudication !== null) {
1112
+ adjudications.push({
1113
+ proposalId: playerAdjudication.playerActionId,
1114
+ outcome: playerAdjudication.outcome,
1115
+ reason: playerAdjudication.reason,
1116
+ actionIds: playerAdjudication.actionIds,
1117
+ });
1118
+ }
1119
+ return {
1120
+ ...frame,
1121
+ gameKind: state.gameKind,
1122
+ revision: state.revision,
1123
+ status,
1124
+ safetyCeiling: {
1125
+ current: state.revision,
1126
+ maximum: state.safetyCeiling,
1127
+ },
1128
+ situation,
1129
+ safeMode: audit.status === 'fallback'
1130
+ ? { active: true, reason: audit.fallbackReason }
1131
+ : { active: false, reason: null },
1132
+ pacing: proposal.pacing,
1133
+ availableActions: status === 'active' && Array.isArray(proposal.availableActions)
1134
+ ? proposal.availableActions
1135
+ : [],
1136
+ characterResponses: proposal.characterResponses,
1137
+ worldFacts: world.facts,
1138
+ timeline: projectDynamicTimeline(state.history, Array.isArray(state.agents) ? state.agents : []),
1139
+ adjudications,
1140
+ ending: status === 'ended' ? proposal.ending : null,
1141
+ };
1142
+ }
1143
+ function sanitizeLegacyFrame(value) {
1144
+ const frame = jsonRecord(value);
1145
+ if (frame === null || !Array.isArray(frame.agents))
1146
+ return value;
1147
+ return {
1148
+ ...frame,
1149
+ agents: frame.agents.map((agentValue) => {
1150
+ const agent = jsonRecord(agentValue);
1151
+ if (agent === null)
1152
+ return agentValue;
1153
+ return {
1154
+ ...agent,
1155
+ goals: sanitizeLegacyKnowledge(agent.goals, 'goal'),
1156
+ beliefs: sanitizeLegacyKnowledge(agent.beliefs, 'belief'),
1157
+ relationships: sanitizeLegacyKnowledge(agent.relationships, 'relationship'),
1158
+ memories: sanitizeLegacyKnowledge(agent.memories, 'memory'),
1159
+ };
1160
+ }),
1161
+ };
1162
+ }
1163
+ function sanitizeLegacyKnowledge(value, kind) {
1164
+ if (!Array.isArray(value))
1165
+ return value;
1166
+ return value.map((itemValue, index) => {
1167
+ const item = jsonRecord(itemValue);
1168
+ return item?.visibility === 'redacted'
1169
+ ? { ...item, id: `redacted-${kind}-${index + 1}` }
1170
+ : itemValue;
1171
+ });
1172
+ }
1173
+ function jsonRecord(value) {
1174
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
1175
+ ? value
1176
+ : null;
1177
+ }
1178
+ function parseProposal(value, schema) {
1179
+ const normalized = normalizeBoundedJson(value);
1180
+ const result = schema.safeParse(normalized);
1181
+ if (!result.success) {
1182
+ const path = result.error.issues[0]?.path.join('.') || 'root';
1183
+ fail('proposal-shape-invalid', `Dynamic proposal is invalid at ${path}`);
1184
+ }
1185
+ return structuredClone(result.data);
1186
+ }
1187
+ export function validateDynamicStateTransition(input) {
1188
+ stageDynamicHistoryTransition(input.previous, input.next);
1189
+ const next = parseDynamicSimulationState(input.next);
1190
+ if (next.gameKind !== input.driverKind || next.revision !== input.hostRevision + 1) {
1191
+ fail('state-revision-invalid', 'Dynamic state must match its driver and next host revision');
1192
+ }
1193
+ if (input.previous === null) {
1194
+ if (input.hostRevision !== 0) {
1195
+ fail('state-lineage-invalid', 'A dynamic state lineage must start at host revision zero');
1196
+ }
1197
+ return next;
1198
+ }
1199
+ const previous = parseDynamicSimulationState(input.previous);
1200
+ if (previous.status !== 'active') {
1201
+ fail('state-lineage-invalid', 'A terminal dynamic state cannot append another revision');
1202
+ }
1203
+ if (!sameJson(next.interaction.policy, previous.interaction.policy) || next.interaction.policyVersion !== previous.interaction.policyVersion)
1204
+ fail('state-lineage-invalid', 'Interaction policy cannot change within a lineage');
1205
+ if (!sameJson(next.initialization, previous.initialization))
1206
+ fail('state-lineage-invalid', 'Storyteller selection cannot change during a run');
1207
+ if (next.rulesVersion !== previous.rulesVersion || next.agencyVersion !== previous.agencyVersion) {
1208
+ fail('state-lineage-invalid', 'A dynamic state lineage cannot change its rules version');
1209
+ }
1210
+ if (next.revision !== previous.revision + 1
1211
+ || next.gameKind !== previous.gameKind
1212
+ || next.seed !== previous.seed
1213
+ || next.safetyCeiling !== previous.safetyCeiling
1214
+ || !sameJson(dynamicHistory(next).slice(0, -1), dynamicHistory(previous))
1215
+ || !sameJson(readDynamicHistory(next).audit.slice(0, -1), readDynamicHistory(previous).audit)
1216
+ || !sameJson(next.agents.map(agent => agent.actorId), previous.agents.map(agent => agent.actorId))) {
1217
+ fail('state-lineage-invalid', 'Dynamic state must append one revision without rewriting prior state');
1218
+ }
1219
+ const latest = next.history.at(-1);
1220
+ if (latest?.objectGraphBefore !== undefined && !sameJson(latest.objectGraphBefore, dynamicObjectGraph(previous.world.domainObjects))) {
1221
+ fail('state-lineage-invalid', 'Action context must match the previous world');
1222
+ }
1223
+ try {
1224
+ if (latest === undefined || !sameJson(applyDynamicAgentUpdates(previous.agents, latest.gmProposal, {
1225
+ agencyVersion: previous.agencyVersion,
1226
+ knownEventIds: dynamicHistory(previous).map(entry => entry.eventId),
1227
+ memoryHistory: dynamicMemoryHistory(previous), beliefEvidenceHistory: dynamicBeliefEvidenceHistory(previous),
1228
+ characterProposals: latest.characterProposals,
1229
+ }), next.agents)) {
1230
+ fail('state-lineage-invalid', 'Agent state must equal the committed Game Master consequences');
1231
+ }
1232
+ }
1233
+ catch (error) {
1234
+ if (error instanceof DynamicStateContractError)
1235
+ throw error;
1236
+ fail('state-lineage-invalid', 'Agent state contains an invalid Game Master consequence');
1237
+ }
1238
+ try {
1239
+ if (latest === undefined || !sameJson(applyDynamicWorldEffects(previous.world, latest.effects, {
1240
+ agencyVersion: previous.agencyVersion,
1241
+ revision: latest.revision,
1242
+ eventId: latest.eventId,
1243
+ actorIds: next.agents.map(agent => agent.actorId),
1244
+ actionIds: latest.gmProposal.domainActions.map(action => action.id),
1245
+ knownActionIds: [...new Set([
1246
+ ...previous.world.domainObjects
1247
+ .filter(object => object.provenance.createdRevision === 0)
1248
+ .map(object => object.provenance.actionId),
1249
+ ...dynamicHistory(next).flatMap(entry => (entry.gmProposal.domainActions.map(action => action.id))),
1250
+ ])],
1251
+ eventIds: [...new Set([
1252
+ ...previous.world.domainObjects
1253
+ .filter(object => object.provenance.createdRevision === 0)
1254
+ .map(object => object.provenance.eventId),
1255
+ ...dynamicHistory(next).map(entry => entry.eventId),
1256
+ ])],
1257
+ documentIds: [],
1258
+ }), next.world)) {
1259
+ fail('state-lineage-invalid', 'World state must equal the committed Game Master consequences');
1260
+ }
1261
+ }
1262
+ catch (error) {
1263
+ if (error instanceof DynamicStateContractError)
1264
+ throw error;
1265
+ fail('state-lineage-invalid', 'World state contains an invalid Game Master consequence');
1266
+ }
1267
+ return next;
1268
+ }
1269
+ function validateStateRelationships(retained) {
1270
+ const archived = readDynamicHistory(retained);
1271
+ const memories = dynamicMemoryHistory(retained);
1272
+ const state = { ...retained, history: archived.history, audit: archived.audit,
1273
+ agents: memories === undefined ? retained.agents : retained.agents.map(actor => ({ ...actor, memories: memories[actor.actorId] })) };
1274
+ const initial = initialInteraction(state.interaction.policy ?? undefined, state.agents);
1275
+ if (state.interaction.policyVersion !== initial.policyVersion || !sameJson(state.interaction.locations, initial.locations))
1276
+ fail('interaction-state-invalid', 'Interaction state must match its immutable policy');
1277
+ let interaction = initial;
1278
+ for (const entry of state.history) {
1279
+ if (initial.policyVersion === null && entry.meetings !== undefined)
1280
+ fail('interaction-state-invalid', 'Legacy history cannot contain invented meetings');
1281
+ if (initial.policyVersion !== null && entry.meetings === undefined)
1282
+ fail('interaction-state-invalid', 'Enabled history must retain meeting outcomes');
1283
+ validateMeetingHistory(entry, interaction, state.agents, state.agencyVersion);
1284
+ interaction = moveDynamicActors(interaction, entry.meetings ?? [], entry.gmProposal.domainActions, entry.revision);
1285
+ }
1286
+ if (!sameJson(interaction.positions, state.interaction.positions) || !sameJson(state.frame.locations, interaction.locations)
1287
+ || !sameJson(state.frame.positions, interaction.positions) || !sameJson(state.frame.meetings, state.history.at(-1)?.meetings ?? []))
1288
+ fail('interaction-state-invalid', 'Positions and public meeting projection must match canonical history');
1289
+ if (!sameJson(state.frame.storyteller, state.initialization?.storyteller ?? null)
1290
+ || state.history.some(entry => state.initialization === null ? entry.storyteller !== undefined
1291
+ : entry.storyteller === undefined || (state.initialization.storyteller.policyVersion === 'storyteller-2') !== (entry.storyteller.recovery !== undefined) || entry.storyteller.decision.basedOnRevision !== entry.revision - 1)) {
1292
+ fail('state-lineage-invalid', 'Storyteller selection and history disagree');
1293
+ }
1294
+ const actorIds = state.agents.map(agent => agent.actorId);
1295
+ const actors = new Set(actorIds);
1296
+ const frameActorIds = state.frame.agents.map(agent => agent.id);
1297
+ const eventIds = state.history.map(entry => entry.eventId);
1298
+ const proposalIds = state.history.map(entry => entry.gmProposal.proposalId);
1299
+ const characterProposalIds = state.history.flatMap(entry => (entry.characterProposals.map(proposal => proposal.proposalId)));
1300
+ const actionIds = state.history.flatMap(entry => [
1301
+ ...entry.characterProposals.flatMap(proposal => proposal.attemptedActions.map(action => action.id)),
1302
+ ...entry.gmProposal.domainActions.map(action => action.id),
1303
+ ]);
1304
+ const revisionsMatch = state.history.every((entry, index) => entry.revision === index + 1)
1305
+ && state.audit.every((entry, index) => entry.revision === index + 1);
1306
+ const validStatus = state.revision <= state.safetyCeiling
1307
+ && (state.status !== 'active' || state.revision < state.safetyCeiling)
1308
+ && (state.status !== 'safety-stopped' || state.revision === state.safetyCeiling)
1309
+ && (state.status !== 'ended' || state.frame.ending !== null)
1310
+ && (state.status === 'ended' || state.frame.ending === null);
1311
+ const terminalChronology = state.history.every((entry, index) => {
1312
+ const isFinal = index === state.history.length - 1;
1313
+ const resolves = entry.gmProposal.pacing.mode === 'resolve';
1314
+ const hasEnding = entry.gmProposal.ending !== null;
1315
+ if (resolves !== hasEnding)
1316
+ return false;
1317
+ return isFinal && state.status === 'ended' ? resolves : !resolves;
1318
+ });
1319
+ const frameMatches = sameJson(state.frame.storyReview, state.episode === undefined ? undefined : storyReviewView(state.episode))
1320
+ && state.frame.gameKind === state.gameKind
1321
+ && state.frame.revision === state.revision
1322
+ && state.frame.status === state.status
1323
+ && state.frame.safetyCeiling.current === state.revision
1324
+ && state.frame.safetyCeiling.maximum === state.safetyCeiling
1325
+ && sameJson(state.frame.worldFacts, state.world.facts)
1326
+ && validDerivedFrame(retained);
1327
+ const rosterMatches = unique(actorIds)
1328
+ && state.agents.filter(agent => agent.humanControlled).length === 1
1329
+ && unique(frameActorIds)
1330
+ && sameSet(actorIds, frameActorIds)
1331
+ && state.agents.every(agent => (unique(agent.capabilities)
1332
+ && unique(agent.goals.map(goal => goal.id))
1333
+ && unique(agent.beliefs.map(belief => belief.id))
1334
+ && unique(agent.memories.map(memory => memory.id))
1335
+ && unique(agent.relationships.map(relationship => relationship.targetActorId))
1336
+ && (state.agencyVersion === 'emergent-v1' || state.status === 'ended'
1337
+ || agent.humanControlled
1338
+ || agent.goals.some(goal => goal.status === 'active'))
1339
+ && agent.relationships.every(relationship => (relationship.targetActorId !== agent.actorId
1340
+ && actors.has(relationship.targetActorId)))
1341
+ && (state.agencyVersion === 'emergent-v1' || agent.currentIntent === null || agent.goals.some(goal => (goal.id === agent.currentIntent?.goalId && goal.status === 'active')))
1342
+ && (state.agencyVersion === 'emergent-v1' || agent.currentIntent === null
1343
+ || agent.capabilities.includes(agent.currentIntent.mechanic))
1344
+ && (state.agencyVersion === 'emergent-v1' || agent.currentIntent?.targetActorId === undefined
1345
+ || (actors.has(agent.currentIntent.targetActorId)
1346
+ && agent.currentIntent.targetActorId !== agent.actorId))));
1347
+ const historyMatches = state.history.length === state.revision
1348
+ && state.audit.length === state.revision
1349
+ && revisionsMatch
1350
+ && unique(eventIds)
1351
+ && unique(proposalIds)
1352
+ && unique(characterProposalIds)
1353
+ && unique(actionIds)
1354
+ && terminalChronology
1355
+ && state.history.every((entry, index) => (entry.gmProposal.basedOnRevision === index
1356
+ && entry.gmProposal.event.id === entry.eventId
1357
+ && entry.characterProposals.every(proposal => proposal.basedOnRevision === index)
1358
+ && state.audit[index]?.proposalId === entry.gmProposal.proposalId))
1359
+ && validCommittedHistory(state);
1360
+ const invalidRelationships = [
1361
+ ...(!validStatus ? ['status'] : []),
1362
+ ...(!frameMatches ? ['frame'] : []),
1363
+ ...(!rosterMatches ? ['roster'] : []),
1364
+ ...(!historyMatches ? ['history'] : []),
1365
+ ...(!validWorldObjects(state) ? ['world'] : []),
1366
+ ...(state.agencyVersion !== 'emergent-v1' && leaksPrivateText(state) ? ['privacy'] : []),
1367
+ ];
1368
+ if (invalidRelationships.length > 0) {
1369
+ fail('state-inconsistent', `Dynamic state relationships are inconsistent: ${invalidRelationships.join(', ')}`);
1370
+ }
1371
+ }
1372
+ function validWorldObjects(state) {
1373
+ const seedObjects = state.world.domainObjects.filter(object => (object.provenance.createdRevision === 0));
1374
+ const seedEventIds = seedObjects.map(object => object.provenance.eventId);
1375
+ const currentEventId = state.history.at(-1)?.eventId ?? seedEventIds[0] ?? 'initial-state';
1376
+ try {
1377
+ applyDynamicWorldEffects(state.world, [], {
1378
+ agencyVersion: state.agencyVersion,
1379
+ revision: Math.max(1, state.revision),
1380
+ eventId: currentEventId,
1381
+ actorIds: state.agents.map(agent => agent.actorId),
1382
+ actionIds: [],
1383
+ knownActionIds: [...new Set([
1384
+ ...seedObjects.map(object => object.provenance.actionId),
1385
+ ...state.history.flatMap(entry => (entry.gmProposal.domainActions.map(action => action.id))),
1386
+ ])],
1387
+ eventIds: [...new Set([
1388
+ currentEventId,
1389
+ ...seedEventIds,
1390
+ ...state.history.map(entry => entry.eventId),
1391
+ ])],
1392
+ documentIds: [],
1393
+ });
1394
+ return true;
1395
+ }
1396
+ catch {
1397
+ return false;
1398
+ }
1399
+ }
1400
+ function validDerivedFrame(state) {
1401
+ const resourceIds = Object.keys(state.world.resources);
1402
+ const player = state.agents.find(agent => agent.humanControlled);
1403
+ if (player === undefined)
1404
+ return false;
1405
+ const expectedDomainObjects = projectDynamicDomainObjectsForActor(state.world.domainObjects, player.actorId);
1406
+ const expectedLatestEffects = projectDynamicEffectsForActor(state.history.at(-1)?.effects ?? [], state.frame.world, player.actorId, state.frame.latestEffects.some(effect => effect.operation === 'resource.change' && effect.cause !== undefined)
1407
+ ? state.history.at(-1)?.gmProposal.domainActions ?? [] : [], state.agents);
1408
+ const expectedAgents = projectDynamicAgents(state.agents, state.history, state.history.at(-1)?.gmProposal.characterResponses ?? []);
1409
+ if (!unique(state.frame.world.map(resource => resource.id))
1410
+ || (state.frame.playerDecision !== undefined
1411
+ && !sameJson(state.frame.playerDecision, projectDynamicPlayerDecision(state.history)))
1412
+ || state.frame.world.some(resource => !resourceIds.includes(resource.id))
1413
+ || state.frame.world.some(resource => state.world.resources[resource.id] !== resource.value)
1414
+ || !sameJson(state.frame.domainObjects, expectedDomainObjects)
1415
+ || !sameJson(state.frame.latestEffects, expectedLatestEffects)
1416
+ || !sameJson(state.frame.agents, expectedAgents)
1417
+ || !sameJson(state.frame.timeline, projectDynamicTimeline(state.history, state.agents)))
1418
+ return false;
1419
+ if (state.revision === 0) {
1420
+ return state.frame.timeline.length === 0
1421
+ && state.frame.characterResponses.length === 0
1422
+ && state.frame.adjudications.length === 0
1423
+ && state.frame.ending === null
1424
+ && sameJson(state.frame.safeMode, { active: false, reason: null });
1425
+ }
1426
+ const proposal = state.history.at(-1)?.gmProposal;
1427
+ const audit = state.audit.at(-1);
1428
+ if (!proposal || !audit)
1429
+ return false;
1430
+ const situation = state.status === 'safety-stopped'
1431
+ ? {
1432
+ title: 'Safety ceiling reached',
1433
+ narrative: 'The run stops without inventing a win or loss. Its full history remains available for review.',
1434
+ urgency: 'low',
1435
+ openQuestions: [],
1436
+ }
1437
+ : proposal.event;
1438
+ const adjudications = [
1439
+ ...proposal.adjudications.map(item => ({
1440
+ proposalId: item.characterProposalId,
1441
+ outcome: item.outcome,
1442
+ reason: item.reason,
1443
+ actionIds: item.actionIds,
1444
+ })),
1445
+ ...(proposal.playerAdjudication === null
1446
+ ? []
1447
+ : [{
1448
+ proposalId: proposal.playerAdjudication.playerActionId,
1449
+ outcome: proposal.playerAdjudication.outcome,
1450
+ reason: proposal.playerAdjudication.reason,
1451
+ actionIds: proposal.playerAdjudication.actionIds,
1452
+ }]),
1453
+ ];
1454
+ return sameJson(state.frame.situation, situation)
1455
+ && sameJson(state.frame.availableActions, state.status === 'active' ? proposal.availableActions : [])
1456
+ && sameJson(state.frame.characterResponses, proposal.characterResponses)
1457
+ && sameJson(state.frame.pacing, proposal.pacing)
1458
+ && sameJson(state.frame.adjudications, adjudications)
1459
+ && sameJson(state.frame.ending, state.status === 'ended' ? proposal.ending : null)
1460
+ && sameJson(state.frame.safeMode, audit.status === 'fallback'
1461
+ ? { active: true, reason: audit.fallbackReason }
1462
+ : storyReviewFailed(state) ? { active: true, reason: 'Story review failed; no story judgment was accepted.' }
1463
+ : { active: false, reason: null });
1464
+ }
1465
+ function validCommittedHistory(state) {
1466
+ const actors = new Map(state.agents.map(agent => [agent.actorId, agent]));
1467
+ const appendedGoalKeys = state.history.flatMap(entry => entry.gmProposal.agentUpdates
1468
+ .flatMap(update => update.goalsToAppend.map(goal => `${update.actorId}:${goal.id}`)));
1469
+ const appendedBeliefKeys = state.history.flatMap(entry => entry.gmProposal.agentUpdates
1470
+ .flatMap(update => update.beliefsToAppend.map(belief => `${update.actorId}:${belief.id}`)));
1471
+ const appendedMemoryKeys = state.history.flatMap(entry => entry.gmProposal.agentUpdates
1472
+ .flatMap(update => update.memoriesToAppend.map(memory => `${update.actorId}:${memory.id}`)));
1473
+ if (!unique(appendedGoalKeys) || !unique(appendedBeliefKeys) || !unique(appendedMemoryKeys)) {
1474
+ return false;
1475
+ }
1476
+ const appendedGoals = new Set(appendedGoalKeys);
1477
+ const appendedBeliefs = new Set(appendedBeliefKeys);
1478
+ const appendedMemories = new Set(appendedMemoryKeys);
1479
+ const replacedIntentActorIds = new Set(state.history.flatMap(entry => (entry.gmProposal.agentUpdates
1480
+ .filter(update => update.nextIntent !== null)
1481
+ .map(update => update.actorId))));
1482
+ const updatedGoalStatusKeys = new Set(state.history.flatMap(entry => (entry.gmProposal.agentUpdates.flatMap(update => update.goalUpdates
1483
+ .filter(goal => goal.status !== undefined)
1484
+ .map(goal => `${update.actorId}:${goal.goalId}`)))));
1485
+ const cursors = new Map(state.agents.map(agent => [agent.actorId, {
1486
+ goals: new Map(agent.goals
1487
+ .filter(goal => !appendedGoals.has(`${agent.actorId}:${goal.id}`))
1488
+ .map(goal => [
1489
+ goal.id,
1490
+ updatedGoalStatusKeys.has(`${agent.actorId}:${goal.id}`) ? 'active' : goal.status,
1491
+ ])),
1492
+ beliefs: new Set(agent.beliefs
1493
+ .filter(belief => !appendedBeliefs.has(`${agent.actorId}:${belief.id}`))
1494
+ .map(belief => belief.id)),
1495
+ memories: new Set(agent.memories
1496
+ .filter(memory => !appendedMemories.has(`${agent.actorId}:${memory.id}`))
1497
+ .map(memory => memory.id)),
1498
+ currentIntent: replacedIntentActorIds.has(agent.actorId)
1499
+ ? null
1500
+ : structuredClone(agent.currentIntent),
1501
+ }]));
1502
+ const historyIsValid = state.history.every((entry, index) => {
1503
+ const audit = state.audit[index];
1504
+ if (!audit)
1505
+ return false;
1506
+ const proposal = entry.gmProposal;
1507
+ const actions = new Map(proposal.domainActions.map(action => [action.id, action]));
1508
+ const graphBefore = entry.objectGraphBefore ?? state.world.domainObjects;
1509
+ const graphAtAction = (actionId) => entry.objectGraphBefore === undefined
1510
+ ? graphBefore
1511
+ : dynamicActionObjectGraph(actionId, proposal.domainActions, graphBefore, entry.effects);
1512
+ if (entry.objectGraphBefore !== undefined) {
1513
+ const graph = entry.objectGraphBefore;
1514
+ if (!unique(graph.map(object => object.id)) || graph.some(object => ((object.ownerActorId !== null && !actors.has(object.ownerActorId))
1515
+ || object.links.some(link => ((link.targetType === 'actor' && !actors.has(link.targetId))
1516
+ || (link.targetType === 'object' && !graph.some(target => target.id === link.targetId)))))))
1517
+ return false;
1518
+ const after = dynamicActionObjectGraph('', proposal.domainActions, graph, entry.effects);
1519
+ const expectedAfter = index === state.history.length - 1
1520
+ ? dynamicObjectGraph(state.world.domainObjects)
1521
+ : state.history[index + 1]?.objectGraphBefore;
1522
+ if (expectedAfter === undefined || !sameJson(after, expectedAfter))
1523
+ return false;
1524
+ }
1525
+ const characters = new Map(entry.characterProposals.map(character => [
1526
+ character.proposalId,
1527
+ character,
1528
+ ]));
1529
+ const responseActorIds = new Set(proposal.characterResponses.map(response => response.actorId));
1530
+ const requiredResponseActorIds = new Set([
1531
+ ...entry.characterProposals.map(character => character.actorId),
1532
+ ...proposal.agentUpdates.map(update => update.actorId),
1533
+ ].filter(actorId => actors.get(actorId)?.humanControlled === false));
1534
+ if (entry.title !== proposal.event.title
1535
+ || entry.summary !== proposal.event.narrative
1536
+ || entry.kind !== deriveHistoryKind(entry)
1537
+ || !sameJson(entry.acceptedActionIds, proposal.domainActions.map(action => action.id))
1538
+ || entry.effects.some(effect => !actions.has(effect.actionId))
1539
+ || entry.usedFallback !== (audit.status === 'fallback')
1540
+ || (audit.status === 'accepted' && (audit.codes.length !== 0 || audit.fallbackReason !== null))
1541
+ || (audit.status === 'fallback' && (audit.codes.length === 0 || audit.fallbackReason === null))
1542
+ || (audit.shed !== undefined && (audit.shed.some(item => actions.has(item.actionId))
1543
+ || !unique(audit.shed.map(item => item.actionId))
1544
+ || audit.shed.some(item => item.actorId !== undefined
1545
+ && actors.get(item.actorId)?.humanControlled !== false)))
1546
+ || (audit.characterCalls !== undefined && (!unique(audit.characterCalls.map(item => item.actorId))
1547
+ || audit.characterCalls.some(item => actors.get(item.actorId)?.humanControlled !== false
1548
+ || (item.status === 'rejected' && !(item.failureCode === 'input_privacy_violation' || (item.privacyVersion === 3 && item.failureCode === 'private-knowledge-leak')) && !audit.codes.includes(item.failureCode))
1549
+ || (item.status === 'rejected' && (item.failureCode === 'input_privacy_violation' || (item.privacyVersion === 3 && item.failureCode === 'private-knowledge-leak'))
1550
+ && !audit.characterRepairs?.some(repair => repair.actorId === item.actorId))
1551
+ || (item.status === 'accepted' && !audit.codes.includes('identifier-reused')
1552
+ && !entry.characterProposals.some(character => character.actorId === item.actorId
1553
+ && digestDynamicText(JSON.stringify(character)) === item.proposalDigest)))))
1554
+ || (audit.characterRepairs !== undefined && (!unique(audit.characterRepairs.map(item => item.actorId))
1555
+ || audit.characterRepairs.some(item => !actors.has(item.actorId)
1556
+ || (item.status === 'accepted'
1557
+ ? !entry.characterProposals.some(character => character.actorId === item.actorId
1558
+ && character.proposalId === item.proposalId
1559
+ && digestDynamicText(JSON.stringify(character)) === item.proposalDigest)
1560
+ : audit.status !== 'fallback' || !audit.codes.includes(`character-public-write-rejected:${item.actorId}`)
1561
+ || entry.characterProposals.some(character => character.actorId === item.actorId)))))
1562
+ || (audit.publicRepairs !== undefined && ((audit.gameMasterRoute !== 'gpt-5.6-sol:none' && audit.gameMasterRoute !== 'zergrouter:modal/deepseek-v4.1-flash')
1563
+ || audit.publicRepairs.some(item => {
1564
+ const original = item.phase === 'main' ? audit : audit.choiceAuthoring;
1565
+ return original === undefined || item.initialInputDigest !== original.inputDigest
1566
+ || item.initialOutputDigest !== original.outputDigest || item.initialOutputBytes !== original.outputBytes
1567
+ || (item.status === 'rejected' && (audit.status !== 'fallback' || !audit.codes.includes(item.failureCode)));
1568
+ })
1569
+ || (audit.status === 'accepted' && audit.outputBytes + (audit.choiceAuthoring?.outputBytes ?? 0)
1570
+ + (audit.actorUpdates?.entries.reduce((sum, item) => sum + item.outputBytes + (item.repair?.outputBytes ?? 0), 0) ?? 0)
1571
+ + audit.publicRepairs.reduce((sum, item) => sum + item.outputBytes, 0) > 20480)))
1572
+ || (audit.actorUpdates !== undefined && (!unique(audit.actorUpdates.entries.map(item => item.actorId))
1573
+ || (audit.actorUpdates.byteAllocation === 'receipt-pool-v1' && (state.agencyVersion !== 'emergent-v1'
1574
+ || !audit.actorUpdates.entries.some(item => item.instructionVersion === 6 || item.instructionVersion === 8 || item.instructionVersion === 9 || item.instructionVersion === 11)
1575
+ || (audit.actorUpdates.status === 'accepted' && (() => {
1576
+ const remaining = 20_480 - audit.outputBytes;
1577
+ const pool = remaining - Math.min(4096, Math.floor(remaining / 2));
1578
+ const equalShare = Math.floor(pool / Math.max(1, audit.actorUpdates.entries.length));
1579
+ return audit.actorUpdates.entries.reduce((sum, item) => sum + item.outputBytes, 0) > pool
1580
+ || audit.actorUpdates.entries.some(item => item.repair !== undefined
1581
+ || item.outputBytes > (item.instructionVersion === 6 || item.instructionVersion === 8 || item.instructionVersion === 9 || item.instructionVersion === 11 ? pool : equalShare));
1582
+ })())))
1583
+ || audit.actorUpdates.entries.some(item => !actors.has(item.actorId)
1584
+ || (item.causeBindingVersion !== undefined && (state.agencyVersion !== 'emergent-v1' || ![8, 9, 11].includes(item.instructionVersion ?? 1)))
1585
+ || audit.gameMasterRoute !== (item.model === 'modal/deepseek-v4.1-flash' ? `zergrouter:${item.model}` : `${item.model}:${item.reasoningEffort}`)
1586
+ || (state.agencyVersion !== 'emergent-v1' && item.sourceActionIds.length === 0 && item.sourceAdjudicationProposalIds === undefined)
1587
+ || (item.sourceAdjudicationProposalIds !== undefined && (actors.get(item.actorId)?.humanControlled === true
1588
+ || !entry.characterProposals.some(character => character.actorId === item.actorId && character.proposalId === item.sourceAdjudicationProposalIds?.[0])))
1589
+ || (item.status === 'accepted' && (item.failureCode !== undefined || !item.requested))
1590
+ || (!item.requested && (item.outputBytes !== 0 || item.outputDigest !== digestDynamicText('')))
1591
+ || (item.status === 'rejected' && item.failureCode === undefined)
1592
+ || (item.repair !== undefined && (!item.requested || item.outputBytes === 0 || item.repair.maxTokens > item.maxTokens
1593
+ || (item.repair.status === 'rejected' && (item.status !== 'rejected' || item.failureCode !== item.repair.failureCode)))))
1594
+ || audit.actorUpdates.entries.reduce((sum, item) => sum + item.maxTokens, 0) > 2560
1595
+ || audit.actorUpdates.entries.reduce((sum, item) => sum + (item.repair?.maxTokens ?? 0), 0) > 2560
1596
+ || (audit.actorUpdates.status === 'fallback' && audit.status !== 'fallback')
1597
+ || (audit.actorUpdates.status === 'accepted' && (audit.actorUpdates.entries.some(item => item.status !== 'accepted'
1598
+ || item.sourceEventId !== entry.eventId
1599
+ || !unique(item.sourceActionIds)
1600
+ || !validFailedAdjudicationCauses(item, proposal, entry.characterProposals, [...actors.values()].filter(actor => actor.humanControlled).map(actor => actor.actorId), state.agencyVersion)
1601
+ || (state.agencyVersion !== 'emergent-v1' && !proposal.agentUpdates.some(update => update.actorId === item.actorId
1602
+ && isDeepStrictEqual(update.sourceAdjudicationProposalIds, item.sourceAdjudicationProposalIds)
1603
+ && update.sourceActionIds.length === item.sourceActionIds.length
1604
+ && item.sourceActionIds.every(id => update.sourceActionIds.includes(id))))
1605
+ || item.sourceActionIds.some(actionId => !actions.has(actionId)
1606
+ || (state.agencyVersion !== 'emergent-v1'
1607
+ && !proposal.agentUpdates.some(update => update.actorId === item.actorId && update.sourceActionIds.length === item.sourceActionIds.length && update.sourceActionIds.includes(actionId)))))
1608
+ || proposal.agentUpdates.some(update => !audit.actorUpdates?.entries.some(item => item.actorId === update.actorId))
1609
+ || audit.outputBytes + audit.actorUpdates.entries.reduce((sum, item) => sum + item.outputBytes + (item.repair?.outputBytes ?? 0), 0) > 20480
1610
+ || (audit.choiceAuthoring?.status === 'accepted' && audit.outputBytes
1611
+ + audit.actorUpdates.entries.reduce((sum, item) => sum + item.outputBytes + (item.repair?.outputBytes ?? 0), 0)
1612
+ + audit.choiceAuthoring.outputBytes > 20480)))))
1613
+ || (audit.choiceAuthoring?.status === 'fallback' && audit.status !== 'fallback')
1614
+ || (audit.choiceAuthoring?.status === 'accepted' && audit.choiceAuthoring.failureCode !== undefined)
1615
+ || (audit.choiceAuthoring?.status === 'fallback' && audit.choiceAuthoring.failureCode === undefined)
1616
+ || (audit.choiceAuthoring !== undefined && audit.choiceRepair !== undefined)
1617
+ || (audit.choiceRepair?.status === 'rejected' && audit.status !== 'fallback')
1618
+ || (audit.choiceRepair?.status === 'topped-up' && proposal.availableActions.length < 3)
1619
+ || audit.status === 'rejected'
1620
+ || !unique(entry.characterProposals.map(character => character.actorId))
1621
+ || entry.characterProposals.some(character => (!actors.has(character.actorId)
1622
+ || actors.get(character.actorId)?.humanControlled === true
1623
+ || (state.agencyVersion !== 'emergent-v1' && (character.intent === null || !actors.get(character.actorId)?.capabilities.includes(character.intent.mechanic)
1624
+ || cursors.get(character.actorId)?.goals.get(character.intent.goalId) !== 'active'
1625
+ || (cursors.get(character.actorId)?.currentIntent !== null && (cursors.get(character.actorId)?.currentIntent?.mechanic !== character.intent.mechanic
1626
+ || cursors.get(character.actorId)?.currentIntent?.goalId !== character.intent.goalId
1627
+ || cursors.get(character.actorId)?.currentIntent?.targetActorId
1628
+ !== character.intent.targetActorId))))
1629
+ || character.attemptedActions.some(action => (action.actorId !== character.actorId
1630
+ || !actors.has(action.actorId)
1631
+ || !actors.get(character.actorId)?.capabilities.includes(action.mechanic)
1632
+ || (state.agencyVersion !== 'emergent-v1' && (action.motivation === null || character.intent === null || action.motivation.goalId !== character.intent.goalId
1633
+ || !cursors.get(character.actorId)?.beliefs.has(action.motivation.beliefId)
1634
+ || !cursors.get(character.actorId)?.memories.has(action.motivation.memoryId)
1635
+ || !actors.get(character.actorId)?.relationships.some(relationship => (relationship.targetActorId === action.motivation?.relationshipTargetActorId))
1636
+ || (action.targetActorId !== undefined
1637
+ && action.targetActorId !== action.motivation.relationshipTargetActorId)
1638
+ || !Object.hasOwn(actors.get(character.actorId)?.resources ?? {}, action.motivation.resourceId)))))))
1639
+ || proposal.domainActions.some(action => {
1640
+ const actor = action.actorId === undefined ? null : actors.get(action.actorId);
1641
+ return actor === undefined
1642
+ || (actor !== null && !actor.capabilities.includes(action.mechanic) && !(state.agencyVersion === 'emergent-v1' && actor.humanControlled && action.mechanic === 'act-freely' && entry.playerIntent !== undefined));
1643
+ })
1644
+ || proposal.characterResponses.some(response => (!actors.has(response.actorId)
1645
+ || actors.get(response.actorId)?.humanControlled === true))
1646
+ || (state.agencyVersion !== 'emergent-v1' && [...requiredResponseActorIds].some(actorId => !responseActorIds.has(actorId)))
1647
+ || (proposal.ending !== null && (!unique(proposal.ending.causalEventIds)
1648
+ || !proposal.ending.causalEventIds.includes(proposal.event.id)
1649
+ || proposal.ending.causalEventIds.some(eventId => (!state.history.slice(0, index + 1).some(candidate => candidate.eventId === eventId)))))
1650
+ || !unique(proposal.agentUpdates.map(update => update.actorId))
1651
+ || proposal.agentUpdates.some(update => (update.sourceEventId !== proposal.event.id
1652
+ || !unique(update.sourceActionIds)
1653
+ || !validFailedAdjudicationCauses(update, proposal, entry.characterProposals, [...actors.values()].filter(actor => actor.humanControlled).map(actor => actor.actorId), state.agencyVersion)
1654
+ || update.sourceActionIds.some((actionId) => {
1655
+ const action = actions.get(actionId);
1656
+ return action === undefined || !historicalActionParticipantIds(action, entry.effects, graphAtAction(actionId)).includes(update.actorId);
1657
+ })))
1658
+ || (state.agencyVersion !== 'emergent-v1' && proposal.domainActions.some(action => (!entry.effects.some(effect => effect.actionId === action.id)
1659
+ && !proposal.agentUpdates.some(update => update.sourceActionIds.includes(action.id)))))
1660
+ || proposal.agentUpdates.some(update => !validHistoricalAgentUpdate(update, actors, cursors, state.history.slice(0, index + 1).map(historyEntry => historyEntry.eventId), actions, entry.effects, graphAtAction, proposal.pacing.mode === 'continue', state.agencyVersion)))
1661
+ return false;
1662
+ const adjudications = new Map(proposal.adjudications.map(adjudication => [
1663
+ adjudication.characterProposalId,
1664
+ adjudication,
1665
+ ]));
1666
+ if (adjudications.size !== proposal.adjudications.length
1667
+ || adjudications.size !== characters.size
1668
+ || [...characters.keys()].some(id => !adjudications.has(id)))
1669
+ return false;
1670
+ const adjudicatedActionIds = [];
1671
+ for (const adjudication of proposal.adjudications) {
1672
+ const character = characters.get(adjudication.characterProposalId);
1673
+ if (!character || (['failed', 'deferred'].includes(adjudication.outcome) && adjudication.actionIds.length !== 0)) {
1674
+ return false;
1675
+ }
1676
+ if (adjudication.outcome === 'succeeded'
1677
+ && character.attemptedActions.length > 0
1678
+ && adjudication.actionIds.length === 0)
1679
+ return false;
1680
+ for (const actionId of adjudication.actionIds) {
1681
+ const action = actions.get(actionId);
1682
+ if (!action
1683
+ || action.sourceCharacterProposalId !== character.proposalId
1684
+ || action.actorId !== character.actorId)
1685
+ return false;
1686
+ adjudicatedActionIds.push(actionId);
1687
+ }
1688
+ }
1689
+ if (!unique(adjudicatedActionIds))
1690
+ return false;
1691
+ const player = state.agents.find(agent => agent.humanControlled);
1692
+ const playerAdjudication = proposal.playerAdjudication;
1693
+ if ((entry.playerActionId === null) !== (playerAdjudication === null))
1694
+ return false;
1695
+ const playerActionIds = proposal.domainActions
1696
+ .filter(action => action.sourcePlayerActionId !== undefined)
1697
+ .map(action => action.id);
1698
+ if (entry.playerActionId === null) {
1699
+ if (playerActionIds.length !== 0)
1700
+ return false;
1701
+ }
1702
+ else {
1703
+ if (!player || !playerAdjudication)
1704
+ return false;
1705
+ if (playerAdjudication.playerActionId !== entry.playerActionId
1706
+ || (playerAdjudication.outcome === 'failed' && playerAdjudication.actionIds.length !== 0 && entry.playerIntent === undefined)
1707
+ || (entry.playerIntent !== undefined && (state.agencyVersion !== 'emergent-v1'
1708
+ || playerAdjudication.actionIds.length === 0
1709
+ || proposal.domainActions.filter(action => action.sourcePlayerActionId === entry.playerActionId)
1710
+ .some(action => action.mechanic !== 'act-freely' || JSON.stringify(action.parameters?.intent) !== JSON.stringify({ text: entry.playerIntent }))))
1711
+ || !sameSet(playerActionIds, playerAdjudication.actionIds))
1712
+ return false;
1713
+ }
1714
+ return proposal.domainActions.every((action) => {
1715
+ if (!actors.has(action.actorId ?? '') && action.actorId !== undefined)
1716
+ return false;
1717
+ if (action.actorId === undefined) {
1718
+ return action.sourceCharacterProposalId === undefined
1719
+ && action.sourceAttemptedActionId === undefined
1720
+ && action.sourcePlayerActionId === undefined
1721
+ && !adjudicatedActionIds.includes(action.id)
1722
+ && !playerActionIds.includes(action.id);
1723
+ }
1724
+ if (actors.get(action.actorId)?.humanControlled === true) {
1725
+ return entry.playerActionId !== null
1726
+ && action.sourcePlayerActionId === entry.playerActionId
1727
+ && action.sourceCharacterProposalId === undefined
1728
+ && action.sourceAttemptedActionId === undefined
1729
+ && playerAdjudication?.actionIds.includes(action.id) === true;
1730
+ }
1731
+ const character = characters.get(action.sourceCharacterProposalId ?? '');
1732
+ const attempted = character?.attemptedActions.find(candidate => (candidate.id === action.sourceAttemptedActionId));
1733
+ return action.sourcePlayerActionId === undefined
1734
+ && character?.actorId === action.actorId
1735
+ && attempted?.actorId === action.actorId
1736
+ && attempted.mechanic === action.mechanic
1737
+ && attempted.targetActorId === action.targetActorId
1738
+ && adjudicatedActionIds.includes(action.id);
1739
+ });
1740
+ });
1741
+ return historyIsValid && state.agents.every((agent) => {
1742
+ const cursor = cursors.get(agent.actorId);
1743
+ return cursor !== undefined
1744
+ && sameSet([...cursor.goals.keys()], agent.goals.map(goal => goal.id))
1745
+ && agent.goals.every(goal => cursor.goals.get(goal.id) === goal.status)
1746
+ && sameSet([...cursor.beliefs], agent.beliefs.map(belief => belief.id))
1747
+ && sameSet([...cursor.memories], agent.memories.map(memory => memory.id))
1748
+ && sameJson(cursor.currentIntent, agent.currentIntent);
1749
+ });
1750
+ }
1751
+ function deriveHistoryKind(entry) {
1752
+ if (entry.gmProposal.ending !== null)
1753
+ return 'ending';
1754
+ if (entry.playerActionId !== null)
1755
+ return 'player-action';
1756
+ if (entry.gmProposal.domainActions.some(action => (entry.gmProposal.agentUpdates.filter(update => (update.sourceActionIds.includes(action.id))).length > 1)))
1757
+ return 'agent-interaction';
1758
+ if (entry.gmProposal.domainActions.some(action => action.actorId !== undefined)) {
1759
+ return 'agent-action';
1760
+ }
1761
+ return 'gm-event';
1762
+ }
1763
+ function historicalActionParticipantIds(action, effects, knownObjects) {
1764
+ const actorIds = new Set();
1765
+ if (action.actorId !== undefined)
1766
+ actorIds.add(action.actorId);
1767
+ if (action.targetActorId !== undefined)
1768
+ actorIds.add(action.targetActorId);
1769
+ const referencedIds = new Set(collectStringLeaves(action.parameters));
1770
+ const effectObjects = effects.flatMap(effect => (effect.actionId === action.id && effect.operation === 'object.put' ? [effect.object] : []));
1771
+ for (const object of effectObjects)
1772
+ referencedIds.add(object.id);
1773
+ const objectById = new Map(knownObjects.map(object => [object.id, object]));
1774
+ for (const object of effectObjects)
1775
+ objectById.set(object.id, object);
1776
+ for (let pass = 0; pass <= objectById.size; pass += 1) {
1777
+ let changed = false;
1778
+ for (const object of objectById.values()) {
1779
+ const reachesAffected = object.links.some(link => (link.targetType === 'object' && referencedIds.has(link.targetId)));
1780
+ if (reachesAffected && !referencedIds.has(object.id)) {
1781
+ referencedIds.add(object.id);
1782
+ changed = true;
1783
+ }
1784
+ if (!referencedIds.has(object.id))
1785
+ continue;
1786
+ for (const link of object.links) {
1787
+ if (link.targetType === 'object' && !referencedIds.has(link.targetId)) {
1788
+ referencedIds.add(link.targetId);
1789
+ changed = true;
1790
+ }
1791
+ }
1792
+ }
1793
+ if (!changed)
1794
+ break;
1795
+ }
1796
+ for (const objectId of referencedIds) {
1797
+ const object = objectById.get(objectId);
1798
+ if (!object)
1799
+ continue;
1800
+ if (object.ownerActorId !== null)
1801
+ actorIds.add(object.ownerActorId);
1802
+ for (const link of object.links) {
1803
+ if (link.targetType === 'actor')
1804
+ actorIds.add(link.targetId);
1805
+ }
1806
+ }
1807
+ return [...actorIds];
1808
+ }
1809
+ function collectStringLeaves(value) {
1810
+ if (typeof value === 'string')
1811
+ return [value];
1812
+ if (Array.isArray(value))
1813
+ return value.flatMap(collectStringLeaves);
1814
+ if (value === null || typeof value !== 'object')
1815
+ return [];
1816
+ return Object.values(value).flatMap(collectStringLeaves);
1817
+ }
1818
+ function validHistoricalAgentUpdate(update, actors, cursors, allowedEventIds, actions, effects, graphAtAction, continues, agencyVersion) {
1819
+ const agent = actors.get(update.actorId);
1820
+ const cursor = cursors.get(update.actorId);
1821
+ if (!agent || !cursor)
1822
+ return false;
1823
+ const nextGoalStatuses = new Map(cursor.goals);
1824
+ for (const goal of update.goalUpdates) {
1825
+ if (goal.status !== undefined)
1826
+ nextGoalStatuses.set(goal.goalId, goal.status);
1827
+ }
1828
+ for (const goal of update.goalsToAppend)
1829
+ nextGoalStatuses.set(goal.id, goal.status);
1830
+ const nextBeliefIds = new Set(cursor.beliefs);
1831
+ for (const belief of update.beliefsToAppend)
1832
+ nextBeliefIds.add(belief.id);
1833
+ const nextMemoryIds = new Set(cursor.memories);
1834
+ for (const memory of update.memoriesToAppend)
1835
+ nextMemoryIds.add(memory.id);
1836
+ const relationshipIds = new Set(agent.relationships.map(item => item.targetActorId));
1837
+ const evidenceIsValid = (eventIds) => (unique(eventIds) && eventIds.every(eventId => allowedEventIds.includes(eventId)));
1838
+ const currentEventId = allowedEventIds.at(-1);
1839
+ const nextIntent = update.nextIntent === null
1840
+ ? (continues && agencyVersion !== 'emergent-v1' ? cursor.currentIntent : null)
1841
+ : update.nextIntent;
1842
+ const valid = unique(update.goalUpdates.map(goal => goal.goalId))
1843
+ && update.goalUpdates.every(goal => cursor.goals.has(goal.goalId))
1844
+ && unique(update.goalsToAppend.map(goal => goal.id))
1845
+ && update.goalsToAppend.every((goal) => {
1846
+ const finalGoal = agent.goals.find(candidate => candidate.id === goal.id);
1847
+ return goal.status === 'active'
1848
+ && !cursor.goals.has(goal.id)
1849
+ && finalGoal?.description === goal.description
1850
+ && finalGoal.visibility === goal.visibility;
1851
+ })
1852
+ && unique(update.beliefUpdates.map(belief => belief.beliefId))
1853
+ && update.beliefUpdates.every(belief => (cursor.beliefs.has(belief.beliefId)
1854
+ && evidenceIsValid(belief.evidenceEventIds)
1855
+ && belief.evidenceEventIds.includes(currentEventId ?? '')))
1856
+ && unique(update.beliefsToAppend.map(belief => belief.id))
1857
+ && update.beliefsToAppend.every((belief) => {
1858
+ const finalBelief = agent.beliefs.find(candidate => candidate.id === belief.id);
1859
+ return belief.evidenceEventIds.length > 0
1860
+ && !cursor.beliefs.has(belief.id)
1861
+ && evidenceIsValid(belief.evidenceEventIds)
1862
+ && belief.evidenceEventIds.includes(currentEventId ?? '')
1863
+ && finalBelief?.subject === belief.subject
1864
+ && finalBelief.claim === belief.claim
1865
+ && finalBelief.visibility === belief.visibility;
1866
+ })
1867
+ && unique(update.relationshipDeltas.map(item => item.targetActorId))
1868
+ && update.relationshipDeltas.every(item => (relationshipIds.has(item.targetActorId)
1869
+ && (agencyVersion === 'emergent-v1' || update.sourceActionIds.some((actionId) => {
1870
+ const action = actions.get(actionId);
1871
+ return action !== undefined && historicalActionParticipantIds(action, effects, graphAtAction(actionId)).includes(item.targetActorId);
1872
+ }))))
1873
+ && unique(update.memoriesToAppend.map(memory => memory.id))
1874
+ && update.memoriesToAppend.every((memory) => {
1875
+ const finalMemory = agent.memories.find(candidate => candidate.id === memory.id);
1876
+ return !cursor.memories.has(memory.id)
1877
+ && allowedEventIds.includes(memory.eventId)
1878
+ && sameJson(finalMemory, memory);
1879
+ })
1880
+ && Object.keys(update.resourceDeltas).every(resourceId => (Object.hasOwn(agent.resources, resourceId)))
1881
+ && (agencyVersion === 'emergent-v1' || !continues || agent.humanControlled || ([...nextGoalStatuses.values()].some(status => status === 'active')
1882
+ && !(cursor.currentIntent !== null
1883
+ && nextGoalStatuses.get(cursor.currentIntent.goalId) !== 'active'
1884
+ && update.nextIntent === null)))
1885
+ && (agencyVersion === 'emergent-v1' || nextIntent === null || (nextGoalStatuses.get(nextIntent.goalId) === 'active'
1886
+ && agent.capabilities.includes(nextIntent.mechanic)
1887
+ && (nextIntent.targetActorId === undefined
1888
+ || (actors.has(nextIntent.targetActorId)
1889
+ && nextIntent.targetActorId !== agent.actorId))));
1890
+ if (!valid)
1891
+ return false;
1892
+ cursor.goals = nextGoalStatuses;
1893
+ cursor.beliefs = nextBeliefIds;
1894
+ cursor.memories = nextMemoryIds;
1895
+ cursor.currentIntent = nextIntent;
1896
+ return true;
1897
+ }
1898
+ function leaksPrivateText(state) {
1899
+ const privateIdentifiers = state.agents.flatMap(agent => [
1900
+ ...agent.goals.filter(item => item.visibility === 'private').map(item => item.id),
1901
+ ...agent.beliefs.filter(item => item.visibility === 'private').map(item => item.id),
1902
+ ...agent.memories.filter(item => item.visibility === 'private').map(item => item.id),
1903
+ ]).map(normalizePrivateText);
1904
+ const privatePhrases = state.agents.flatMap(agent => [
1905
+ ...agent.goals.filter(item => item.visibility === 'private').map(item => item.description),
1906
+ ...agent.beliefs
1907
+ .filter(item => item.visibility === 'private')
1908
+ // Topic secrecy needs the domain vocabulary; policy validation owns that check.
1909
+ .map(item => item.claim),
1910
+ ...agent.memories.filter(item => item.visibility === 'private').map(item => item.summary),
1911
+ ...agent.relationships.filter(item => item.visibility === 'private').flatMap(item => item.conflictNotes),
1912
+ ...(agent.currentIntent !== null && agent.goals.some(goal => (goal.id === agent.currentIntent?.goalId && goal.visibility === 'private')) ? [agent.currentIntent.summary] : []),
1913
+ ])
1914
+ .map(normalizePrivateText)
1915
+ .filter(text => text.length >= 8 && text !== 'private knowledge');
1916
+ const frameTexts = collectStringValues(state.frame).map(normalizePrivateText);
1917
+ return privatePhrases.some(secret => frameTexts.some(text => text.includes(secret)))
1918
+ || privateIdentifiers.some(identifier => frameTexts.some(text => (identifier.length > 0 && ` ${text} `.includes(` ${identifier} `))));
1919
+ }
1920
+ function collectStringValues(value, depth = 0) {
1921
+ if (depth > 16)
1922
+ return [];
1923
+ if (typeof value === 'string')
1924
+ return [value];
1925
+ if (Array.isArray(value)) {
1926
+ return value.flatMap(item => collectStringValues(item, depth + 1));
1927
+ }
1928
+ const record = jsonRecord(value);
1929
+ return record === null
1930
+ ? []
1931
+ : Object.values(record).flatMap(item => collectStringValues(item, depth + 1));
1932
+ }
1933
+ function normalizePrivateText(value) {
1934
+ return value
1935
+ .normalize('NFKC')
1936
+ .toLocaleLowerCase()
1937
+ .replace(/[^\p{L}\p{N}]+/gu, ' ')
1938
+ .trim();
1939
+ }
1940
+ function normalizeBoundedJson(value) {
1941
+ try {
1942
+ const serialized = JSON.stringify(value);
1943
+ if (serialized === undefined
1944
+ || Buffer.byteLength(serialized, 'utf8') > MAX_DYNAMIC_STATE_BYTES) {
1945
+ throw new Error('Dynamic state exceeds its byte bound');
1946
+ }
1947
+ return JSON.parse(serialized);
1948
+ }
1949
+ catch {
1950
+ fail('state-shape-invalid', 'Dynamic state must be bounded JSON');
1951
+ }
1952
+ }
1953
+ function unique(values) {
1954
+ return new Set(values).size === values.length;
1955
+ }
1956
+ function sameSet(left, right) {
1957
+ return left.length === right.length && left.every(value => right.includes(value));
1958
+ }
1959
+ function sameJson(left, right) {
1960
+ return isDeepStrictEqual(left, right);
1961
+ }
1962
+ function fail(code, message) {
1963
+ throw new DynamicStateContractError(code, message);
1964
+ }
1965
+ export function asDynamicStateJson(state) {
1966
+ return parseDynamicSimulationState(state);
1967
+ }