@zergai/ztc 0.26.6-dev.202611240947 → 0.27.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 (268) hide show
  1. package/README.md +629 -167
  2. package/RUST_THIRD_PARTY_LICENSES.txt +5 -5
  3. package/bin/zmux-darwin-arm64 +0 -0
  4. package/bin/zmux-linux-x64 +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-tui-linux-x64 +0 -0
  12. package/bin/zterm-darwin-arm64 +2 -2
  13. package/dist/App.js +6 -1
  14. package/dist/agent/agent.d.ts +21 -15
  15. package/dist/agent/agent.js +389 -163
  16. package/dist/agent/backends/codex_app_server.d.ts +7 -1
  17. package/dist/agent/backends/codex_app_server.js +11 -1
  18. package/dist/agent/backends/gemini.js +22 -8
  19. package/dist/agent/commands/batch.js +8 -0
  20. package/dist/agent/commands/config.js +10 -0
  21. package/dist/agent/commands/environment.js +5 -5
  22. package/dist/agent/commands/goal.d.ts +1 -0
  23. package/dist/agent/commands/goal.js +2 -1
  24. package/dist/agent/commands/index.js +2 -1
  25. package/dist/agent/commands/manifest.js +4 -0
  26. package/dist/agent/commands/optimize.js +5 -2
  27. package/dist/agent/commands/pane_cli.d.ts +29 -0
  28. package/dist/agent/commands/pane_cli.js +303 -0
  29. package/dist/agent/commands/settings.js +13 -3
  30. package/dist/agent/commands/shannon.js +8 -0
  31. package/dist/agent/commands/update.js +15 -3
  32. package/dist/agent/commands/zerg.js +31 -1
  33. package/dist/agent/commands/ztc_pane.js +3 -1
  34. package/dist/agent/factory.d.ts +4 -0
  35. package/dist/agent/factory.js +11 -1
  36. package/dist/agent/loop_policy.d.ts +42 -5
  37. package/dist/agent/loop_policy.js +206 -3
  38. package/dist/agent/runtime/command_jobs.d.ts +5 -0
  39. package/dist/agent/runtime/command_jobs.js +241 -31
  40. package/dist/agent/runtime/command_wait.d.ts +2 -0
  41. package/dist/agent/runtime/command_wait.js +1 -0
  42. package/dist/agent/runtime/done_report.d.ts +18 -0
  43. package/dist/agent/runtime/done_report.js +130 -0
  44. package/dist/agent/runtime/execution_context.js +4 -1
  45. package/dist/agent/runtime/failure_cause.d.ts +2 -0
  46. package/dist/agent/runtime/failure_cause.js +35 -0
  47. package/dist/agent/runtime/policy.d.ts +14 -2
  48. package/dist/agent/runtime/policy.js +104 -12
  49. package/dist/agent/runtime/quiet_job.d.ts +18 -0
  50. package/dist/agent/runtime/quiet_job.js +48 -0
  51. package/dist/agent/runtime/recovery.d.ts +1 -5
  52. package/dist/agent/runtime/recovery.js +2 -44
  53. package/dist/agent/runtime/tool_runtime.d.ts +1 -0
  54. package/dist/agent/runtime/tool_runtime.js +2 -0
  55. package/dist/agent/subagent.js +6 -1
  56. package/dist/agent/tools/deferred.js +1 -0
  57. package/dist/agent/tools/index.d.ts +2 -0
  58. package/dist/agent/tools/index.js +1 -0
  59. package/dist/agent/tools/outcome.d.ts +15 -0
  60. package/dist/agent/tools/outcome.js +107 -0
  61. package/dist/agent/tools/pane.d.ts +2 -1
  62. package/dist/agent/tools/pane.js +21 -3
  63. package/dist/agent/tools/registry.js +2 -0
  64. package/dist/agent/tools/shell.d.ts +1 -0
  65. package/dist/agent/tools/shell.js +128 -17
  66. package/dist/agent/tools/sim_domain_tools.js +4 -2
  67. package/dist/agent/tools/supervision.js +4 -2
  68. package/dist/agent/tools/types.d.ts +3 -0
  69. package/dist/app/command_context.js +5 -9
  70. package/dist/app/conversation_compaction.d.ts +4 -2
  71. package/dist/app/conversation_compaction.js +16 -5
  72. package/dist/app/headless_shell_mode.d.ts +14 -0
  73. package/dist/app/headless_shell_mode.js +7 -0
  74. package/dist/app/hosted_resident.d.ts +356 -0
  75. package/dist/app/hosted_resident.js +677 -0
  76. package/dist/app/restart.js +11 -2
  77. package/dist/app/session_manager.d.ts +5 -0
  78. package/dist/app/session_manager.js +21 -6
  79. package/dist/app/session_messages.js +6 -6
  80. package/dist/app/workspace_layout_controller.js +7 -0
  81. package/dist/batch/worktree.d.ts +10 -0
  82. package/dist/batch/worktree.js +15 -0
  83. package/dist/bench/registry.js +4 -2
  84. package/dist/cli_args.js +1 -1
  85. package/dist/cli_main.js +80 -10
  86. package/dist/cli_ratatui.d.ts +75 -0
  87. package/dist/cli_ratatui.js +485 -84
  88. package/dist/components/InputArea.js +4 -4
  89. package/dist/config/execution.d.ts +10 -0
  90. package/dist/config/execution.js +10 -0
  91. package/dist/config/hosted_runtime.d.ts +4 -1
  92. package/dist/config/hosted_runtime.js +4 -1
  93. package/dist/config/permission_pin.d.ts +34 -2
  94. package/dist/config/permission_pin.js +52 -2
  95. package/dist/config/person_command_policy.d.ts +38 -0
  96. package/dist/config/person_command_policy.js +11 -0
  97. package/dist/config/profiles.d.ts +21 -0
  98. package/dist/config/profiles.js +56 -2
  99. package/dist/config/types.d.ts +4 -1
  100. package/dist/config.js +34 -19
  101. package/dist/desktop/daily/codex_exec_adapter.js +7 -2
  102. package/dist/desktop/daily/desktop_wiring.d.ts +7 -1
  103. package/dist/desktop/daily/desktop_wiring.js +11 -3
  104. package/dist/desktop/daily/recipes.js +20 -4
  105. package/dist/desktop/health.d.ts +24 -0
  106. package/dist/desktop/health.js +151 -0
  107. package/dist/desktop/native_dialogs.d.ts +37 -0
  108. package/dist/desktop/native_dialogs.js +105 -0
  109. package/dist/diagnostics/session_export.d.ts +1 -0
  110. package/dist/diagnostics/session_export.js +28 -0
  111. package/dist/embedded/registry.js +4 -2
  112. package/dist/emulation/tool_adapters.js +9 -4
  113. package/dist/emulation/ztc_addendum.js +3 -0
  114. package/dist/headless.d.ts +11 -4
  115. package/dist/headless.js +99 -34
  116. package/dist/headless_approval.d.ts +6 -0
  117. package/dist/headless_cli.js +1 -1
  118. package/dist/hooks/runner.js +7 -6
  119. package/dist/library.d.ts +4 -0
  120. package/dist/library.js +3 -0
  121. package/dist/mcp/client.js +3 -3
  122. package/dist/modes/registry.js +13 -4
  123. package/dist/onboarding/setup_environment.js +13 -1
  124. package/dist/optimize/adapters/kernelbench.js +88 -10
  125. package/dist/optimize/adapters/types.d.ts +5 -0
  126. package/dist/optimize/executor.js +21 -0
  127. package/dist/panes/cli_install.d.ts +54 -0
  128. package/dist/panes/cli_install.js +157 -0
  129. package/dist/panes/model_catalog.js +3 -0
  130. package/dist/panes/new_pane_choices.d.ts +6 -2
  131. package/dist/panes/new_pane_choices.js +24 -12
  132. package/dist/panes/pane_cli_launch.d.ts +50 -0
  133. package/dist/panes/pane_cli_launch.js +124 -0
  134. package/dist/panes/pane_clis.d.ts +171 -0
  135. package/dist/panes/pane_clis.js +325 -0
  136. package/dist/panes/person_only_panes.d.ts +45 -0
  137. package/dist/panes/person_only_panes.js +117 -0
  138. package/dist/plugin/simulation_living.js +0 -2
  139. package/dist/plugin/simulation_living_engine.d.ts +1 -0
  140. package/dist/plugin/simulation_living_engine.js +1 -0
  141. package/dist/plugin/simulation_living_labels.d.ts +3 -0
  142. package/dist/plugin/simulation_living_labels.js +2 -0
  143. package/dist/router_auth.js +12 -1
  144. package/dist/session.js +26 -1
  145. package/dist/simulation/art/gemini_image.js +11 -5
  146. package/dist/simulation/domains/loader.js +25 -3
  147. package/dist/simulation/living/cold.d.ts +23 -0
  148. package/dist/simulation/living/cold.js +41 -0
  149. package/dist/simulation/living/context.d.ts +591 -1283
  150. package/dist/simulation/living/context.js +378 -244
  151. package/dist/simulation/living/contradictions.d.ts +14 -0
  152. package/dist/simulation/living/contradictions.js +282 -0
  153. package/dist/simulation/living/core/ids.d.ts +53 -0
  154. package/dist/simulation/living/core/ids.js +39 -0
  155. package/dist/simulation/living/core/kind.d.ts +20 -0
  156. package/dist/simulation/living/core/kind.js +15 -0
  157. package/dist/simulation/living/core/laws.d.ts +179 -0
  158. package/dist/simulation/living/core/laws.js +184 -0
  159. package/dist/simulation/living/core/ops.d.ts +257 -0
  160. package/dist/simulation/living/core/ops.js +34 -0
  161. package/dist/simulation/living/definer.d.ts +17 -1
  162. package/dist/simulation/living/definer.js +130 -51
  163. package/dist/simulation/living/definition.d.ts +174 -65
  164. package/dist/simulation/living/definition.js +287 -180
  165. package/dist/simulation/living/director.d.ts +80 -0
  166. package/dist/simulation/living/director.js +363 -0
  167. package/dist/simulation/living/frame.d.ts +108 -21
  168. package/dist/simulation/living/frame.js +111 -66
  169. package/dist/simulation/living/identifiers.d.ts +0 -1
  170. package/dist/simulation/living/identifiers.js +0 -3
  171. package/dist/simulation/living/index.d.ts +18 -9
  172. package/dist/simulation/living/index.js +18 -9
  173. package/dist/simulation/living/inference.d.ts +92 -50
  174. package/dist/simulation/living/inference.js +319 -175
  175. package/dist/simulation/living/knowledge.d.ts +28 -0
  176. package/dist/simulation/living/knowledge.js +73 -0
  177. package/dist/simulation/living/library.json +1177 -0
  178. package/dist/simulation/living/mechanics.d.ts +31 -34
  179. package/dist/simulation/living/mechanics.js +222 -138
  180. package/dist/simulation/living/model-input.d.ts +6 -3
  181. package/dist/simulation/living/model-input.js +18 -26
  182. package/dist/simulation/living/open-world.d.ts +74 -94
  183. package/dist/simulation/living/open-world.js +151 -30
  184. package/dist/simulation/living/phrases.d.ts +3 -0
  185. package/dist/simulation/living/phrases.js +37 -0
  186. package/dist/simulation/living/phrases.json +560 -0
  187. package/dist/simulation/living/projection.d.ts +316 -2
  188. package/dist/simulation/living/projection.js +50 -2
  189. package/dist/simulation/living/prompts/example-spec.json +11 -0
  190. package/dist/simulation/living/prompts/role-text.json +14 -0
  191. package/dist/simulation/living/prompts.d.ts +5 -0
  192. package/dist/simulation/living/prompts.js +275 -0
  193. package/dist/simulation/living/recall.d.ts +2 -2
  194. package/dist/simulation/living/reduce.d.ts +51 -14
  195. package/dist/simulation/living/reduce.js +941 -579
  196. package/dist/simulation/living/replay.d.ts +5 -4
  197. package/dist/simulation/living/replay.js +10 -9
  198. package/dist/simulation/living/runtime.d.ts +135 -25
  199. package/dist/simulation/living/runtime.js +1641 -583
  200. package/dist/simulation/living/scale.d.ts +96 -0
  201. package/dist/simulation/living/scale.js +124 -0
  202. package/dist/simulation/living/script.d.ts +5 -0
  203. package/dist/simulation/living/script.js +115 -0
  204. package/dist/simulation/living/shared-kinds.d.ts +4 -11
  205. package/dist/simulation/living/shared-kinds.js +11 -81
  206. package/dist/simulation/living/space.d.ts +14 -0
  207. package/dist/simulation/living/space.js +132 -0
  208. package/dist/simulation/living/state.d.ts +100 -0
  209. package/dist/simulation/living/state.js +393 -0
  210. package/dist/simulation/living/types.d.ts +829 -512
  211. package/dist/simulation/living/types.js +162 -187
  212. package/dist/simulation/living/world-rules.d.ts +100 -0
  213. package/dist/simulation/living/world-rules.js +267 -0
  214. package/dist/simulation/plugins/loader.js +11 -0
  215. package/dist/skills/loader.js +4 -0
  216. package/dist/tools.d.ts +1 -0
  217. package/dist/tools.js +1 -0
  218. package/dist/ui/ratatui/headless_pane_manager.d.ts +4 -1
  219. package/dist/ui/ratatui/headless_pane_manager.js +13 -9
  220. package/dist/ui/ratatui/pane_relay.js +29 -0
  221. package/dist/ui/ratatui/pane_type.d.ts +10 -0
  222. package/dist/ui/ratatui/pane_type.js +11 -0
  223. package/dist/ui/ratatui/process.d.ts +30 -0
  224. package/dist/ui/ratatui/process.js +133 -19
  225. package/dist/ui/ratatui/protocol.d.ts +124 -2
  226. package/dist/ui/ratatui/protocol.js +35 -0
  227. package/dist/ui/ratatui/relay_policy.js +3 -0
  228. package/dist/ui/ratatui/ztc_launch_trust.d.ts +2 -1
  229. package/dist/ui/ratatui/ztc_launch_trust.js +8 -1
  230. package/dist/ui/terminal_image.d.ts +12 -0
  231. package/dist/ui/terminal_image.js +21 -1
  232. package/dist/utils/codex_project_trust.d.ts +19 -0
  233. package/dist/utils/codex_project_trust.js +37 -0
  234. package/dist/utils/compaction.js +103 -20
  235. package/dist/utils/git_program_files.d.ts +19 -12
  236. package/dist/utils/git_program_files.js +411 -83
  237. package/dist/utils/host_shell.d.ts +10 -1
  238. package/dist/utils/host_shell.js +14 -1
  239. package/dist/utils/mid_turn_compaction.d.ts +2 -0
  240. package/dist/utils/mid_turn_compaction.js +2 -0
  241. package/dist/utils/models.js +6 -1
  242. package/dist/utils/sandbox.d.ts +109 -8
  243. package/dist/utils/sandbox.js +981 -187
  244. package/dist/utils/shell.d.ts +2 -0
  245. package/dist/utils/shell.js +10 -4
  246. package/dist/utils/subprocess_env.d.ts +47 -11
  247. package/dist/utils/subprocess_env.js +107 -15
  248. package/dist/utils/system_ps.d.ts +8 -0
  249. package/dist/utils/system_ps.js +39 -7
  250. package/dist/utils/unattended_compaction.d.ts +9 -0
  251. package/dist/utils/unattended_compaction.js +13 -0
  252. package/dist/utils/ztc_own_state.d.ts +8 -5
  253. package/dist/utils/ztc_own_state.js +17 -11
  254. package/dist/web/mirror_client.js +1 -0
  255. package/dist/web/mirror_stream.d.ts +50 -6
  256. package/dist/web/mirror_stream.js +160 -15
  257. package/dist/workflows/registry.js +3 -1
  258. package/dist/workspace/controller.js +12 -0
  259. package/dist/workspace_collision.d.ts +3 -0
  260. package/dist/workspace_collision.js +14 -1
  261. package/dist/workspace_session_context.js +2 -1
  262. package/dist/zlm-embed.mjs +3823 -1970
  263. package/node_modules/@zerg/model-contracts/README.md +16 -4
  264. package/node_modules/@zerg/model-contracts/index.js +6 -1
  265. package/npm-shrinkwrap.json +1 -1
  266. package/package.json +42 -24
  267. package/packages/model-contracts/README.md +16 -4
  268. package/packages/model-contracts/index.js +6 -1
@@ -1,11 +1,19 @@
1
- import { BOUNDED_IDENTIFIERS_ENGINE, generatedId } from './identifiers.js';
2
- import { current, isDraft, produce, setAutoFreeze } from 'immer';
1
+ import { generatedId } from './identifiers.js';
2
+ import { isDraft, produce, setAutoFreeze } from 'immer';
3
3
  import { observedObjectIds, observedSummary, visibleTo, witnessed } from './projection.js';
4
- import { valueMatchesType } from './open-world.js';
5
- import { ACT_GATE_ENGINE, GLOBAL_SIGNAL_CHANNEL, LAZY_METER_ENGINE, LOCAL_RECOVERY_ENGINE, plain, PEEK_ENTITY, readEntity, advanceScopedEntities, applyEventChanges, currentValue, dropStalePredictions, indexPlaceless, insertScheduled, reindexPlaceless, keepPassedCrossings, predictCrossings, blockedByGate, gatesAgainst, heldHere, normViolationsFor, runTriggers, signalNotice, signalsFor, spreadLevel } from './mechanics.js';
6
- import { STABLE_CONVERSATION_ENGINE, ADDED_LINE_ENGINE, AUTHORS_ENGINE, AVERTED_ENGINE, AWAY_REPLY_ENGINE, SEEN_AT_EVENTS_ENGINE, THINGS_SEEN_ENGINE, VOTE_CLOSES_ENGINE, VOTE_OPEN_MINUTES, isNight, COUNT_ONLY_ENGINE, REMINDER_ENGINE, WHOLE_SIDES_ENGINE, PLAYER_REST_ENGINE, SIDE_ORDER_ENGINE, OPEN_NOW_ENGINE, SEEN_WHERE_ENGINE, REST_ENGINE, UNHELD_ENGINE, WHOLE_TEXT_ENGINE, AWAY_APART_ENGINE, CHRONICLE_ENGINE, CONDITION_SIDES_ENGINE, DEADLINE_ENGINE, LEFT_UNSEEN_ENGINE, MAX_ADDED_LINE, VOTES_ENGINE, MAX_LINE, PROMISE_IMPORTANCE, PROMISE_LEAD_MINUTES, IDENTITY_ENGINE, STALL_ENGINE, STALL_MINUTES, SILENCE_ENGINE, WRITING_GROWS_ENGINE, MAX_TEXT, clockLabel, UNANSWERED_LINES, UNANSWERED_MINUTES, UNANSWERED_RESET_MINUTES, NEWCOMER_ENGINE, REQUEST_TIME_ENGINE, LivingWorldError, MAX_CHRONICLE, MAX_THING_NOTES, THING_NOTE_TEXT, SHOWN_CLOCK_ENGINE, THING_MEMORY_ENGINE, WALK_OFF_ENGINE, entityRefs, eventSchema, sealLivingIndexes, GONE_AT_ENGINE, PROBLEM_VIEW_ENGINE } from './types.js';
7
- import { BOUNDED_PERSON_RECORDS_ENGINE, MAX_WORKING_BELIEFS, MAX_CLOSED_COMMITMENTS, MAX_OPEN_COMMITMENTS } from './types.js';
8
- import { namesPerson, neverHeld, oneEachSlot, sealedPaper } from './shared-kinds.js';
4
+ import { entitySchema, narrowsKindRevision, valueMatchesType } from './open-world.js';
5
+ import { checkKindDefinition } from './world-rules.js';
6
+ import { plain, PEEK_ENTITY, readEntity, applyEventChanges, currentValue, dropStalePredictions, indexPlaceless, insertScheduled, reindexPlaceless, keepPassedCrossings, predictCrossings, blockedByGate, gatesAgainst, heldHere, lastingChangeToken, normViolationsFor, runTriggers, signalNotice, signalsFor, spreadLevel } from './mechanics.js';
7
+ import { holds, moveWithin, placesWithin, siteOf } from './space.js';
8
+ import { wordsOf } from './contradictions.js';
9
+ import { MAX_ADDED_LINE, MAX_LINE, PROMISE_IMPORTANCE, MAX_TEXT, REPEAT_ASK_EARLIER, REPEAT_ASK_OVERLAP, UNANSWERED_LINES, LivingWorldError, THING_NOTE_TEXT, entityRefs, eventSchema } from './types.js';
10
+ import { BOUNDS, boundState, capsBoundaryOf, foldOf, owedSchedule, sealState } from './state.js';
11
+ import { cueMatches, evaluateCondition, evaluateTerm, subjectId } from './core/laws.js';
12
+ import { MAX_OPEN_COMMITMENTS } from './types.js';
13
+ import { pace, restingAt } from './scale.js';
14
+ import { phrase } from './phrases.js';
15
+ import { namesPerson, neverHeld, oneEachSlot } from './shared-kinds.js';
16
+ import { DIRECTOR_CHECK_INTENT } from './director.js';
9
17
  // The reducer is the replay oracle. It is pure: the same state and event always give
10
18
  // the same next state, and nothing here consults a model, a clock, or randomness.
11
19
  setAutoFreeze(false);
@@ -43,15 +51,37 @@ function entityOverlay(entities) {
43
51
  });
44
52
  return { table, changes: () => changed };
45
53
  }
46
- // Who is in a place now; someone who has left the world, or is away for a while, is nowhere.
54
+ function placeChain(places, placeId) {
55
+ const chain = new Set([placeId]);
56
+ let outer = places[placeId]?.containerId ?? null;
57
+ while (outer !== null && places[outer] !== undefined && !chain.has(outer)) {
58
+ chain.add(outer);
59
+ outer = places[outer].containerId ?? null;
60
+ }
61
+ let grew = true;
62
+ while (grew) {
63
+ grew = false;
64
+ for (const place of Object.values(places)) {
65
+ if (place.containerId !== null && place.containerId !== undefined && chain.has(place.containerId) && !chain.has(place.id)) {
66
+ chain.add(place.id);
67
+ grew = true;
68
+ }
69
+ }
70
+ }
71
+ return chain;
72
+ }
47
73
  export function peopleAt(state, placeId) {
48
- return Object.values(state.people).filter(person => person.placeId === placeId && person.departed === undefined && person.away === undefined).map(person => person.id).sort();
74
+ const chain = placeChain(state.places, placeId);
75
+ return Object.values(state.people).filter(person => chain.has(person.placeId) && person.departed === undefined && person.offstage === undefined)
76
+ .sort((left, right) => (left.arrivedSeq ?? 0) - (right.arrivedSeq ?? 0)
77
+ || (left.id === state.playerId ? -1 : right.id === state.playerId ? 1 : 0)
78
+ || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
79
+ .map(person => person.id);
49
80
  }
50
81
  export function witnessesFor(state, event) {
51
82
  const present = event.placeId === null ? [] : peopleAt(state, event.placeId);
52
- if (event.actorId !== null && !present.includes(event.actorId))
53
- return [...present, event.actorId].sort();
54
- return present;
83
+ const wanted = new Set(event.actorId === null ? present : [...present, event.actorId]);
84
+ return Object.keys(state.people).filter(id => wanted.has(id));
55
85
  }
56
86
  // Who notices an event without being in the room: with 'nearby' reach, everyone in a
57
87
  // connected place; with 'everywhere', everyone elsewhere; and whoever is in a room that
@@ -60,10 +90,13 @@ export function witnessesFor(state, event) {
60
90
  export function nearbyFor(state, event) {
61
91
  const noticed = new Set();
62
92
  const place = event.placeId === null ? undefined : state.places[event.placeId];
63
- if (place && (event.reach ?? 'here') !== 'here') {
64
- const places = event.reach === 'everywhere' ? Object.keys(state.places).filter(id => id !== event.placeId) : place.connections;
65
- for (const id of places.flatMap(id => peopleAt(state, id)))
66
- noticed.add(id);
93
+ const carries = event.channel ?? null;
94
+ if (place) {
95
+ const range = carries === null ? (event.reach === 'everywhere' ? Number.MAX_SAFE_INTEGER : event.reach === 'nearby' ? 1 : 0)
96
+ : state.channels[carries]?.reach ?? 0;
97
+ if (range > 0)
98
+ for (const id of placesWithin(state, event.placeId, range).flatMap(id => peopleAt(state, id)))
99
+ noticed.add(id);
67
100
  }
68
101
  for (const effect of event.effects) {
69
102
  if (effect.kind !== 'move')
@@ -76,11 +109,15 @@ export function nearbyFor(state, event) {
76
109
  if (signal.targetPlaceId !== null)
77
110
  for (const id of peopleAt(state, signal.targetPlaceId))
78
111
  noticed.add(id);
79
- else if (signal.channel === GLOBAL_SIGNAL_CHANNEL)
80
- for (const id of Object.keys(state.people))
81
- noticed.add(id);
112
+ else {
113
+ const range = state.channels[signal.channel]?.reach ?? 0;
114
+ if (signal.sourcePlaceId !== null)
115
+ for (const id of placesWithin(state, signal.sourcePlaceId, range).flatMap(id => peopleAt(state, id)))
116
+ noticed.add(id);
117
+ }
82
118
  }
83
- return [...noticed].filter(id => event.placeId === null || state.people[id].placeId !== event.placeId).sort();
119
+ const here = event.placeId === null ? new Set() : new Set(peopleAt(state, event.placeId));
120
+ return Object.keys(state.people).filter(id => noticed.has(id) && !here.has(id));
84
121
  }
85
122
  // Where someone arrived from, when an event walked them into this person's room.
86
123
  export function arrivalFor(state, event, personId) {
@@ -90,19 +127,8 @@ export function arrivalFor(state, event, personId) {
90
127
  const move = event.effects.find(effect => effect.kind === 'move' && effect.placeId === person.placeId && effect.personId !== personId);
91
128
  if (!move || move.kind !== 'move')
92
129
  return null;
93
- return `${state.people[move.personId]?.name ?? move.personId} comes in from ${event.placeId ? state.places[event.placeId]?.name ?? event.placeId : 'elsewhere'}`;
94
- }
95
- // The working state keeps the recent part of what the event log keeps whole: the latest lines of
96
- // each conversation, the latest ended conversations, and the latest messages.
97
- const CONVERSATION_LINES = 64;
98
- const ENDED_CONVERSATIONS = 16;
99
- const INBOX_MESSAGES = 256;
100
- const KEPT_CLOSED_REQUESTS = 64;
101
- const BOUNDED_RECORDS_ENGINE = 33;
102
- // How many of the newest events, and their changes, the working state carries.
103
- const RECENT_EVENTS = 64;
104
- const KEPT_ACTIVE_GOALS = 32;
105
- const KEPT_FINISHED_GOALS = 16;
130
+ return phrase('arrival.for', { name: state.people[move.personId]?.name ?? move.personId, place: event.placeId ? state.places[event.placeId]?.name ?? event.placeId : phrase('arrival.elsewhere') });
131
+ }
106
132
  // The working state carries the property and relation changes of the recent events it carries;
107
133
  // the durable change log keeps every change. Dropping from the front costs each change once.
108
134
  function keepRecentChanges(state, cutoffSeq) {
@@ -110,66 +136,132 @@ function keepRecentChanges(state, cutoffSeq) {
110
136
  let first = 0;
111
137
  while (first < items.length && items[first].seq <= cutoffSeq)
112
138
  first += 1;
113
- if (first === 0)
139
+ const kept = items.slice(first);
140
+ if (kept.length <= BOUNDS.changes) {
141
+ if (first > 0)
142
+ state.changes = kept;
114
143
  return;
115
- state.changes = items.slice(first);
116
- }
117
- function keepWorkingStateBounded(state, replay) {
118
- for (const conversation of state.conversations) {
119
- if (conversation.lines.length > CONVERSATION_LINES)
120
- conversation.lines = conversation.lines.slice(-CONVERSATION_LINES);
121
144
  }
122
- const ended = state.conversations.filter(conversation => conversation.endedAt !== null);
123
- if (ended.length > ENDED_CONVERSATIONS) {
124
- const dropped = new Set(ended.slice(0, ended.length - ENDED_CONVERSATIONS).map(conversation => conversation.id));
125
- state.conversations = state.conversations.filter(conversation => !dropped.has(conversation.id));
126
- }
127
- if (state.messages.length > INBOX_MESSAGES)
128
- state.messages = state.messages.slice(-INBOX_MESSAGES);
129
- // Requests and goals stay in the event log; saved state keeps what inputs and rules can use: every
130
- // open request, the newest refusals, the newest settled requests, and each person's newest goals.
131
- // Older engines kept every request and goal; their logged ids depend on that, so they keep it.
132
- if (state.engine < BOUNDED_RECORDS_ENGINE)
145
+ const dropped = kept.slice(0, kept.length - BOUNDS.changes);
146
+ state.folds.changes = foldOf(state.folds.changes, dropped, 'changes');
147
+ state.changes = kept.slice(kept.length - BOUNDS.changes);
148
+ }
149
+ export function applyLivingEvent(previous, input, cold) {
150
+ return applyEvent(previous, input, undefined, cold);
151
+ }
152
+ function engageIncidental(state, event) {
153
+ if ((event.kind === 'plan' && event.actorId === null))
133
154
  return;
134
- const newest = (items, keep) => new Set(items.slice(Math.max(0, items.length - keep)));
135
- if (state.requests.length > KEPT_CLOSED_REQUESTS) {
136
- const refused = newest(state.requests.filter(request => request.status === 'refused'), KEPT_CLOSED_REQUESTS);
137
- const settled = newest(state.requests.filter(request => request.status === 'answered' || request.status === 'done'), KEPT_CLOSED_REQUESTS);
138
- if (refused.size + settled.size + state.requests.filter(request => request.status === 'open').length < state.requests.length) {
139
- state.requests = state.requests.filter(request => request.status === 'open' || refused.has(request) || settled.has(request));
140
- }
141
- }
142
- for (const person of Object.values(state.people)) {
143
- if (state.engine >= BOUNDED_PERSON_RECORDS_ENGINE) {
144
- if (person.beliefs.length > MAX_WORKING_BELIEFS)
145
- person.beliefs = person.beliefs.slice(-MAX_WORKING_BELIEFS);
146
- const closed = newest(person.commitments.filter(item => item.status !== 'open'), MAX_CLOSED_COMMITMENTS);
147
- if (closed.size + person.commitments.filter(item => item.status === 'open').length < person.commitments.length) {
148
- person.commitments = person.commitments.filter(item => item.status === 'open' || closed.has(item));
149
- if (replay)
150
- replay.set(person.id, new Map(person.commitments.map(item => [item.id, item])));
155
+ const engaged = new Set();
156
+ if (event.actorId !== null)
157
+ engaged.add(event.actorId);
158
+ for (const effect of event.effects) {
159
+ switch (effect.kind) {
160
+ case 'say':
161
+ for (const id of effect.toIds)
162
+ engaged.add(id);
163
+ break;
164
+ case 'message':
165
+ for (const id of effect.toIds)
166
+ engaged.add(id);
167
+ break;
168
+ case 'dispatch':
169
+ for (const id of effect.toIds)
170
+ engaged.add(id);
171
+ break;
172
+ case 'person.create': break;
173
+ case 'schedule':
174
+ if (effect.targetId !== null)
175
+ engaged.add(effect.targetId);
176
+ if ((effect.series === 'director') && effect.personId !== null)
177
+ engaged.add(effect.personId);
178
+ break;
179
+ default: {
180
+ if ('personId' in effect && typeof effect.personId === 'string')
181
+ engaged.add(effect.personId);
182
+ if ('targetId' in effect && typeof effect.targetId === 'string')
183
+ engaged.add(effect.targetId);
184
+ if ('toId' in effect && typeof effect.toId === 'string')
185
+ engaged.add(effect.toId);
186
+ if ('receiverId' in effect && typeof effect.receiverId === 'string')
187
+ engaged.add(effect.receiverId);
188
+ if ('participantIds' in effect && Array.isArray(effect.participantIds))
189
+ for (const id of effect.participantIds)
190
+ if (typeof id === 'string')
191
+ engaged.add(id);
151
192
  }
152
193
  }
153
- if (person.goals.length <= KEPT_ACTIVE_GOALS)
154
- continue;
155
- const active = newest(person.goals.filter(goal => goal.status === 'active'), KEPT_ACTIVE_GOALS);
156
- const finished = newest(person.goals.filter(goal => goal.status !== 'active'), KEPT_FINISHED_GOALS);
157
- if (active.size + finished.size < person.goals.length)
158
- person.goals = person.goals.filter(goal => active.has(goal) || finished.has(goal));
159
194
  }
160
- }
161
- export function applyLivingEvent(previous, input) {
162
- return applyEvent(previous, input);
195
+ for (const id of engaged) {
196
+ const person = state.people[id];
197
+ if (person?.incidental)
198
+ delete person.incidental;
199
+ }
163
200
  }
164
201
  // Replay owns this fresh state. Mutating it avoids copying the full archive on every event.
165
- export function foldLivingEvents(initial, events) {
202
+ export function foldLivingEvents(initial, events, cold) {
166
203
  let state = structuredClone(initial);
167
204
  const commitments = new Map(Object.values(state.people).map(person => [person.id, new Map(person.commitments.map(commitment => [commitment.id, commitment]))]));
168
205
  for (const event of events)
169
- state = applyEvent(state, event, commitments);
170
- return sealLivingIndexes(state);
206
+ state = applyEvent(state, event, commitments, cold);
207
+ return sealState(state);
208
+ }
209
+ function namedEntityIds(event) {
210
+ const ids = new Set(event.thingIds ?? []);
211
+ for (const effect of event.effects) {
212
+ if (effect.kind === 'entity.create')
213
+ continue;
214
+ for (const key of ['entityId', 'targetId', 'containerId', 'thingId']) {
215
+ const value = effect[key];
216
+ if (typeof value === 'string')
217
+ ids.add(value);
218
+ }
219
+ const things = effect.thingIds;
220
+ if (Array.isArray(things))
221
+ for (const id of things)
222
+ if (typeof id === 'string')
223
+ ids.add(id);
224
+ }
225
+ return [...ids];
226
+ }
227
+ function loadParked(state, cold, id) {
228
+ if (state.entities[id] !== undefined || cold === undefined || !cold.has(id))
229
+ return;
230
+ const parsed = entitySchema.safeParse(cold.load(id));
231
+ if (!parsed.success)
232
+ throw new LivingWorldError('not-loaded', `Parked entity ${id} could not be loaded`);
233
+ const entity = parsed.data;
234
+ state.entities[id] = entity;
235
+ state.touched[id] = state.revision;
236
+ if (entity.containerId === null)
237
+ state.globalEntityIds = [...state.globalEntityIds, id];
238
+ else
239
+ state.within[entity.containerId] = [...(state.within[entity.containerId] ?? []), id];
240
+ indexPlaceless(state, id);
241
+ for (const mechanic of state.kinds[entity.kindId]?.mechanics ?? []) {
242
+ const onEvent = mechanic.onEvent;
243
+ if (onEvent === undefined)
244
+ continue;
245
+ const subjectId = entity.properties[onEvent.subjectPropertyId]?.value;
246
+ if (typeof subjectId === 'string')
247
+ (state.entityMoveSubjectIds[subjectId] ??= []).push(id);
248
+ }
249
+ }
250
+ function touchEntities(state, event) {
251
+ if (event.kind === 'opening')
252
+ return;
253
+ for (const id of namedEntityIds(event))
254
+ if (state.entities[id] !== undefined)
255
+ state.touched[id] = event.seq;
256
+ const ids = Object.keys(state.touched);
257
+ if (ids.length <= BOUNDS.entities)
258
+ return;
259
+ const drop = ids.sort((left, right) => state.touched[left] - state.touched[right] || (left < right ? -1 : 1))
260
+ .slice(0, ids.length - BOUNDS.entities);
261
+ for (const id of drop)
262
+ delete state.touched[id];
171
263
  }
172
- function applyEvent(previous, input, replay) {
264
+ function applyEvent(previous, input, replay, cold) {
173
265
  if (previous.status === 'finished')
174
266
  throw new LivingWorldError('run-finished', 'A finished story accepts no further events');
175
267
  // Events written by an older engine carry no reach: parsing fills the defaults and the
@@ -194,7 +286,7 @@ function applyEvent(previous, input, replay) {
194
286
  const live = previous.clockRate !== null;
195
287
  const endsAt = live && event.kind !== 'tick' ? event.at : event.at + event.minutes;
196
288
  const expectedWitnesses = witnessesFor(previous, event);
197
- if (JSON.stringify(expectedWitnesses) !== JSON.stringify([...event.witnessIds].sort())) {
289
+ if (JSON.stringify([...expectedWitnesses].sort()) !== JSON.stringify([...event.witnessIds].sort())) {
198
290
  throw new LivingWorldError('replay-mismatch', `Event ${event.seq} names witnesses ${event.witnessIds.join(',')} but ${expectedWitnesses.join(',')} were present`);
199
291
  }
200
292
  if (event.perceivedBy && (new Set(event.perceivedBy).size !== event.perceivedBy.length
@@ -209,8 +301,7 @@ function applyEvent(previous, input, replay) {
209
301
  if (affectedObjects.has(id))
210
302
  return false;
211
303
  const object = previous.objects[id];
212
- return !object || event.placeId === null || object.placeId !== event.placeId
213
- && (object.holderId === null || previous.people[object.holderId]?.placeId !== event.placeId);
304
+ return !object || event.placeId === null || siteOf(previous, object.containerId) !== event.placeId;
214
305
  });
215
306
  if (remoteVisibleObject) {
216
307
  throw new LivingWorldError('effect-invalid', `Visible object ${remoteVisibleObject} is not at the event place`);
@@ -229,18 +320,25 @@ function applyEvent(previous, input, replay) {
229
320
  throw new LivingWorldError('effect-invalid', `Visible tension ${remoteVisibleTension} has no participant at the event place`);
230
321
  }
231
322
  const expectedNearby = nearbyFor(previous, event);
232
- if (!legacy && JSON.stringify(expectedNearby) !== JSON.stringify([...event.nearbyIds].sort())) {
323
+ if (!legacy && JSON.stringify([...expectedNearby].sort()) !== JSON.stringify([...event.nearbyIds].sort())) {
233
324
  throw new LivingWorldError('replay-mismatch', `Event ${event.seq} names nearby people ${event.nearbyIds.join(',')} but ${expectedNearby.join(',')} were nearby`);
234
325
  }
326
+ const grew = event.effects.some(effect => effect.kind === 'entity.create')
327
+ || namedEntityIds(event).some(id => previous.entities[id] === undefined && cold?.has(id) === true);
235
328
  const change = (state) => {
329
+ if (state.admissionCapsFrom === undefined)
330
+ state.admissionCapsFrom = event.seq;
331
+ for (const id of namedEntityIds(event))
332
+ loadParked(state, cold, id);
236
333
  const playerPresent = event.witnessIds.includes(state.playerId);
237
334
  // Older changes leave before this event's changes join, so the trim reads the list as it was.
238
- if (state.engine >= LOCAL_RECOVERY_ENGINE)
239
- keepRecentChanges(state, event.seq - RECENT_EVENTS);
335
+ keepRecentChanges(state, event.seq - BOUNDS.events);
240
336
  for (const effect of event.effects)
241
337
  applyEffect(state, event, effect, replay);
242
- if (state.engine >= SILENCE_ENGINE)
243
- noteUnanswered(state, event);
338
+ reactPass(state, event, [...event.effects.flatMap(changedSlots), ...(event.lawSeeds ?? [])], 0);
339
+ engageIncidental(state, event);
340
+ noteUnanswered(state, event);
341
+ noteSituation(state, event);
244
342
  if (event.thingIds && (new Set(event.thingIds).size !== event.thingIds.length || event.thingIds.some(id => !readEntity(state, id) && !state.objects[id]))) {
245
343
  throw new LivingWorldError('effect-invalid', `Event ${event.seq} names a thing that does not exist, or one twice`);
246
344
  }
@@ -257,36 +355,20 @@ function applyEvent(previous, input, replay) {
257
355
  if (affectedTensions.has(tensionId))
258
356
  continue;
259
357
  const tension = state.tensions.find(candidate => candidate.id === tensionId);
260
- if (state.engine >= PROBLEM_VIEW_ENGINE) {
358
+ {
261
359
  seeTension(state, tension, event, 'shown');
262
360
  continue;
263
361
  }
264
- tension.playerView = {
265
- title: tension.playerView?.title ?? tension.title,
266
- summary: tension.playerView?.summary ?? event.observed ?? tension.summary,
267
- status: tension.status,
268
- resolution: tension.status === 'settled' ? event.observed ?? tension.resolution : null,
269
- latest: tension.playerView ? event.observed ?? null : null,
270
- };
271
362
  }
272
363
  }
273
364
  applyEventChanges(state, event);
274
- if (state.engine >= LAZY_METER_ENGINE)
275
- dropStalePredictions(state, endsAt);
276
- else {
277
- advanceScopedEntities(state, event.placeId, endsAt, event.seq);
278
- for (const destination of new Set(event.effects.flatMap(effect => effect.kind === 'move' ? [effect.placeId] : []))) {
279
- if (destination !== event.placeId)
280
- advanceScopedEntities(state, destination, endsAt, event.seq);
281
- }
282
- }
365
+ dropStalePredictions(state, endsAt);
283
366
  if (event.effects.some(effect => effect.kind === 'move')) {
284
367
  for (const person of Object.values(state.people)) {
285
368
  if (person.held?.byId && state.people[person.held.byId].placeId !== person.placeId)
286
369
  delete person.held;
287
370
  }
288
371
  }
289
- keepWorkingStateBounded(state, replay);
290
372
  // A typed cause set up later in the same act still counts as what stopped the person.
291
373
  for (const effect of event.effects) {
292
374
  if (effect.kind !== 'incapacitate')
@@ -299,8 +381,7 @@ function applyEvent(previous, input, replay) {
299
381
  // Recovery is decided where the event happens and where the player arrives: a character may arrive
300
382
  // several rooms away in a room a command did not load, but the player's next room is always loaded,
301
383
  // so a scoped fold and the whole world reach the same state.
302
- const recoveryPlaces = state.engine >= LOCAL_RECOVERY_ENGINE
303
- ? new Set([event.placeId, ...event.effects.flatMap(effect => effect.kind === 'move' && effect.personId === state.playerId ? [effect.placeId] : [])]) : null;
384
+ const recoveryPlaces = (new Set([event.placeId, ...event.effects.flatMap(effect => effect.kind === 'move' && effect.personId === state.playerId ? [effect.placeId] : [])]));
304
385
  for (const person of Object.values(state.people)) {
305
386
  if (person.incapacitatedBy === undefined || (recoveryPlaces !== null && !recoveryPlaces.has(person.placeId)))
306
387
  continue;
@@ -314,7 +395,7 @@ function applyEvent(previous, input, replay) {
314
395
  noteThings(state, event);
315
396
  learnThings(state, event);
316
397
  // From engine 50 those where something happens learn what lies there in the open; that room is loaded.
317
- if (state.engine >= SEEN_AT_EVENTS_ENGINE && event.placeId !== null && state.places[event.placeId]) {
398
+ if ((event.placeId !== null) && state.places[event.placeId]) {
318
399
  for (const personId of peopleAt(state, event.placeId))
319
400
  seeWhatLiesHere(state, personId, event.placeId);
320
401
  }
@@ -336,19 +417,42 @@ function applyEvent(previous, input, replay) {
336
417
  if (event.kind === 'keep-playing')
337
418
  state.stoppingPoint = null;
338
419
  // Suggestions belong to the latest character line addressed to the player; the player's own words clear them.
339
- if (event.actorId === state.playerId)
420
+ if (event.actorId === state.playerId) {
340
421
  state.suggestions = [];
341
- else if (event.suggestions.length > 0)
422
+ state.suggestionsFrom = null;
423
+ }
424
+ else if (event.suggestions.length > 0) {
342
425
  state.suggestions = [...event.suggestions];
426
+ state.suggestionsFrom = event.actorId;
427
+ }
428
+ if ((state.suggestionsFrom !== null) && state.suggestionsFrom !== undefined) {
429
+ const from = state.people[state.suggestionsFrom];
430
+ if (!from || from.departed !== undefined || from.offstage !== undefined || from.placeId !== state.people[state.playerId].placeId) {
431
+ state.suggestions = [];
432
+ state.suggestionsFrom = null;
433
+ }
434
+ }
343
435
  if (event.kind === 'finish') {
344
436
  state.epilogue = { title: event.summary, text: event.narration ?? event.summary, at: event.at, ...event.ending };
345
437
  state.status = 'finished';
346
438
  }
347
439
  state.clock = endsAt;
348
440
  state.revision = event.seq;
349
- if (state.engine >= PLAYER_REST_ENGINE && event.actorId === state.playerId && event.kind !== 'tick' && event.kind !== 'clock')
441
+ if (event.kind === 'attempt' || (event.kind === 'world' && event.outcome !== null)) {
442
+ state.rulings += 1;
443
+ if (event.effects.some(effect => effect.kind === 'note'))
444
+ state.notedRulings += 1;
445
+ }
446
+ if ((event.actorId === state.playerId) && event.kind !== 'tick' && event.kind !== 'clock')
350
447
  state.playerActedAt = event.at;
351
- state.events = [...plain(state.events).slice(-RECENT_EVENTS), event];
448
+ if ((event.actorId === state.playerId) && event.kind !== 'tick' && event.kind !== 'clock')
449
+ state.playerTurnSeq = event.seq;
450
+ state.events = [...previous.events.slice(-BOUNDS.events), event];
451
+ touchEntities(state, event);
452
+ boundState(state, cold, grew);
453
+ if (replay)
454
+ for (const person of Object.values(state.people))
455
+ replay.set(person.id, new Map(person.commitments.map(item => [item.id, item])));
352
456
  };
353
457
  if (replay) {
354
458
  change(previous);
@@ -357,20 +461,103 @@ function applyEvent(previous, input, replay) {
357
461
  const overlay = entityOverlay(previous.entities);
358
462
  const next = produce({ ...previous, entities: overlay.table }, change);
359
463
  const changed = overlay.changes();
360
- const result = { ...next, entities: Object.keys(changed).length === 0 ? previous.entities : { ...previous.entities, ...changed } };
361
- sealLivingIndexes(result);
464
+ const result = { ...next, entities: next.parked.count !== previous.parked.count ? next.entities
465
+ : Object.keys(changed).length === 0 ? previous.entities : { ...previous.entities, ...changed } };
466
+ sealState(result);
362
467
  return result;
363
468
  }
364
- function applyEffect(state, event, effect, replay) {
469
+ function checkKindForWorld(state, definition, event) {
470
+ const kindIds = new Set(Object.keys(state.kinds));
471
+ if (event !== undefined) {
472
+ for (const effect of event.effects)
473
+ if ('definition' in effect)
474
+ kindIds.add(effect.definition.id);
475
+ }
476
+ checkKindDefinition(definition, kindIds, new Set(Object.keys(state.channels)), `kinds.${definition.id}`, 'effect-invalid');
477
+ }
478
+ export function isDecisionKind(kind) {
479
+ if (kind === undefined)
480
+ return false;
481
+ const { properties } = kind;
482
+ return properties.some(property => property.type === 'series' && property.options !== undefined && property.options.length > 0)
483
+ && properties.some(property => property.type === 'series' && property.options === undefined);
484
+ }
485
+ export function isChoiceTurn(state, item) {
486
+ const entity = item.targetId === null ? undefined : state.entities[item.targetId];
487
+ return item.kind === 'plan' && entity !== undefined && isDecisionKind(state.kinds[entity.kindId]);
488
+ }
489
+ export function answeredLine(state, personId, causeSeq) {
490
+ return state.events.some(event => event.causeSeq === causeSeq && event.actorId === personId
491
+ && event.effects.some(effect => effect.kind === 'say' && effect.toIds.includes(state.playerId)));
492
+ }
493
+ function causedByPlayer(state, event) {
494
+ if (event.actorId === state.playerId)
495
+ return true;
496
+ if (event.causeSeq === null)
497
+ return false;
498
+ return state.events.find(item => item.seq === event.causeSeq)?.actorId === state.playerId;
499
+ }
500
+ function capsApply(state, event) {
501
+ return event.seq >= capsBoundaryOf(state);
502
+ }
503
+ function owesRoom(state, item, event) {
504
+ if (!owedSchedule(item))
505
+ return true;
506
+ const owed = state.schedule.filter(owedSchedule).length;
507
+ if (!capsApply(state, event)) {
508
+ if (owed >= BOUNDS.pinnedSchedule)
509
+ throw new LivingWorldError('effect-invalid', `The world already owes ${BOUNDS.pinnedSchedule} scheduled acts; finish one before adding another`);
510
+ return true;
511
+ }
512
+ return owed < (causedByPlayer(state, event) ? BOUNDS.pinnedSchedule : BOUNDS.pinnedSchedule - BOUNDS.owedReserve);
513
+ }
514
+ function scheduleDecisionVotes(state, event, entityId) {
515
+ const entity = state.entities[entityId];
516
+ if (entity === undefined)
517
+ return;
518
+ if (!isDecisionKind(state.kinds[entity.kindId]))
519
+ return;
520
+ const { members } = entity.properties;
521
+ if (!Array.isArray(members?.value))
522
+ return;
523
+ for (const member of members.value) {
524
+ const personId = member.personId;
525
+ const person = typeof personId === 'string' ? state.people[personId] : undefined;
526
+ if (person === undefined || person.offstage !== undefined || person.departed !== undefined || person.placeId !== siteOf(state, entity.containerId))
527
+ continue;
528
+ const id = generatedId(state.engine, 'choice', [entityId, person.id]);
529
+ if (state.schedule.some(item => item.id === id))
530
+ continue;
531
+ const item = { id, at: state.clock + pace(state.calendar, 'contactAnswer'), personId: person.id, kind: 'plan',
532
+ intent: phrase('vote.cast', { name: entity.name }), placeId: null, targetId: entityId, sourceSeq: event.seq, importance: PROMISE_IMPORTANCE };
533
+ if (!owesRoom(state, item, event))
534
+ continue;
535
+ insertScheduled(state, item);
536
+ }
537
+ }
538
+ function applyEffect(state, event, effect, replay, fromLaw = false, fromCreate = false) {
539
+ forbidCheck(state, event, effect);
540
+ if (effect.kind === 'kind.revise') {
541
+ const definition = effect.definition;
542
+ const previous = state.kinds[definition.id];
543
+ if (!previous)
544
+ throw new LivingWorldError('effect-invalid', `Kind ${definition.id} does not exist`);
545
+ if (narrowsKindRevision(previous, definition))
546
+ throw new LivingWorldError('narrows-revision', `Kind ${definition.id} revision narrows it; a revision may only add slots, options, mechanics and laws`);
547
+ checkKindForWorld(state, definition);
548
+ state.kinds[definition.id] = definition;
549
+ state.stewardAt = event.at;
550
+ return;
551
+ }
365
552
  // From engine 49 a world's own things, as its opening sets them out, are known to everyone in it.
366
- const opening = event.kind === 'opening' && state.engine >= THINGS_SEEN_ENGINE;
553
+ const opening = (event.kind === 'opening');
367
554
  const knownTo = opening ? Object.keys(state.people).sort()
368
555
  : [...new Set([...(event.perceivedBy ?? event.witnessIds), ...(event.actorId && state.people[event.actorId] ? [event.actorId] : [])])];
369
556
  switch (effect.kind) {
370
557
  case 'move': {
371
558
  const person = requirePerson(state, effect.personId);
372
559
  // The player goes where they choose, or where someone beside them takes them; nothing else moves them.
373
- if (state.engine >= IDENTITY_ENGINE && person.id === state.playerId && event.actorId !== state.playerId
560
+ if ((person.id === state.playerId) && event.actorId !== state.playerId
374
561
  && (event.actorId === null || event.placeId !== person.placeId)) {
375
562
  throw new LivingWorldError('effect-invalid', `${person.name} moves only by their own choice or with someone beside them`);
376
563
  }
@@ -382,15 +569,15 @@ function applyEffect(state, event, effect, replay) {
382
569
  }
383
570
  requirePlace(state, effect.placeId);
384
571
  const from = person.placeId;
385
- person.placeId = effect.placeId;
572
+ moveWithin(state, person.id, effect.placeId);
573
+ rescheduleContents(state, person.id, effect.placeId);
386
574
  person.arrivedSeq = event.seq;
387
- carryHeldEntities(state, person.id, from, effect.placeId);
388
575
  // A character may walk into a room the command did not load; from engine 50 only the player,
389
576
  // whose next room is always loaded, learns what lies there on arrival.
390
- if (state.engine < SEEN_AT_EVENTS_ENGINE || person.id === state.playerId)
577
+ if ((person.id === state.playerId))
391
578
  seeWhatLiesHere(state, person.id, effect.placeId);
392
579
  // Walking off sets aside any long act the person had under way.
393
- if (state.engine >= WALK_OFF_ENGINE && state.schedule.some(item => item.kind === 'finish' && item.targetId === person.id)) {
580
+ if ((state.schedule.some(item => item.kind === 'finish' && item.targetId === person.id))) {
394
581
  state.schedule = state.schedule.filter(item => !(item.kind === 'finish' && item.targetId === person.id));
395
582
  }
396
583
  leaveConversations(state, person.id, from, event.at);
@@ -401,7 +588,7 @@ function applyEffect(state, event, effect, replay) {
401
588
  state.sightings[person.id] = { placeId: effect.placeId, at: event.at };
402
589
  // Seen walking out, they were last seen heading into the next room on their way.
403
590
  else if ((event.perceivedBy ?? event.witnessIds).includes(state.playerId)) {
404
- state.sightings[person.id] = { placeId: travelPath(state, from, effect.placeId)?.[1] ?? effect.placeId, at: event.at, heading: true };
591
+ state.sightings[person.id] = ({ placeId: effect.placeId, at: event.at, heading: true });
405
592
  }
406
593
  return;
407
594
  }
@@ -409,14 +596,14 @@ function applyEffect(state, event, effect, replay) {
409
596
  const speaker = requirePerson(state, effect.personId);
410
597
  if (event.placeId === null || speaker.placeId !== event.placeId)
411
598
  throw new LivingWorldError('effect-invalid', `${speaker.name} cannot speak at a place they are not in`);
412
- if (state.engine >= ACT_GATE_ENGINE && event.actorId === speaker.id) {
599
+ if ((event.actorId === speaker.id)) {
413
600
  const gate = blockedByGate(state, speaker.id, 'speak');
414
601
  if (gate)
415
602
  throw new LivingWorldError('effect-invalid', `Speech is blocked by ${gate}`);
416
603
  }
417
604
  for (const target of effect.toIds) {
418
605
  const listener = requirePerson(state, target);
419
- if (listener.placeId !== event.placeId || state.engine >= AWAY_APART_ENGINE && listener.away)
606
+ if (listener.placeId !== event.placeId || (listener.offstage))
420
607
  throw new LivingWorldError('effect-invalid', `${listener.name} is not here to be addressed`);
421
608
  }
422
609
  const conversation = openConversation(state, event.placeId, [speaker.id, ...effect.toIds], event.at, event.seq);
@@ -439,7 +626,7 @@ function applyEffect(state, event, effect, replay) {
439
626
  // Whose account it passes on is checked now, when it is sent; the reader learns it from the sender.
440
627
  const { kind: _kind, dispatchId, sourcePersonId: _source, ...delivery } = effect;
441
628
  insertScheduled(state, { id: dispatchId, at: event.at + state.messageTravel.minutes, personId: null, kind: 'deliver',
442
- intent: `A message from ${state.people[effect.fromId].name}`.slice(0, 600), placeId: null, targetId: null, sourceSeq: event.seq, importance: event.importance, delivery });
629
+ intent: phrase('dispatch.from', { name: state.people[effect.fromId].name }).slice(0, 600), placeId: null, targetId: null, sourceSeq: event.seq, importance: event.importance, delivery });
443
630
  return;
444
631
  }
445
632
  case 'request.open': {
@@ -450,8 +637,17 @@ function applyEffect(state, event, effect, replay) {
450
637
  if (state.requests.some(request => request.id === effect.requestId))
451
638
  throw new LivingWorldError('effect-invalid', `Request ${effect.requestId} already exists`);
452
639
  state.requests.push({ id: effect.requestId, senderId: effect.senderId, receiverId: effect.receiverId,
453
- topic: effect.topic, status: 'open', openedSeq: event.seq, ...(state.engine >= REQUEST_TIME_ENGINE ? { openedAt: event.at } : {}),
640
+ topic: effect.topic, status: 'open', openedSeq: event.seq, ...(({ openedAt: event.at })),
454
641
  knownTo: [...new Set([effect.senderId, effect.receiverId, ...(event.perceivedBy ?? event.witnessIds)])] });
642
+ const receiver = state.people[effect.receiverId];
643
+ if ((!receiver.isPlayer) && receiver.departed === undefined && receiver.offstage === undefined
644
+ && !state.schedule.some(item => item.decision?.kind === 'ask' && item.decision.id === effect.requestId)) {
645
+ const item = { id: generatedId(state.engine, 'ask', [effect.requestId]), at: event.at + pace(state.calendar, 'askDecision'), personId: receiver.id, kind: 'plan',
646
+ intent: phrase('request.decide', { name: state.people[effect.senderId].name, topic: effect.topic }).slice(0, MAX_LINE), placeId: null, targetId: effect.senderId,
647
+ sourceSeq: event.seq, importance: PROMISE_IMPORTANCE, decision: { kind: 'ask', id: effect.requestId } };
648
+ if (owesRoom(state, item, event))
649
+ insertScheduled(state, item);
650
+ }
455
651
  return;
456
652
  }
457
653
  case 'norm.violation': {
@@ -486,8 +682,6 @@ function applyEffect(state, event, effect, replay) {
486
682
  return;
487
683
  }
488
684
  case 'request.remind': {
489
- if (state.engine < REMINDER_ENGINE)
490
- throw new LivingWorldError('effect-invalid', 'This world keeps no reminders');
491
685
  const request = state.requests.find(item => item.id === effect.requestId);
492
686
  if (!request)
493
687
  throw new LivingWorldError('effect-invalid', `Unknown request ${effect.requestId}`);
@@ -510,37 +704,26 @@ function applyEffect(state, event, effect, replay) {
510
704
  request.status = effect.status;
511
705
  if (effect.answer !== undefined)
512
706
  request.answer = { text: effect.answer, seq: event.seq };
707
+ state.schedule = state.schedule.filter(item => !(item.decision?.kind === 'ask' && item.decision.id === effect.requestId));
513
708
  return;
514
709
  }
515
710
  case 'object.update': {
516
711
  const object = state.objects[effect.objectId];
517
712
  if (!object)
518
713
  throw new LivingWorldError('effect-invalid', `Unknown object ${effect.objectId}`);
519
- if (effect.placeId !== null)
520
- requirePlace(state, effect.placeId);
521
- if (effect.holderId !== null)
522
- requirePerson(state, effect.holderId);
523
714
  if (effect.ownerId !== null)
524
715
  requirePerson(state, effect.ownerId);
525
- if (effect.placeId !== null && effect.holderId !== null)
526
- throw new LivingWorldError('effect-invalid', `${object.name} cannot be both placed and held`);
527
- if (effect.placeId !== null || effect.holderId !== null) {
716
+ if (effect.containerId !== undefined) {
717
+ requireContainer(state, effect.containerId);
528
718
  object.custodyKnownTo = observedObjectIds(event).includes(effect.objectId)
529
719
  ? [...new Set([...(event.perceivedBy ?? event.witnessIds), ...(event.actorId ? [event.actorId] : [])])]
530
720
  : event.actorId === state.playerId ? [state.playerId] : [];
531
- }
532
- if (effect.placeId !== null) {
533
- object.placeId = effect.placeId;
534
- object.holderId = null;
535
- }
536
- if (effect.holderId !== null) {
537
- object.holderId = effect.holderId;
538
- object.placeId = null;
721
+ moveWithin(state, object.id, effect.containerId);
539
722
  }
540
723
  if (effect.ownerId !== null)
541
724
  object.ownerId = effect.ownerId;
542
725
  if (effect.condition !== null) {
543
- object.condition = state.engine >= CONDITION_SIDES_ENGINE ? withSide(object, effect.aspect, effect.condition, state.engine >= WHOLE_SIDES_ENGINE, state.engine >= SIDE_ORDER_ENGINE) : effect.condition;
726
+ object.condition = (withSide(object, effect.aspect, effect.condition, true, true));
544
727
  object.conditionKnownTo = observedObjectIds(event).includes(effect.objectId)
545
728
  ? [...new Set([...(event.perceivedBy ?? event.witnessIds), ...(event.actorId ? [event.actorId] : [])])]
546
729
  : event.actorId === state.playerId ? [state.playerId] : [];
@@ -550,17 +733,14 @@ function applyEffect(state, event, effect, replay) {
550
733
  case 'object.create': {
551
734
  if (state.objects[effect.objectId])
552
735
  throw new LivingWorldError('effect-invalid', `Object ${effect.objectId} already exists`);
553
- if ((effect.placeId === null) === (effect.holderId === null))
554
- throw new LivingWorldError('effect-invalid', `${effect.name} needs exactly one of a place or a holder`);
555
- if (effect.placeId !== null)
556
- requirePlace(state, effect.placeId);
557
- if (effect.holderId !== null)
558
- requirePerson(state, effect.holderId);
736
+ requireContainer(state, effect.containerId);
559
737
  if (effect.ownerId !== null)
560
738
  requirePerson(state, effect.ownerId);
561
- state.objects[effect.objectId] = { id: effect.objectId, name: effect.name, summary: effect.summary, placeId: effect.placeId, holderId: effect.holderId, ownerId: effect.ownerId, condition: effect.condition, singlePersonMovable: true, introducedAt: event.seq,
739
+ state.objects[effect.objectId] = { id: effect.objectId, name: effect.name, summary: effect.summary, containerId: effect.containerId, ownerId: effect.ownerId, condition: effect.condition, singlePersonMovable: true, introducedAt: event.seq,
562
740
  custodyKnownTo: observedObjectIds(event).includes(effect.objectId) ? [...new Set([...(event.perceivedBy ?? event.witnessIds), ...(event.actorId ? [event.actorId] : [])])] : [],
563
741
  conditionKnownTo: observedObjectIds(event).includes(effect.objectId) ? [...new Set([...(event.perceivedBy ?? event.witnessIds), ...(event.actorId ? [event.actorId] : [])])] : [] };
742
+ if (effect.containerId !== null)
743
+ state.within[effect.containerId] = [...(state.within[effect.containerId] ?? []), effect.objectId];
564
744
  return;
565
745
  }
566
746
  case 'place.condition': {
@@ -595,65 +775,97 @@ function applyEffect(state, event, effect, replay) {
595
775
  throw new LivingWorldError('effect-invalid', `Place ${effect.placeId} already exists`);
596
776
  for (const connection of effect.connections)
597
777
  requirePlace(state, connection);
598
- state.places[effect.placeId] = { id: effect.placeId, name: effect.name, kind: 'room', summary: effect.summary, connections: [...effect.connections], conditions: [], conditionAspects: {}, introducedAt: event.seq };
778
+ state.places[effect.placeId] = { id: effect.placeId, name: effect.name, containerId: null, summary: effect.summary, connections: [...effect.connections], edgeCosts: {}, conditions: [], conditionAspects: {}, introducedAt: event.seq };
599
779
  for (const connection of effect.connections)
600
780
  state.places[connection].connections.push(effect.placeId);
601
781
  return;
602
782
  }
783
+ case 'place.move': {
784
+ const place = requirePlace(state, effect.placeId);
785
+ requirePlace(state, effect.toPlaceId);
786
+ if (place.containerId === effect.toPlaceId)
787
+ throw new LivingWorldError('effect-invalid', `${place.name} is already there`);
788
+ if (!place.connections.includes(effect.toPlaceId))
789
+ throw new LivingWorldError('effect-invalid', `${place.name} can only move to a place it connects to`);
790
+ moveWithin(state, place.id, effect.toPlaceId);
791
+ return;
792
+ }
603
793
  case 'person.create': {
604
794
  if (state.people[effect.personId])
605
795
  throw new LivingWorldError('effect-invalid', `Person ${effect.personId} already exists`);
606
- const namesake = state.engine >= IDENTITY_ENGINE ? Object.values(state.people).find(person => person.departed === undefined && person.name === effect.name) : undefined;
796
+ const namesake = (Object.values(state.people).find(person => person.departed === undefined && person.name === effect.name));
607
797
  if (namesake)
608
798
  throw new LivingWorldError('effect-invalid', `${effect.name} (${namesake.id}) is already in the story; tell the newcomer apart by a name of their own or by what anyone can see, such as a coat or a trade, not a number`);
609
799
  requirePlace(state, effect.placeId);
800
+ const incidental = ((event.kind === 'attempt' || event.kind === 'world'));
801
+ const activity = incidental ? { intent: effect.wants ?? phrase('schedule.bearings'), placeId: effect.placeId, targetId: null, dueAt: event.at + pace(state.calendar, 'incidentalActivity') } : null;
610
802
  state.people[effect.personId] = {
611
803
  id: effect.personId, name: effect.name, role: effect.role, roleId: null, summary: effect.summary, persona: effect.persona, isPlayer: false,
612
804
  ...(effect.pronouns ? { pronouns: effect.pronouns } : {}),
613
- placeId: effect.placeId, money: null, mood: 'Arrived', goals: effect.wants === undefined ? [] : [{ id: generatedId(state.engine, 'goal', [effect.personId, 1], `${effect.personId}-goal-1`), text: effect.wants, status: 'active' }],
805
+ placeId: effect.placeId, knownPlaceIds: [], mood: 'Arrived', goals: effect.wants === undefined ? [] : [{ id: generatedId(state.engine, 'goal', [effect.personId, 1], `${effect.personId}-goal-1`), text: effect.wants, status: 'active' }],
614
806
  relationships: {},
615
- beliefs: [], memories: [], commitments: [], plan: null, incapacitated: false,
616
- ...(state.engine >= NEWCOMER_ENGINE ? { newcomer: true, arrivedAt: event.at } : {}),
807
+ beliefs: [], memories: [], commitments: [], plan: activity, incapacitated: false,
808
+ ...(({ newcomer: true, arrivedAt: event.at })),
809
+ ...(incidental ? { incidental: true } : {}),
617
810
  };
811
+ const mover = state.people[effect.personId];
812
+ if (mover === undefined || (mover.offstage === undefined && mover.departed === undefined))
813
+ state.within[effect.placeId] = [...(state.within[effect.placeId] ?? []), effect.personId];
814
+ if (activity)
815
+ insertScheduled(state, { id: generatedId(state.engine, 'incidental', [event.seq, effect.personId]), at: activity.dueAt, personId: effect.personId,
816
+ kind: 'plan', intent: activity.intent, placeId: effect.placeId, targetId: null, sourceSeq: event.seq, importance: 1 });
618
817
  if ((event.perceivedBy ?? event.witnessIds).includes(state.playerId) && effect.placeId === event.placeId)
619
818
  state.sightings[effect.personId] = { placeId: effect.placeId, at: event.at };
620
- if (state.engine < SEEN_AT_EVENTS_ENGINE)
621
- seeWhatLiesHere(state, effect.personId, effect.placeId);
622
- return;
623
- }
624
- case 'money': {
625
- const person = requirePerson(state, effect.personId);
626
- if (person.money === null)
627
- throw new LivingWorldError('effect-invalid', `${person.name} keeps no money in this world`);
628
- const next = person.money + effect.delta;
629
- if (next < 0)
630
- throw new LivingWorldError('effect-invalid', `${person.name} cannot spend more than they have`);
631
- person.money = next;
632
819
  return;
633
820
  }
634
- case 'transfer': {
821
+ case 'shift': {
822
+ const slot = state.numbers[effect.slotId];
823
+ if (slot === undefined)
824
+ throw new LivingWorldError('effect-invalid', `Unknown number ${effect.slotId}`);
635
825
  if (effect.fromId === null && effect.toId === null)
636
- throw new LivingWorldError('effect-invalid', 'A transfer needs someone who pays or someone who receives');
637
- const unit = state.currency?.name ?? 'units';
638
- const cents = (amount) => Math.round(amount * 100) / 100;
639
- const from = effect.fromId === null ? null : purse(state, effect.fromId);
640
- const to = effect.toId === null ? null : purse(state, effect.toId);
641
- if (from !== null) {
642
- const actor = event.actorId === null ? undefined : state.people[event.actorId];
643
- // An account held by no one moves only by the world's own happenings; one held by someone, by them.
644
- if (from.account && actor && from.account.holderId === null)
826
+ throw new LivingWorldError('effect-invalid', 'A shift needs someone who gives or someone who receives');
827
+ if (!(effect.amount > 0))
828
+ throw new LivingWorldError('effect-invalid', 'A shift moves a positive amount');
829
+ const unit = state.units[slot.unit]?.name ?? slot.unit;
830
+ const actor = event.actorId === null ? null : state.people[event.actorId] ?? null;
831
+ const from = effect.fromId === null ? null : numberHolder(state, effect.fromId);
832
+ const to = effect.toId === null ? null : numberHolder(state, effect.toId);
833
+ if (effect.fromId !== null && from === null)
834
+ throw new LivingWorldError('effect-invalid', `Unknown holder ${effect.fromId}`);
835
+ if (effect.toId !== null && to === null)
836
+ throw new LivingWorldError('effect-invalid', `Unknown holder ${effect.toId}`);
837
+ if (from !== null && from.kind === HOLDER_PERSON && actor !== null && actor.id !== from.id && actor.placeId !== from.placeId) {
838
+ throw new LivingWorldError('effect-invalid', `${actor.name} cannot reach ${from.name}'s ${slot.id} from here`);
839
+ }
840
+ if (from !== null && from.kind === HOLDER_ENTITY && actor !== null) {
841
+ if (from.holderId === null)
645
842
  throw new LivingWorldError('effect-invalid', `${from.name} is moved only by the world's own rules, such as a vote or a due happening`);
646
- if (from.account && actor && from.account.holderId !== null && from.account.holderId !== actor.id)
647
- throw new LivingWorldError('effect-invalid', `Only ${state.people[from.account.holderId]?.name ?? from.account.holderId} moves money from ${from.name}`);
648
- // Someone else's purse is reached only by someone beside them.
649
- if (from.person && actor && actor.id !== from.person.id && actor.placeId !== from.person.placeId)
650
- throw new LivingWorldError('effect-invalid', `${actor.name} cannot reach ${from.name}'s money from here`);
651
- if (!from.allowsDebt && from.balance() < effect.amount)
652
- throw new LivingWorldError('effect-invalid', `${from.name} holds ${from.balance()} ${unit}; ${effect.amount} is more than that`);
653
- from.set(cents(from.balance() - effect.amount));
654
- }
655
- if (to !== null)
656
- to.set(cents(to.balance() + effect.amount));
843
+ if (from.holderId !== actor.id)
844
+ throw new LivingWorldError('effect-invalid', `Only ${state.people[from.holderId]?.name ?? from.holderId} moves ${slot.id} from ${from.name}`);
845
+ }
846
+ if (from !== null && from.kind === HOLDER_PLACE && actor !== null && actor.placeId !== from.id) {
847
+ throw new LivingWorldError('effect-invalid', `${actor.name} cannot reach ${from.name}'s ${slot.id} from here`);
848
+ }
849
+ const fromValue = from === null ? (state.outside[slot.unit] ?? 0) : heldAmount(state, from.id, slot.id);
850
+ const toValue = to === null ? (state.outside[slot.unit] ?? 0) : heldAmount(state, to.id, slot.id);
851
+ if (from !== null && fromValue === undefined)
852
+ throw new LivingWorldError('effect-invalid', `${from.name} keeps none of ${slot.id}`);
853
+ if (to !== null && toValue === undefined)
854
+ throw new LivingWorldError('effect-invalid', `${to.name} keeps none of ${slot.id}`);
855
+ if (from !== null && slot.min !== null && fromValue - effect.amount < slot.min) {
856
+ throw new LivingWorldError('effect-invalid', `${from.name} holds ${fromValue} ${unit}; ${effect.amount} would leave less than ${slot.min}`);
857
+ }
858
+ if (to !== null && slot.max !== null && toValue + effect.amount > slot.max) {
859
+ throw new LivingWorldError('effect-invalid', `${to.name} holds ${toValue} ${unit}; ${effect.amount} would take it past ${slot.max}`);
860
+ }
861
+ if (from === null)
862
+ state.outside[slot.unit] = (state.outside[slot.unit] ?? 0) - effect.amount;
863
+ else
864
+ setHeldAmount(state, from.id, slot.id, fromValue - effect.amount);
865
+ if (to === null)
866
+ state.outside[slot.unit] = (state.outside[slot.unit] ?? 0) + effect.amount;
867
+ else
868
+ setHeldAmount(state, to.id, slot.id, toValue + effect.amount);
657
869
  return;
658
870
  }
659
871
  case 'relationship': {
@@ -705,23 +917,49 @@ function applyEffect(state, event, effect, replay) {
705
917
  const index = replay?.get(person.id);
706
918
  if (index ? index.has(effect.commitmentId) : person.commitments.some(commitment => commitment.id === effect.commitmentId))
707
919
  throw new LivingWorldError('effect-invalid', `Commitment ${effect.commitmentId} already exists`);
708
- if (state.engine >= BOUNDED_PERSON_RECORDS_ENGINE && person.commitments.filter(item => item.status === 'open').length >= MAX_OPEN_COMMITMENTS) {
709
- throw new LivingWorldError('effect-invalid', `${person.name} already has ${MAX_OPEN_COMMITMENTS} open promises; settle one before adding another`);
710
- }
711
920
  // Those who perceived the event heard the promise; a message in the same event carries it to its recipients.
712
921
  const heard = [...(event.perceivedBy ?? event.witnessIds), effect.personId,
713
922
  ...event.effects.flatMap(item => item.kind === 'message' ? item.toIds : [])];
714
923
  const dueAt = effect.dueInMinutes === null ? null : event.at + effect.dueInMinutes;
715
924
  if (effect.placeId !== undefined)
716
925
  requirePlace(state, effect.placeId);
926
+ const open = person.commitments.filter(item => item.status === 'open');
927
+ if (!capsApply(state, event)) {
928
+ if (open.length >= BOUNDS.openCommitments)
929
+ throw new LivingWorldError('effect-invalid', `${person.name} already has ${BOUNDS.openCommitments} open promises; settle one before adding another`);
930
+ }
931
+ else if (dueAt !== null) {
932
+ if (open.filter(item => item.dueAt !== null).length >= MAX_OPEN_COMMITMENTS)
933
+ return;
934
+ if (open.length >= BOUNDS.openCommitments)
935
+ return;
936
+ }
937
+ else if (open.length >= BOUNDS.openCommitments) {
938
+ throw new LivingWorldError('effect-invalid', `${person.name} already has ${BOUNDS.openCommitments} open promises; settle one before adding another`);
939
+ }
717
940
  person.commitments.push({ id: effect.commitmentId, toId: effect.toId, text: effect.text, dueAt, ...(effect.placeId === undefined ? {} : { placeId: effect.placeId }), status: 'open', madeAt: event.at,
718
941
  madeSeq: event.seq, knownTo: [...new Set(heard)].sort() });
719
942
  index?.set(effect.commitmentId, person.commitments[person.commitments.length - 1]);
720
- // A promise to be somewhere at a time becomes a decision the promiser must make in time to get there,
721
- // one no routine plan puts aside.
722
- if (state.engine >= DEADLINE_ENGINE && dueAt !== null && effect.placeId !== undefined && !person.isPlayer) {
723
- insertScheduled(state, { id: generatedId(state.engine, 'keep', [effect.commitmentId]), at: Math.max(event.at + 1, dueAt - PROMISE_LEAD_MINUTES), personId: person.id, kind: 'plan',
724
- intent: `Keep your promise to ${state.people[effect.toId].name}: ${effect.text}`.slice(0, MAX_LINE), placeId: effect.placeId, targetId: effect.toId, sourceSeq: event.seq, importance: PROMISE_IMPORTANCE });
943
+ if ((dueAt !== null) && !person.isPlayer) {
944
+ const item = { id: generatedId(state.engine, 'keep', [effect.commitmentId]), at: Math.max(event.at + pace(state.calendar, 'speech'), dueAt - (effect.placeId === undefined ? 0 : pace(state.calendar, 'promiseLead'))),
945
+ personId: person.id, kind: 'plan', intent: phrase('commitment.keepOrBreak', { name: state.people[effect.toId].name, text: effect.text }).slice(0, MAX_LINE),
946
+ placeId: effect.placeId ?? null, targetId: effect.toId, sourceSeq: event.seq, importance: PROMISE_IMPORTANCE, decision: { kind: 'promise', id: effect.commitmentId } };
947
+ if (!owesRoom(state, item, event)) {
948
+ person.commitments.pop();
949
+ index?.delete(effect.commitmentId);
950
+ return;
951
+ }
952
+ insertScheduled(state, item);
953
+ }
954
+ else if ((dueAt !== null) && effect.placeId !== undefined && !person.isPlayer) {
955
+ const item = { id: generatedId(state.engine, 'keep', [effect.commitmentId]), at: Math.max(event.at + pace(state.calendar, 'speech'), dueAt - pace(state.calendar, 'promiseLead')), personId: person.id, kind: 'plan',
956
+ intent: phrase('commitment.keep', { name: state.people[effect.toId].name, text: effect.text }).slice(0, MAX_LINE), placeId: effect.placeId, targetId: effect.toId, sourceSeq: event.seq, importance: PROMISE_IMPORTANCE };
957
+ if (!owesRoom(state, item, event)) {
958
+ person.commitments.pop();
959
+ index?.delete(effect.commitmentId);
960
+ return;
961
+ }
962
+ insertScheduled(state, item);
725
963
  }
726
964
  return;
727
965
  }
@@ -733,6 +971,7 @@ function applyEffect(state, event, effect, replay) {
733
971
  if (commitment.status !== 'open')
734
972
  throw new LivingWorldError('effect-invalid', `Commitment ${effect.commitmentId} is already ${commitment.status}`);
735
973
  commitment.status = effect.status;
974
+ state.schedule = state.schedule.filter(item => !(item.decision?.kind === 'promise' && item.decision.id === effect.commitmentId));
736
975
  return;
737
976
  }
738
977
  case 'goal': {
@@ -797,36 +1036,42 @@ function applyEffect(state, event, effect, replay) {
797
1036
  throw new LivingWorldError('effect-invalid', `Scheduled item ${effect.scheduledId} already exists`);
798
1037
  if (effect.scheduleKind === 'deliver')
799
1038
  throw new LivingWorldError('effect-invalid', 'A delivery comes only from a dispatched message');
800
- if (effect.scheduleKind === 'back')
801
- throw new LivingWorldError('effect-invalid', 'A return comes only from someone going away');
802
- if (effect.scheduleKind === 'count')
803
- throw new LivingWorldError('effect-invalid', 'A vote opens and is counted only at its own written times');
1039
+ if (effect.scheduleKind === 'onstage')
1040
+ throw new LivingWorldError('effect-invalid', 'A return comes only from someone going offstage');
804
1041
  if (effect.scheduleKind === 'finish' && (effect.targetId === null || effect.placeId === null || effect.held === undefined))
805
1042
  throw new LivingWorldError('effect-invalid', 'A long act ends for its actor where it began, as it was ruled');
806
1043
  // Someone away answers a message once they are back; from engine 49, only one asleep at night waits.
807
- const away = effect.personId !== null && effect.scheduleKind === 'reply' ? state.people[effect.personId].away : undefined;
808
- const waits = away !== undefined && (state.engine < AWAY_REPLY_ENGINE || isNight(event.at + effect.inMinutes));
809
- insertScheduled(state, { id: effect.scheduledId, at: Math.max(event.at + effect.inMinutes, waits ? away.until : 0), personId: effect.personId, kind: effect.scheduleKind, intent: effect.intent, placeId: effect.placeId, targetId: effect.targetId, sourceSeq: event.seq, importance: effect.importance ?? event.importance,
1044
+ const offstage = effect.personId !== null && effect.scheduleKind === 'reply' ? state.people[effect.personId].offstage : undefined;
1045
+ const waits = offstage !== undefined && restingAt(state.calendar, event.at + effect.inMinutes);
1046
+ const item = { id: effect.scheduledId, at: Math.max(event.at + effect.inMinutes, waits ? offstage.until : 0), personId: effect.personId, kind: effect.scheduleKind, intent: effect.intent, placeId: effect.placeId, targetId: effect.targetId, sourceSeq: event.seq, importance: effect.importance ?? event.importance,
810
1047
  ...(effect.everyMinutes === undefined ? {} : { everyMinutes: effect.everyMinutes }), ...(effect.series === undefined ? {} : { series: effect.series }),
1048
+ ...(effect.chain === undefined ? {} : { chain: effect.chain }), ...(effect.link === undefined ? {} : { link: effect.link }),
811
1049
  ...(effect.beat === undefined ? {} : { beat: effect.beat }),
812
- ...(state.engine >= BOUNDED_IDENTIFIERS_ENGINE && effect.replanned ? { replanned: true } : {}),
813
- ...(effect.held === undefined ? {} : { held: { at: event.at, ...effect.held } }) });
1050
+ ...(effect.decision === undefined ? {} : { decision: effect.decision }),
1051
+ ...((effect.replanned) ? { replanned: true } : {}),
1052
+ ...((effect.selfPlanned) ? { selfPlanned: true } : {}),
1053
+ ...((effect.waitingForExchange) ? { waitingForExchange: true } : {}),
1054
+ ...(effect.held === undefined ? {} : { held: { at: event.at, ...effect.held } }) };
1055
+ if (!owesRoom(state, item, event))
1056
+ return;
1057
+ insertScheduled(state, item);
814
1058
  return;
815
1059
  }
816
1060
  case 'deadline.passed': {
817
1061
  state.passedDeadlines = [...(state.passedDeadlines ?? []), { what: effect.what, at: event.at, outcome: effect.outcome,
818
- ...(effect.averted && state.engine >= AVERTED_ENGINE ? { averted: true } : {}) }].slice(-8);
1062
+ ...((effect.averted) ? { averted: true } : {}) }].slice(-8);
819
1063
  return;
820
1064
  }
821
1065
  case 'unschedule': {
822
1066
  const index = state.schedule.findIndex(item => item.id === effect.scheduledId);
823
- const predicted = index === -1 ? plain(state.meterSchedule).findIndex(item => item.id === effect.scheduledId) : -1;
824
- if (index === -1 && predicted === -1)
825
- throw new LivingWorldError('effect-invalid', `Unknown scheduled item ${effect.scheduledId}`);
826
- if (index !== -1)
1067
+ if (index !== -1) {
827
1068
  state.schedule.splice(index, 1);
828
- else
829
- state.meterSchedule = plain(state.meterSchedule).filter((_, index) => index !== predicted);
1069
+ return;
1070
+ }
1071
+ const predicted = state.predictions.items.findIndex(item => item.id === effect.scheduledId);
1072
+ if (predicted === -1)
1073
+ throw new LivingWorldError('effect-invalid', `Unknown scheduled item ${effect.scheduledId}`);
1074
+ state.predictions.items.splice(predicted, 1);
830
1075
  return;
831
1076
  }
832
1077
  case 'plan': {
@@ -836,8 +1081,10 @@ function applyEffect(state, event, effect, replay) {
836
1081
  if (effect.plan?.targetId)
837
1082
  requirePerson(state, effect.plan.targetId);
838
1083
  person.plan = effect.plan;
1084
+ if ((effect.plan))
1085
+ person.planBasisSeq = effect.basisSeq ?? event.seq;
839
1086
  // What someone has been doing lately stays in view when they decide again.
840
- if (effect.plan && state.engine >= CHRONICLE_ENGINE)
1087
+ if ((effect.plan) && ((effect.deciding !== true)))
841
1088
  person.planHistory = [...(person.planHistory ?? []), { at: event.at, intent: effect.plan.intent }].slice(-6);
842
1089
  return;
843
1090
  }
@@ -870,15 +1117,17 @@ function applyEffect(state, event, effect, replay) {
870
1117
  case 'tension.create': {
871
1118
  if (state.tensions.some(tension => tension.id === effect.tensionId))
872
1119
  throw new LivingWorldError('effect-invalid', `Tension ${effect.tensionId} already exists`);
1120
+ if (state.tensions.filter(tension => tension.status === 'open').length >= BOUNDS.openTensions) {
1121
+ throw new LivingWorldError('effect-invalid', `The world already has ${BOUNDS.openTensions} open problems; settle one before adding another`);
1122
+ }
873
1123
  for (const participant of effect.participantIds)
874
1124
  requirePerson(state, participant);
875
1125
  const playerCanSee = (event.perceivedBy ?? event.witnessIds).includes(state.playerId)
876
1126
  && (event.visibleTensionIds ?? (event.observed === undefined ? [effect.tensionId] : [])).includes(effect.tensionId);
877
- const modern = state.engine >= PROBLEM_VIEW_ENGINE;
878
1127
  state.tensions.push({ id: effect.tensionId, title: effect.title, summary: effect.summary, participantIds: [...effect.participantIds], status: 'open', resolution: null, changedAt: event.at,
879
1128
  ...(effect.openedBy === undefined ? {} : { openedBy: effect.openedBy }),
880
- playerView: playerCanSee && !modern ? { title: effect.title.slice(0, 200), summary: event.observed ?? effect.summary, status: 'open', resolution: null, latest: null } : null });
881
- if (playerCanSee && modern)
1129
+ playerView: (null) });
1130
+ if ((playerCanSee))
882
1131
  seeTension(state, state.tensions.at(-1), event, 'created');
883
1132
  return;
884
1133
  }
@@ -886,6 +1135,22 @@ function applyEffect(state, event, effect, replay) {
886
1135
  const tension = state.tensions.find(candidate => candidate.id === effect.tensionId);
887
1136
  if (!tension)
888
1137
  throw new LivingWorldError('effect-invalid', `Unknown tension ${effect.tensionId}`);
1138
+ const decisionSettles = Object.values(state.entities).some(entity => {
1139
+ if (!isDecisionKind(state.kinds[entity.kindId]))
1140
+ return false;
1141
+ const { settles } = entity.properties;
1142
+ return settles?.value === effect.tensionId;
1143
+ });
1144
+ if (effect.status === 'settled' && !fromLaw && !opening && decisionSettles)
1145
+ throw new LivingWorldError('effect-invalid', phrase('effect.tensionSettled'));
1146
+ if (effect.status === 'open' && !opening)
1147
+ for (const candidate of Object.values(state.entities)) {
1148
+ if (!isDecisionKind(state.kinds[candidate.kindId]))
1149
+ continue;
1150
+ const { settles } = candidate.properties;
1151
+ if (settles?.value === effect.tensionId)
1152
+ scheduleDecisionVotes(state, event, candidate.id);
1153
+ }
889
1154
  const settling = tension.status === 'open' && effect.status === 'settled';
890
1155
  tension.status = effect.status;
891
1156
  tension.changedAt = event.at;
@@ -899,14 +1164,10 @@ function applyEffect(state, event, effect, replay) {
899
1164
  state.stoppingPoint = { at: event.at, tensionId: tension.id, title: tension.title, summary: tension.resolution ?? tension.summary };
900
1165
  if ((event.perceivedBy ?? event.witnessIds).includes(state.playerId)
901
1166
  && (event.visibleTensionIds ?? (event.observed === undefined ? [effect.tensionId] : [])).includes(effect.tensionId)) {
902
- if (state.engine >= PROBLEM_VIEW_ENGINE) {
1167
+ {
903
1168
  seeTension(state, tension, event, 'changed');
904
1169
  return;
905
1170
  }
906
- tension.playerView = { title: tension.playerView?.title ?? tension.title.slice(0, 200),
907
- summary: tension.playerView?.summary ?? event.observed ?? tension.summary, status: tension.status,
908
- resolution: tension.status === 'settled' ? event.observed ?? tension.resolution : null,
909
- latest: tension.playerView ? event.observed ?? effect.note : null };
910
1171
  }
911
1172
  return;
912
1173
  }
@@ -928,11 +1189,11 @@ function applyEffect(state, event, effect, replay) {
928
1189
  state.forcedEnding = effect.reason;
929
1190
  return;
930
1191
  }
931
- case 'person.away': {
1192
+ case 'person.offstage': {
932
1193
  const person = requirePerson(state, effect.personId);
933
1194
  if (person.isPlayer)
934
1195
  throw new LivingWorldError('effect-invalid', 'The player decides where they go');
935
- if (person.departed || person.away)
1196
+ if (person.departed || person.offstage)
936
1197
  throw new LivingWorldError('effect-invalid', `${person.name} is not here to leave`);
937
1198
  if (person.incapacitated)
938
1199
  throw new LivingWorldError('effect-invalid', `${person.name} cannot leave while unable to act`);
@@ -942,33 +1203,30 @@ function applyEffect(state, event, effect, replay) {
942
1203
  if (gate)
943
1204
  throw new LivingWorldError('effect-invalid', `${gate.name} (${gate.entityId}) holds ${person.name}; to free them, set its ${gate.propertyId} first in the same ruling, or keep them here`);
944
1205
  const until = event.at + effect.minutes;
945
- person.away = { at: event.at, until, reason: effect.reason };
946
- person.plan = { intent: effect.reason, placeId: null, targetId: null, dueAt: until };
1206
+ person.offstage = { at: event.at, until, why: effect.why };
1207
+ person.plan = { intent: effect.why, placeId: null, targetId: null, dueAt: until };
947
1208
  leaveConversations(state, person.id, person.placeId, event.at);
948
1209
  // What they meant to do here waits; messages to them are answered when they are back.
949
1210
  // From engine 42 a long act under way is set aside too.
950
1211
  state.schedule = state.schedule.filter(item => (item.personId !== person.id || item.kind === 'reply')
951
- && !(state.engine >= AWAY_APART_ENGINE && item.kind === 'finish' && item.targetId === person.id))
1212
+ && !((item.kind === 'finish') && item.targetId === person.id))
952
1213
  .map(item => item.personId === person.id && item.at < until
953
- && !(state.engine >= AWAY_REPLY_ENGINE && item.kind === 'reply' && !isNight(item.at)) ? { ...item, at: until } : item)
1214
+ && !((item.kind === 'reply') && !restingAt(state.calendar, item.at)) ? { ...item, at: until } : item)
954
1215
  .sort((left, right) => left.at - right.at || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
955
- insertScheduled(state, { id: generatedId(state.engine, 'back', [event.seq, person.id], `back-${event.seq}-${person.id}`.slice(0, 64)), at: until, personId: person.id, kind: 'back', intent: effect.reason,
1216
+ insertScheduled(state, { id: generatedId(state.engine, 'onstage', [event.seq, person.id], `onstage-${event.seq}-${person.id}`.slice(0, 64)), at: until, personId: person.id, kind: 'onstage', intent: effect.why,
956
1217
  placeId: person.placeId, targetId: null, sourceSeq: event.seq, importance: 3 });
957
1218
  // Seen going, they are known to have left for a while.
958
1219
  if (event.witnessIds.includes(state.playerId) || event.perceivedBy?.includes(state.playerId))
959
- state.sightings[person.id] = { placeId: person.placeId, at: event.at, away: true };
1220
+ state.sightings[person.id] = { placeId: person.placeId, at: event.at, offstage: true };
960
1221
  return;
961
1222
  }
962
- case 'person.back': {
1223
+ case 'person.onstage': {
963
1224
  const person = requirePerson(state, effect.personId);
964
- if (!person.away)
965
- throw new LivingWorldError('effect-invalid', `${person.name} is not away`);
966
- delete person.away;
1225
+ if (!person.offstage)
1226
+ throw new LivingWorldError('effect-invalid', `${person.name} is not offstage`);
1227
+ delete person.offstage;
967
1228
  person.arrivedSeq = event.seq;
968
- if (state.engine < SEEN_AT_EVENTS_ENGINE)
969
- seeWhatLiesHere(state, person.id, person.placeId);
970
- if (state.engine >= REST_ENGINE)
971
- person.restedAt = event.at;
1229
+ person.restedAt = event.at;
972
1230
  if (state.people[state.playerId].placeId === person.placeId)
973
1231
  state.sightings[person.id] = { placeId: person.placeId, at: event.at };
974
1232
  return;
@@ -998,54 +1256,22 @@ function applyEffect(state, event, effect, replay) {
998
1256
  const definition = effect.definition;
999
1257
  if (state.kinds[definition.id])
1000
1258
  throw new LivingWorldError('effect-invalid', `Kind ${definition.id} already exists`);
1001
- if (event.kind !== 'opening' && definition.mechanics.some(mechanic => mechanic.kind === 'signal' && mechanic.channel === GLOBAL_SIGNAL_CHANNEL)) {
1002
- throw new LivingWorldError('effect-invalid', `Only the world's own data may define what reaches everyone, as ${definition.id} would`);
1003
- }
1004
- const propertyIds = new Set(definition.properties.map(property => property.id));
1005
- const relationIds = new Set(definition.relations.map(relation => relation.id));
1006
- if (propertyIds.size !== definition.properties.length || relationIds.size !== definition.relations.length) {
1007
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} repeats a slot id`);
1008
- }
1009
- for (const relation of definition.relations) {
1010
- if (relation.targetKindId !== definition.id && !state.kinds[relation.targetKindId]) {
1011
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} refers to unknown target kind ${relation.targetKindId}`);
1012
- }
1013
- }
1014
- for (const mechanic of definition.mechanics) {
1015
- if ('propertyId' in mechanic && mechanic.propertyId !== null && !propertyIds.has(mechanic.propertyId)) {
1016
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} has unknown property ${mechanic.propertyId}`);
1017
- }
1018
- if ('relationId' in mechanic && mechanic.relationId !== null && !relationIds.has(mechanic.relationId)) {
1019
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} has unknown relation ${mechanic.relationId}`);
1020
- }
1021
- if (mechanic.kind === 'spread' && definition.properties.find(property => property.id === mechanic.propertyId)?.type !== 'level') {
1022
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} spreads a property that is not a level`);
1023
- }
1024
- if (mechanic.kind === 'authority' && (mechanic.propertyId === null) === (mechanic.relationId === null)) {
1025
- throw new LivingWorldError('effect-invalid', 'Authority needs exactly one property or relation');
1026
- }
1027
- const targetProperty = 'propertyId' in mechanic ? definition.properties.find(property => property.id === mechanic.propertyId) : undefined;
1028
- if ((mechanic.kind === 'change' && (mechanic.onEvent
1029
- ? mechanic.deltaPerMinute !== 0 || !targetProperty || !valueMatchesType(targetProperty.type, mechanic.onEvent.value)
1030
- : targetProperty?.type !== 'number'))
1031
- || mechanic.kind === 'trigger' && targetProperty?.type !== 'number') {
1032
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} changes a property that is not a number`);
1033
- }
1034
- if (mechanic.kind === 'change' && mechanic.onEvent
1035
- && definition.properties.find(property => property.id === mechanic.onEvent.subjectPropertyId)?.type !== 'id') {
1036
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} needs an id subject property for event change`);
1037
- }
1038
- if (mechanic.kind === 'gate' && definition.properties.find(property => property.id === mechanic.subjectPropertyId)?.type !== 'id') {
1039
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} needs an id subject property for its gate`);
1040
- }
1041
- if (mechanic.kind === 'gate' && mechanic.atLeast !== undefined && targetProperty?.type !== 'level') {
1042
- throw new LivingWorldError('effect-invalid', `Kind ${definition.id} needs a level property for a level gate`);
1043
- }
1044
- }
1259
+ checkKindForWorld(state, definition, event);
1045
1260
  state.kinds[definition.id] = definition;
1046
1261
  state.kindRequests = state.kindRequests.filter(request => request.id !== definition.id);
1047
1262
  return;
1048
1263
  }
1264
+ case 'note': {
1265
+ const previous = state.facetUse.items[effect.facet];
1266
+ state.facetUse.items[effect.facet] = {
1267
+ count: (previous?.count ?? 0) + 1,
1268
+ firstSeq: previous?.firstSeq ?? event.seq,
1269
+ lastSeq: event.seq,
1270
+ text: effect.text,
1271
+ kindId: effect.kindId ?? previous?.kindId ?? null,
1272
+ };
1273
+ return;
1274
+ }
1049
1275
  case 'kind.request': {
1050
1276
  if (state.kinds[effect.request.id])
1051
1277
  return;
@@ -1057,77 +1283,64 @@ function applyEffect(state, event, effect, replay) {
1057
1283
  case 'entity.create': {
1058
1284
  if (!state.kinds[effect.kindId])
1059
1285
  throw new LivingWorldError('effect-invalid', `Unknown kind ${effect.kindId}`);
1060
- if (effect.placeId !== null)
1061
- requirePlace(state, effect.placeId);
1286
+ requireContainer(state, effect.containerId);
1062
1287
  if (state.entities[effect.entityId] || state.people[effect.entityId] || state.places[effect.entityId] || state.objects[effect.entityId]) {
1063
1288
  throw new LivingWorldError('effect-invalid', `Entity ${effect.entityId} already exists`);
1064
1289
  }
1065
- if ((effect.condition !== undefined || effect.holderId !== undefined) && effect.placeId === null) {
1290
+ const decision = isDecisionKind(state.kinds[effect.kindId]);
1291
+ if (!opening && decision) {
1292
+ const { settles } = (effect.initialProperties ?? {});
1293
+ const twin = Object.values(state.entities).find(candidate => {
1294
+ const { settles: candidateSettles } = candidate.properties;
1295
+ return candidate.kindId === effect.kindId
1296
+ && (candidate.containerId === effect.containerId || (typeof settles === 'string' && candidateSettles?.value === settles));
1297
+ });
1298
+ if (twin)
1299
+ throw new LivingWorldError('effect-invalid', phrase('effect.decisionExists', { name: twin.name }));
1300
+ }
1301
+ const twin = Object.values(state.entities).find(candidate => candidate.kindId === effect.kindId && candidate.name === effect.name && candidate.containerId === effect.containerId);
1302
+ if (!opening && twin)
1303
+ throw new LivingWorldError('effect-invalid', phrase('effect.duplicate', { name: effect.name, other: twin.name }));
1304
+ if (effect.condition !== undefined && effect.containerId === null) {
1066
1305
  throw new LivingWorldError('effect-invalid', `${effect.name} belongs to no place, so it has no condition and no one holds it`);
1067
1306
  }
1068
- if (effect.holderId !== undefined && state.engine >= UNHELD_ENGINE && neverHeld(state.engine, effect.kindId, state.kinds[effect.kindId])) {
1307
+ if (effect.containerId !== null && state.people[effect.containerId] !== undefined && neverHeld(state.kinds[effect.kindId])) {
1069
1308
  throw new LivingWorldError('effect-invalid', `${effect.name} stays where it is; no one holds it`);
1070
1309
  }
1071
- if (effect.holderId !== undefined) {
1072
- const holder = requirePerson(state, effect.holderId);
1073
- if (holder.departed || holder.away || holder.placeId !== effect.placeId)
1074
- throw new LivingWorldError('effect-invalid', `${holder.name} is not in ${state.places[effect.placeId]?.name ?? effect.placeId} to hold ${effect.name}`);
1075
- }
1076
- const deciding = effect.kindId === 'decision' && state.engine >= VOTES_ENGINE;
1077
- if ((effect.memberIds !== undefined || effect.settles !== undefined || effect.transfers !== undefined) && !deciding)
1078
- throw new LivingWorldError('effect-invalid', `Only a decision has members and settles a problem`);
1079
- if (deciding) {
1080
- if (effect.placeId === null)
1081
- throw new LivingWorldError('effect-invalid', `${effect.name} needs the place where it is voted on`);
1082
- if (!effect.memberIds?.length)
1083
- throw new LivingWorldError('effect-invalid', `${effect.name} needs the members who vote on it`);
1084
- for (const memberId of effect.memberIds)
1085
- requirePerson(state, memberId);
1086
- if (effect.settles !== undefined && !state.tensions.some(tension => tension.id === effect.settles))
1087
- throw new LivingWorldError('effect-invalid', `Unknown problem ${effect.settles}`);
1088
- // A vote called during play goes to the one already open in its room; a world's own data may hold several.
1089
- const open = state.engine >= OPEN_NOW_ENGINE && event.kind !== 'opening'
1090
- ? (state.openDecisionIds ?? []).map(id => state.entities[id]).find(other => other?.placeId === effect.placeId) : undefined;
1091
- if (open)
1092
- throw new LivingWorldError('effect-invalid', `${open.name} is already open to votes here; cast votes on it, not on a new one`);
1093
- }
1094
- // A world's data may say who knows one of its things; they, its holder and its members do.
1310
+ if (effect.containerId !== null && state.people[effect.containerId] !== undefined) {
1311
+ const holder = requirePerson(state, effect.containerId);
1312
+ if (holder.departed || holder.offstage)
1313
+ throw new LivingWorldError('effect-invalid', `${holder.name} is not here to hold ${effect.name}`);
1314
+ }
1095
1315
  if ((effect.knownTo !== undefined || effect.hidden) && !opening)
1096
1316
  throw new LivingWorldError('effect-invalid', 'Only a world\'s opening says who knows a thing, or hides it');
1097
1317
  for (const knower of effect.knownTo ?? [])
1098
1318
  requirePerson(state, knower);
1099
1319
  const knowers = effect.knownTo === undefined ? knownTo
1100
- : [...new Set([...effect.knownTo, ...(effect.holderId === undefined ? [] : [effect.holderId]), ...(effect.memberIds ?? [])])].sort();
1101
- state.entities[effect.entityId] = { id: effect.entityId, kindId: effect.kindId, name: effect.name, placeId: effect.placeId, holderId: effect.holderId ?? null,
1102
- condition: effect.condition ?? null, properties: {}, relations: {}, introducedSeq: event.seq, knownTo: knowers, ...(effect.hidden ? { hidden: true } : {}),
1103
- ...(deciding ? { members: [...new Set(effect.memberIds)], ballots: {}, ...(effect.settles === undefined ? {} : { settles: effect.settles }),
1104
- ...(effect.transfers === undefined ? {} : { transfers: effect.transfers }) } : {}) };
1105
- if (deciding) {
1106
- state.entities[effect.entityId].condition = withSide(state.entities[effect.entityId], 'votes', tally(state.entities[effect.entityId]), state.engine >= WHOLE_SIDES_ENGINE, state.engine >= SIDE_ORDER_ENGINE);
1107
- state.openDecisionIds = [...(state.openDecisionIds ?? []), effect.entityId];
1108
- }
1109
- if (effect.placeId === null)
1110
- state.globalEntityIds.push(effect.entityId);
1320
+ : [...new Set([...effect.knownTo, ...(effect.containerId === null || state.people[effect.containerId] === undefined ? [] : [effect.containerId])])].sort();
1321
+ state.entities[effect.entityId] = { id: effect.entityId, kindId: effect.kindId, name: effect.name, containerId: effect.containerId,
1322
+ condition: effect.condition ?? null, properties: {}, relations: {}, introducedSeq: event.seq, knownTo: knowers, ...(effect.hidden ? { hidden: true } : {}) };
1323
+ if (effect.containerId === null)
1324
+ state.globalEntityIds = [...state.globalEntityIds, effect.entityId];
1111
1325
  else
1112
- (state.entityPlaceIds[effect.placeId] ??= []).push(effect.entityId);
1326
+ state.within[effect.containerId] = [...(state.within[effect.containerId] ?? []), effect.entityId];
1113
1327
  indexPlaceless(state, effect.entityId);
1114
1328
  // A paper made sealed is sealed after its words are written.
1115
- for (const [propertyId, value] of Object.entries(effect.initialProperties ?? {}).sort(([left], [right]) => Number(left === 'sealed') - Number(right === 'sealed'))) {
1116
- applyEffect(state, event, { kind: 'property.set', entityId: effect.entityId, propertyId, value });
1117
- }
1118
- // From engine 50 a vote called during play without a closing time closes two game hours after it opens.
1119
- const called = deciding && event.kind !== 'opening' ? readEntity(state, effect.entityId) : undefined;
1120
- if (called && state.engine >= VOTE_CLOSES_ENGINE && called.properties['closes-at'] === undefined) {
1121
- const opensAt = called.properties['opens-at']?.value;
1122
- applyEffect(state, event, { kind: 'property.set', entityId: effect.entityId, propertyId: 'closes-at',
1123
- value: (typeof opensAt === 'number' && opensAt > event.at ? opensAt : event.at) + VOTE_OPEN_MINUTES });
1124
- }
1125
- // A vote called during play with no later opening time opens now, so each member gets a turn at once.
1126
- if (deciding && state.engine >= OPEN_NOW_ENGINE && event.kind !== 'opening'
1127
- && !state.schedule.some(item => item.count?.entityId === effect.entityId && item.count.opens)) {
1128
- insertScheduled(state, { id: generatedId(state.engine, 'opens', [event.seq, effect.entityId], `opens-${event.seq}-${effect.entityId}`.slice(0, 64)), at: event.at, personId: null, kind: 'count',
1129
- intent: `Voting opens on ${effect.name}`.slice(0, MAX_LINE), placeId: effect.placeId, targetId: null, sourceSeq: event.seq, importance: 5,
1130
- count: { entityId: effect.entityId, opens: true } });
1329
+ const sealedLast = (name) => name === 'sealed' ? 1 : 0;
1330
+ for (const [propertyId, value] of Object.entries(effect.initialProperties ?? {}).sort(([left], [right]) => sealedLast(left) - sealedLast(right))) {
1331
+ const slot = state.kinds[effect.kindId]?.properties.find(property => property.id === propertyId);
1332
+ if (slot?.type === 'series' && Array.isArray(value)) {
1333
+ state.entities[effect.entityId].properties[propertyId] = { value, changedSeq: event.seq, previousSeq: null, knownTo: opening ? state.entities[effect.entityId].knownTo : knownTo, updatedAt: event.at };
1334
+ }
1335
+ else {
1336
+ applyEffect(state, event, { kind: 'property.set', entityId: effect.entityId, propertyId, value }, undefined, false, true);
1337
+ }
1338
+ }
1339
+ if (decision) {
1340
+ const settlers = effect.initialProperties?.settles;
1341
+ const deferred = typeof settlers === 'string' && state.schedule.some(item => item.beat?.then?.tension?.id === settlers);
1342
+ if (!deferred)
1343
+ scheduleDecisionVotes(state, event, effect.entityId);
1131
1344
  }
1132
1345
  return;
1133
1346
  }
@@ -1135,23 +1348,25 @@ function applyEffect(state, event, effect, replay) {
1135
1348
  const entity = state.entities[effect.entityId];
1136
1349
  if (!entity)
1137
1350
  throw new LivingWorldError('effect-invalid', `Unknown entity ${effect.entityId}`);
1138
- if (entity.placeId === null)
1351
+ if (entity.containerId === null)
1139
1352
  throw new LivingWorldError('effect-invalid', `${entity.name} is nowhere to be held; only a thing that is somewhere can change hands`);
1140
- if ((effect.holderId === null) === (effect.placeId === null))
1141
- throw new LivingWorldError('effect-invalid', `${entity.name} goes either to a holder or to a place`);
1142
- const at = state.places[entity.placeId]?.name ?? entity.placeId;
1143
- if (effect.holderId !== null && state.engine >= UNHELD_ENGINE && neverHeld(state.engine, entity.kindId, state.kinds[entity.kindId])) {
1353
+ requireContainer(state, effect.containerId);
1354
+ const where = siteOf(state, entity.containerId);
1355
+ const at = state.places[where ?? '']?.name ?? state.people[entity.containerId]?.name ?? entity.containerId;
1356
+ if ((state.people[effect.containerId] !== undefined) && neverHeld(state.kinds[entity.kindId])) {
1144
1357
  throw new LivingWorldError('effect-invalid', `${entity.name} stays where it is; no one holds it`);
1145
1358
  }
1146
- if (effect.holderId !== null) {
1147
- const holder = requirePerson(state, effect.holderId);
1148
- if (holder.departed || holder.away || holder.placeId !== entity.placeId) {
1359
+ if (state.people[effect.containerId] !== undefined) {
1360
+ const holder = requirePerson(state, effect.containerId);
1361
+ if (holder.departed || holder.offstage || holder.placeId !== where) {
1149
1362
  throw new LivingWorldError('effect-invalid', `${entity.name} is in ${at}, not with ${holder.name}`);
1150
1363
  }
1151
1364
  }
1152
- if (effect.placeId !== null && effect.placeId !== entity.placeId)
1365
+ if (state.places[effect.containerId] !== undefined && where !== null && effect.containerId !== where) {
1153
1366
  throw new LivingWorldError('effect-invalid', `${entity.name} can only be set down in ${at}, where it is`);
1154
- entity.holderId = effect.holderId;
1367
+ }
1368
+ moveWithin(state, entity.id, effect.containerId);
1369
+ rescheduleContents(state, entity.id, siteOf(state, effect.containerId));
1155
1370
  entity.knownTo = [...new Set([...entity.knownTo, ...(event.perceivedBy ?? event.witnessIds), ...(event.actorId ? [event.actorId] : [])])];
1156
1371
  return;
1157
1372
  }
@@ -1159,12 +1374,42 @@ function applyEffect(state, event, effect, replay) {
1159
1374
  const entity = state.entities[effect.entityId];
1160
1375
  if (!entity)
1161
1376
  throw new LivingWorldError('effect-invalid', `Unknown entity ${effect.entityId}`);
1162
- if (entity.placeId === null)
1377
+ if (entity.containerId === null)
1163
1378
  throw new LivingWorldError('effect-invalid', `${entity.name} is nowhere to be seen; only a thing that is somewhere shows a condition`);
1164
- if (entity.kindId === 'decision' && state.engine >= COUNT_ONLY_ENGINE) {
1165
- throw new LivingWorldError('effect-invalid', `The count on ${entity.name} is the engine's; a member casts a ballot, and the vote closes at its time or with decision.close`);
1379
+ entity.condition = (withSide(entity, effect.aspect, effect.condition, true, true));
1380
+ entity.knownTo = [...new Set([...entity.knownTo, ...(event.perceivedBy ?? event.witnessIds), ...(event.actorId ? [event.actorId] : [])])];
1381
+ return;
1382
+ }
1383
+ case 'cell.add': {
1384
+ const entity = state.entities[effect.entityId];
1385
+ if (!entity)
1386
+ throw new LivingWorldError('effect-invalid', `Unknown entity ${effect.entityId}`);
1387
+ const definition = state.kinds[entity.kindId];
1388
+ const properties = definition.properties;
1389
+ const slot = properties.find(property => property.id === effect.slotId);
1390
+ if (!slot || slot.type !== 'series')
1391
+ throw new LivingWorldError('effect-invalid', `${entity.name} has no series ${effect.slotId}`);
1392
+ if (slot.options !== undefined && !slot.options.includes(effect.option)) {
1393
+ throw new LivingWorldError('effect-invalid', `${effect.option} is not one of ${slot.options.join(', ')} for ${entity.name}`);
1394
+ }
1395
+ const person = requirePerson(state, effect.personId);
1396
+ const decision = isDecisionKind(definition);
1397
+ if (decision && !opening) {
1398
+ if (slot.options === undefined)
1399
+ throw new LivingWorldError('effect-invalid', phrase('effect.membersOpening', { name: entity.name, slot: slot.id }));
1400
+ if (effect.personId !== event.actorId)
1401
+ throw new LivingWorldError('effect-invalid', phrase('effect.choiceOwn', { name: person.name, slot: slot.id }));
1402
+ }
1403
+ if (person.departed || person.offstage
1404
+ || (entity.containerId !== null && siteOf(state, entity.containerId) !== person.placeId && entity.containerId !== person.id)) {
1405
+ throw new LivingWorldError('effect-invalid', `${person.name} is not with ${entity.name} to mark it`);
1406
+ }
1407
+ const prior = entity.properties[effect.slotId];
1408
+ const entries = Array.isArray(prior?.value) ? prior.value : [];
1409
+ if (!entries.some(entry => entry.option === effect.option && entry.personId === effect.personId)) {
1410
+ entity.properties[effect.slotId] = { value: [...entries, { option: effect.option, personId: effect.personId, at: event.at, seq: event.seq }].slice(-64),
1411
+ changedSeq: event.seq, previousSeq: prior?.changedSeq ?? null, knownTo: opening ? entity.knownTo : knownTo, updatedAt: event.at };
1166
1412
  }
1167
- entity.condition = state.engine >= CONDITION_SIDES_ENGINE ? withSide(entity, effect.aspect, effect.condition, state.engine >= WHOLE_SIDES_ENGINE, state.engine >= SIDE_ORDER_ENGINE) : effect.condition;
1168
1413
  entity.knownTo = [...new Set([...entity.knownTo, ...(event.perceivedBy ?? event.witnessIds), ...(event.actorId ? [event.actorId] : [])])];
1169
1414
  return;
1170
1415
  }
@@ -1173,40 +1418,38 @@ function applyEffect(state, event, effect, replay) {
1173
1418
  if (!entity)
1174
1419
  throw new LivingWorldError('effect-invalid', `Unknown entity ${effect.entityId}`);
1175
1420
  const definition = state.kinds[entity.kindId];
1176
- const property = definition.properties.find(slot => slot.id === effect.propertyId);
1421
+ const properties = definition.properties;
1422
+ const property = properties.find(slot => slot.id === effect.propertyId);
1177
1423
  if (!property)
1178
1424
  throw new LivingWorldError('effect-invalid', `Unknown property ${effect.propertyId}`);
1179
- const authority = definition.mechanics.filter((mechanic) => mechanic.kind === 'authority' && mechanic.propertyId === effect.propertyId);
1180
- if (event.actorId !== null && authority.length > 0 && !authority.some(mechanic => state.people[event.actorId]?.roleId === mechanic.roleId)) {
1181
- throw new LivingWorldError('effect-invalid', `Changing ${effect.propertyId} needs authority role ${authority.map(mechanic => mechanic.roleId).join(' or ')}`);
1425
+ if (!opening && !fromLaw && !fromCreate && properties.some(slot => slot.type === 'series' && slot.options?.length)
1426
+ && properties.some(slot => slot.type === 'series' && !slot.options?.length)) {
1427
+ throw new LivingWorldError('effect-invalid', phrase('effect.decisionRules', { name: entity.name }));
1182
1428
  }
1183
1429
  if (effect.value !== null && !valueMatchesType(property.type, effect.value)) {
1184
1430
  throw new LivingWorldError('effect-invalid', `Property ${effect.propertyId} needs a ${property.type} value`);
1185
1431
  }
1186
1432
  if (effect.value !== null && property.type === 'id' && !readEntity(state, String(effect.value))
1187
- && !state.people[String(effect.value)] && !state.places[String(effect.value)] && !state.objects[String(effect.value)]) {
1433
+ && !state.people[String(effect.value)] && !state.places[String(effect.value)] && !state.objects[String(effect.value)]
1434
+ && !(property.target === 'tension' && state.tensions.some(tension => tension.id === effect.value))) {
1188
1435
  throw new LivingWorldError('effect-invalid', `Property ${effect.propertyId} refers to an unknown entity`);
1189
1436
  }
1190
- // A decision's terms are fixed once anyone has voted on it.
1191
- if (entity.members !== undefined && (Object.keys(entity.ballots ?? {}).length > 0 || entity.result !== undefined)) {
1192
- throw new LivingWorldError('effect-invalid', `${entity.name} is being voted on; its terms no longer change`);
1193
- }
1194
- if (effect.propertyId !== 'sealed' && sealedPaper(state.engine, entity)) {
1195
- throw new LivingWorldError('effect-invalid', `${entity.name} is sealed; open it first, by setting sealed to false`);
1196
- }
1197
- if (effect.value !== null && namesPerson(state.engine, entity.kindId, effect.propertyId) && !state.people[String(effect.value)]) {
1437
+ if (property.type === 'series' && !opening)
1438
+ throw new LivingWorldError('effect-invalid', `${effect.propertyId} is a series; add to it instead`);
1439
+ if (sealedSlot(state, entity, effect.propertyId))
1440
+ throw new LivingWorldError('effect-invalid', `${entity.name} is sealed; open it first`);
1441
+ if (effect.value !== null && namesPerson(entity.kindId, effect.propertyId) && !state.people[String(effect.value)]) {
1198
1442
  throw new LivingWorldError('effect-invalid', `The ${effect.propertyId} of ${definition.name} ${entity.name} names a person, and ${String(effect.value)} is not one`);
1199
1443
  }
1200
- if (effect.value !== null && oneEachSlot(state.engine, entity.kindId) === effect.propertyId) {
1444
+ if (effect.value !== null && oneEachSlot(entity.kindId) === effect.propertyId) {
1201
1445
  const other = Object.values(state.entities).find(candidate => candidate.id !== entity.id && candidate.kindId === entity.kindId
1202
1446
  && candidate.properties[effect.propertyId]?.value === effect.value);
1203
1447
  if (other)
1204
1448
  throw new LivingWorldError('effect-invalid', `${state.people[String(effect.value)]?.name ?? effect.value} already has ${definition.name} ${other.name}: change that one instead`);
1205
1449
  }
1206
1450
  const previousSeq = entity.properties[effect.propertyId]?.changedSeq ?? null;
1207
- const previousValue = state.engine < LAZY_METER_ENGINE ? entity.properties[effect.propertyId]?.value : currentValue(state, entity, effect.propertyId, event.at);
1208
- if (state.engine >= LAZY_METER_ENGINE)
1209
- keepPassedCrossings(state, entity.id, effect.propertyId, event.at);
1451
+ const previousValue = (currentValue(state, entity, effect.propertyId, event.at));
1452
+ keepPassedCrossings(state, entity.id, effect.propertyId, event.at);
1210
1453
  for (const mechanic of definition.mechanics) {
1211
1454
  if (mechanic.kind !== 'change' || mechanic.onEvent?.subjectPropertyId !== effect.propertyId)
1212
1455
  continue;
@@ -1216,31 +1459,14 @@ function applyEffect(state, event, effect, replay) {
1216
1459
  if (typeof effect.value === 'string')
1217
1460
  (state.entityMoveSubjectIds[effect.value] ??= []).push(entity.id);
1218
1461
  }
1219
- const previousRefs = property.type === 'id' && entity.placeId === null ? entityRefs(state.kinds, entity) : null;
1220
- // Before engine 45, writing on a paper adds to what it holds, marked with when and by whom.
1462
+ const previousRefs = property.type === 'id' && entity.containerId === null ? entityRefs(state.kinds, entity) : null;
1221
1463
  const written = entity.properties[effect.propertyId]?.value;
1222
- const wholeText = state.engine >= WHOLE_TEXT_ENGINE;
1223
- if (!wholeText && state.engine >= ADDED_LINE_ENGINE && property.type === 'text' && typeof effect.value === 'string' && typeof written === 'string' && written !== ''
1224
- && effect.value.length > MAX_ADDED_LINE) {
1225
- throw new LivingWorldError('effect-invalid', `Add only the words written now, at most ${MAX_ADDED_LINE} characters, to ${entity.name}; what is already written stays on it`);
1226
- }
1227
1464
  // The whole text as it now reads replaces the old; one that drops most of a long text is no rewrite of it.
1228
- if (wholeText && property.type === 'text' && typeof effect.value === 'string' && typeof written === 'string' && written.length > MAX_ADDED_LINE
1465
+ if ((property.type === 'text') && typeof effect.value === 'string' && typeof written === 'string' && written.length > MAX_ADDED_LINE
1229
1466
  && effect.value.length * 2 < written.length) {
1230
1467
  throw new LivingWorldError('effect-invalid', `Write the whole text of ${entity.name} as it now reads, with the change; to erase it, set it to null`);
1231
1468
  }
1232
- const stored = !wholeText && state.engine >= WRITING_GROWS_ENGINE && property.type === 'text' && typeof effect.value === 'string' && typeof written === 'string' && written !== ''
1233
- ? addWriting(written, `[${clockLabel(event.at)}${event.actorId && state.people[event.actorId] ? `, ${state.people[event.actorId].name}` : ''}] ${effect.value}`)
1234
- : effect.value;
1235
- if (effect.propertyId === 'body' && property.type === 'text') {
1236
- const prior = entity.properties.body;
1237
- const views = { ...entity.paperViews };
1238
- for (const reader of prior?.knownTo ?? [])
1239
- views[reader] = { name: entity.name, words: typeof prior?.value === 'string' ? prior.value : null };
1240
- for (const reader of opening ? entity.knownTo : knownTo)
1241
- views[reader] = { name: entity.name, words: typeof stored === 'string' ? stored : null };
1242
- entity.paperViews = views;
1243
- }
1469
+ const stored = (effect.value);
1244
1470
  if (stored === null)
1245
1471
  delete entity.properties[effect.propertyId];
1246
1472
  // A world's own words are known to whoever knows the thing; the slot shares its list, which is never changed in place.
@@ -1254,46 +1480,10 @@ function applyEffect(state, event, effect, replay) {
1254
1480
  }
1255
1481
  if (typeof effect.value === 'number')
1256
1482
  runTriggers(state, entity.id, effect.propertyId, typeof previousValue === 'number' ? previousValue : null, effect.value, event.at, event.seq);
1257
- if (state.engine >= LAZY_METER_ENGINE)
1258
- predictCrossings(state, entity.id, effect.propertyId, event.seq);
1259
- if (entity.members !== undefined && (effect.propertyId === 'opens-at' || effect.propertyId === 'closes-at'))
1260
- setCount(state, event, entity.id, effect.propertyId === 'opens-at', typeof stored === 'number' ? stored : null);
1261
- if (effect.propertyId === 'author' && state.engine >= AUTHORS_ENGINE)
1262
- noteAuthor(state, entity.id, typeof previousValue === 'string' ? previousValue : null, typeof stored === 'string' ? stored : null);
1263
- return;
1264
- }
1265
- case 'ballot': {
1266
- const decision = state.entities[effect.entityId];
1267
- if (!decision || decision.members === undefined)
1268
- throw new LivingWorldError('effect-invalid', `${decision?.name ?? effect.entityId} is not put to a vote`);
1269
- const voter = requirePerson(state, effect.personId);
1270
- const shut = votingShut(state, decision, event.at);
1271
- if (shut)
1272
- throw new LivingWorldError('effect-invalid', `${decision.name} ${shut}`);
1273
- if (!decision.members.includes(voter.id))
1274
- throw new LivingWorldError('effect-invalid', `${voter.name} is not a member voting on ${decision.name}`);
1275
- if (event.actorId !== voter.id)
1276
- throw new LivingWorldError('effect-invalid', `Only ${voter.name} casts ${voter.name}'s vote on ${decision.name}`);
1277
- if (decision.ballots?.[voter.id] !== undefined)
1278
- throw new LivingWorldError('effect-invalid', `${voter.name} has already voted on ${decision.name}`);
1279
- decision.ballots = { ...decision.ballots, [voter.id]: effect.choice };
1280
- decision.condition = withSide(decision, 'votes', tally(decision), state.engine >= WHOLE_SIDES_ENGINE, state.engine >= SIDE_ORDER_ENGINE);
1281
- decision.knownTo = [...new Set([...decision.knownTo, ...(event.perceivedBy ?? event.witnessIds), voter.id])];
1282
- // The last member's vote closes it.
1283
- if (decision.members.every(memberId => decision.ballots[memberId] !== undefined))
1284
- closeDecision(state, event, decision);
1285
- return;
1286
- }
1287
- case 'decision.close': {
1288
- const decision = state.entities[effect.entityId];
1289
- if (!decision || decision.members === undefined || decision.result !== undefined)
1290
- throw new LivingWorldError('effect-invalid', `${decision?.name ?? effect.entityId} is not an open vote`);
1291
- const closesAt = decision.properties['closes-at']?.value;
1292
- if (typeof closesAt !== 'number' || closesAt > event.at)
1293
- throw new LivingWorldError('effect-invalid', `${decision.name} is not yet due to be counted`);
1294
- if (effect.result !== countResult(decision))
1295
- throw new LivingWorldError('effect-invalid', `${decision.name} counts as ${countResult(decision)}, not ${effect.result}`);
1296
- closeDecision(state, event, decision);
1483
+ predictCrossings(state, entity.id, effect.propertyId, event.seq);
1484
+ if (property.type === 'time' && typeof effect.value === 'number' && effect.value > event.at) {
1485
+ scheduleLawContinuation(state, event, { entityId: entity.id, slotId: effect.propertyId }, effect.value);
1486
+ }
1297
1487
  return;
1298
1488
  }
1299
1489
  case 'clock': {
@@ -1301,15 +1491,19 @@ function applyEffect(state, event, effect, replay) {
1301
1491
  // engine 40 that is where the player could see it, a short lead past what the world simulated:
1302
1492
  // time it never reached is not owed afterwards.
1303
1493
  const target = clockTargetAt(state, event.realAt);
1304
- const shown = state.engine >= SHOWN_CLOCK_ENGINE && state.clockRate !== null ? Math.min(target, state.clock + livingClockLead(state.clockRate)) : target;
1494
+ const shown = effect.hold === true ? state.clock : (state.clockRate !== null) ? Math.min(target, state.clock + livingClockLead(state.clockRate)) : target;
1305
1495
  const game = Math.max(state.clock, shown);
1306
1496
  state.clockAnchor = { game, real: event.realAt };
1307
1497
  state.clockRate = effect.rate;
1308
1498
  state.paused = effect.paused;
1309
1499
  // Once the clock runs, every two game hours the open problem nobody has acted on longest goes on by itself.
1310
- if (state.engine >= STALL_ENGINE && state.clockRate !== null && !state.schedule.some(item => item.series === 'stall-check')) {
1311
- insertScheduled(state, { id: 'stall-check', at: state.clock + STALL_MINUTES, personId: null, kind: 'world', intent: 'An open problem nobody has acted on goes on by itself.',
1312
- placeId: state.people[state.playerId].placeId, targetId: null, sourceSeq: event.seq, importance: 3, everyMinutes: STALL_MINUTES, series: 'stall-check' });
1500
+ if ((state.clockRate !== null) && !state.schedule.some(item => item.series === 'stall-check')) {
1501
+ insertScheduled(state, { id: 'stall-check', at: state.clock + pace(state.calendar, 'stall'), personId: null, kind: 'world', intent: phrase('happening.alone'),
1502
+ placeId: state.people[state.playerId].placeId, targetId: null, sourceSeq: event.seq, importance: 3, everyMinutes: pace(state.calendar, 'stall'), series: 'stall-check' });
1503
+ }
1504
+ if ((state.clockRate !== null) && !state.schedule.some(item => item.series === 'director-check')) {
1505
+ insertScheduled(state, { id: 'director-check', at: state.clock + pace(state.calendar, 'directorCheck'), personId: null, kind: 'world', intent: DIRECTOR_CHECK_INTENT,
1506
+ placeId: state.people[state.playerId].placeId, targetId: null, sourceSeq: event.seq, importance: 1, series: 'director-check' });
1313
1507
  }
1314
1508
  return;
1315
1509
  }
@@ -1321,15 +1515,11 @@ function applyEffect(state, event, effect, replay) {
1321
1515
  const relation = definition.relations.find(slot => slot.id === effect.relationId);
1322
1516
  if (!relation)
1323
1517
  throw new LivingWorldError('effect-invalid', `Unknown relation ${effect.relationId}`);
1324
- const authority = definition.mechanics.filter((mechanic) => mechanic.kind === 'authority' && mechanic.relationId === effect.relationId);
1325
- if (event.actorId !== null && authority.length > 0 && !authority.some(mechanic => state.people[event.actorId]?.roleId === mechanic.roleId)) {
1326
- throw new LivingWorldError('effect-invalid', `Changing ${effect.relationId} needs authority role ${authority.map(mechanic => mechanic.roleId).join(' or ')}`);
1327
- }
1328
1518
  if (effect.targetId !== null && readEntity(state, effect.targetId)?.kindId !== relation.targetKindId) {
1329
1519
  throw new LivingWorldError('effect-invalid', `Relation ${effect.relationId} needs a ${relation.targetKindId} target`);
1330
1520
  }
1331
1521
  const previousSeq = entity.relations[effect.relationId]?.changedSeq ?? null;
1332
- const previousRefs = entity.placeId === null ? entityRefs(state.kinds, entity) : null;
1522
+ const previousRefs = entity.containerId === null ? entityRefs(state.kinds, entity) : null;
1333
1523
  if (effect.targetId === null)
1334
1524
  delete entity.relations[effect.relationId];
1335
1525
  else
@@ -1350,7 +1540,7 @@ function seeTension(state, tension, event, seen) {
1350
1540
  const view = tension.playerView;
1351
1541
  if (view === null || seen !== 'shown') {
1352
1542
  const place = event.placeId === null ? undefined : state.places[event.placeId];
1353
- const where = state.engine >= SEEN_WHERE_ENGINE && place ? `Seen in ${place.name}` : line;
1543
+ const where = (place) ? phrase('memory.seenIn', { place: place.name }) : line;
1354
1544
  tension.playerView = { title: view?.title ?? (seen === 'created' ? tension.title : where).slice(0, 200), summary: line, status: tension.status, resolution, latest: null, since: event.at };
1355
1545
  return;
1356
1546
  }
@@ -1368,13 +1558,13 @@ function rememberEvent(state, event) {
1368
1558
  if (event.perceivedBy && !event.perceivedBy.includes(witnessId) && event.actorId !== witnessId)
1369
1559
  continue;
1370
1560
  // From engine 42 one's own words are remembered as one's own, whoever else they named.
1371
- const mine = spoken && state.engine >= IDENTITY_ENGINE
1372
- ? `I said${spoken.toIds.length === 0 ? '' : ` to ${spoken.toIds.map(id => state.people[id]?.name ?? id).join(' and ')}`}: "${spoken.text}"` : null;
1561
+ const mine = (spoken)
1562
+ ? phrase('memory.said', { to: spoken.toIds.length === 0 ? '' : phrase('memory.saidTo', { names: spoken.toIds.map(id => state.people[id]?.name ?? id).join(' and ') }), text: spoken.text }) : null;
1373
1563
  const memory = event.actorId === witnessId
1374
- ? mine ?? `I did this: ${event.summary}`
1564
+ ? mine ?? phrase('memory.did', { summary: event.summary })
1375
1565
  : spoken
1376
- ? `I heard ${state.people[spoken.personId].name} say: "${spoken.text}"`
1377
- : `I was there and saw this: ${event.observed ?? event.summary}`;
1566
+ ? phrase('memory.heard', { name: state.people[spoken.personId].name, text: spoken.text })
1567
+ : phrase('memory.saw', { observed: event.observed ?? event.summary });
1378
1568
  addMemory(state, witnessId, event, memory, event.importance, event.witnessIds.filter(other => other !== witnessId), { kind: spoken ? 'heard' : 'observed', eventSeq: event.seq, sourceId: spoken?.personId ?? null });
1379
1569
  }
1380
1570
  for (const nearbyId of event.nearbyIds) {
@@ -1389,9 +1579,10 @@ function rememberEvent(state, event) {
1389
1579
  continue;
1390
1580
  }
1391
1581
  const where = state.places[person.placeId]?.name ?? person.placeId;
1392
- const from = event.placeId ? state.places[event.placeId]?.name ?? event.placeId : 'somewhere close';
1393
- const signal = signalsFor(state, event.effects).find(item => item.targetPlaceId === person.placeId || item.channel === GLOBAL_SIGNAL_CHANNEL);
1394
- addMemory(state, nearbyId, event, `From ${where}, I noticed something from ${from}: ${event.notice ?? 'a commotion'} (I did not see what happened.)`, Math.max(1, event.importance - 1), [], { kind: signal ? signal.channel === 'sound' || signal.channel === GLOBAL_SIGNAL_CHANNEL ? 'heard' : 'observed' : 'inferred', eventSeq: event.seq, sourceId: null });
1582
+ const from = event.placeId ? state.places[event.placeId]?.name ?? event.placeId : phrase('memory.close');
1583
+ const signal = signalsFor(state, event.effects).find(item => item.targetPlaceId === person.placeId
1584
+ || (item.sourcePlaceId !== null && placesWithin(state, item.sourcePlaceId, state.channels[item.channel]?.reach ?? 0).includes(person.placeId)));
1585
+ addMemory(state, nearbyId, event, phrase('memory.from', { where, from, notice: event.notice ?? phrase('notice.commotion') }), Math.max(1, event.importance - 1), [], { kind: signal ? state.channels[signal.channel]?.heard === false ? 'observed' : 'heard' : 'inferred', eventSeq: event.seq, sourceId: null });
1395
1586
  }
1396
1587
  for (const effect of event.effects) {
1397
1588
  if (effect.kind !== 'message')
@@ -1408,7 +1599,7 @@ function rememberEvent(state, event) {
1408
1599
  // read it, and a recorded account from anyone it passes on.
1409
1600
  function checkMessage(state, event, effect) {
1410
1601
  requirePerson(state, effect.fromId);
1411
- if (state.engine >= ACT_GATE_ENGINE && event.actorId === effect.fromId) {
1602
+ if ((event.actorId === effect.fromId)) {
1412
1603
  const gate = blockedByGate(state, effect.fromId, 'message');
1413
1604
  if (gate)
1414
1605
  throw new LivingWorldError('effect-invalid', `Messages are blocked by ${gate}`);
@@ -1428,7 +1619,7 @@ function checkMessage(state, event, effect) {
1428
1619
  // The player's own choices and what they perceived that mattered stay for the ending however long
1429
1620
  // the story runs; past the limit the least weighty of the older half makes room.
1430
1621
  function recordChronicle(state, event) {
1431
- if (state.engine < CHRONICLE_ENGINE || !visibleTo(event, state.playerId))
1622
+ if ((!visibleTo(event, state.playerId)))
1432
1623
  return;
1433
1624
  const mine = event.actorId === state.playerId && (event.kind === 'speech' || event.kind === 'message' || event.kind === 'attempt');
1434
1625
  if (!mine && !(event.importance >= 6 || event.kind === 'attempt' || event.kind === 'world'))
@@ -1437,25 +1628,27 @@ function recordChronicle(state, event) {
1437
1628
  if (summary === null)
1438
1629
  return;
1439
1630
  const nearbyOnly = event.nearbyIds.includes(state.playerId) && !witnessed(event, state.playerId) && event.actorId !== state.playerId;
1440
- state.chronicle.push({ seq: event.seq, at: event.at, kind: event.kind, placeId: nearbyOnly ? null : event.placeId, summary: summary.slice(0, 2000),
1631
+ state.chronicle.items.push({ seq: event.seq, at: event.at, kind: event.kind, placeId: nearbyOnly ? null : event.placeId, summary: summary.slice(0, 2000),
1441
1632
  outcome: event.observed === undefined ? event.outcome : null, importance: event.importance, mine });
1442
- if (state.chronicle.length <= MAX_CHRONICLE)
1633
+ if (state.chronicle.items.length <= BOUNDS.chronicle)
1443
1634
  return;
1444
- const older = Math.floor(state.chronicle.length / 2);
1635
+ const older = Math.floor(state.chronicle.items.length / 2);
1445
1636
  let drop = 0;
1446
1637
  for (let index = 1; index < older; index += 1)
1447
- if (state.chronicle[index].importance < state.chronicle[drop].importance)
1638
+ if (state.chronicle.items[index].importance < state.chronicle.items[drop].importance)
1448
1639
  drop = index;
1449
- state.chronicle.splice(drop, 1);
1640
+ state.chronicle.fold = foldOf(state.chronicle.fold, state.chronicle.items.splice(drop, 1), 'chronicle');
1450
1641
  }
1451
1642
  function addMemory(state, personId, event, text, importance, participantIds, evidence = { kind: 'inferred', eventSeq: event.seq, sourceId: null }) {
1452
1643
  const person = state.people[personId];
1453
1644
  person.memoryCount = (person.memoryCount ?? person.memories.length) + 1;
1454
- const thingIds = state.engine >= THING_MEMORY_ENGINE ? thingsOf(event) : [];
1645
+ const thingIds = (thingsOf(event));
1646
+ const requestIds = ([...new Set(event.effects.flatMap(effect => effect.kind === 'request.open' || effect.kind === 'request.update' ? [effect.requestId] : []))]);
1647
+ const commitmentIds = ([...new Set(event.effects.flatMap(effect => effect.kind === 'commitment' || effect.kind === 'commitment.update' ? [effect.commitmentId] : []))]);
1455
1648
  const memory = {
1456
1649
  id: generatedId(state.engine, 'memory', [personId, event.seq, person.memoryCount], `${personId}-memory-${event.seq}-${person.memoryCount}`), at: event.at, eventSeq: event.seq,
1457
1650
  text: text.slice(0, 2000), importance, participantIds: [...new Set(participantIds)], placeId: event.placeId,
1458
- ...(thingIds.length === 0 ? {} : { thingIds }), evidence,
1651
+ ...(thingIds.length === 0 ? {} : { thingIds }), ...(requestIds.length === 0 ? {} : { requestIds }), ...(commitmentIds.length === 0 ? {} : { commitmentIds }), evidence,
1459
1652
  };
1460
1653
  if (isDraft(person)) {
1461
1654
  // Memories are append-only. Skip drafting and walking the immutable archive.
@@ -1469,29 +1662,49 @@ function addMemory(state, personId, event, text, importance, participantIds, evi
1469
1662
  // A ruling leaves each thing it concerned a note of what it did with it, so a later ruling knows;
1470
1663
  // the oldest note makes room past the limit.
1471
1664
  function noteThings(state, event) {
1472
- if (state.engine < THING_MEMORY_ENGINE || (event.kind !== 'attempt' && event.kind !== 'world'))
1665
+ if (((event.kind !== 'attempt' && event.kind !== 'world')))
1473
1666
  return;
1474
1667
  const things = thingsOf(event).filter(id => readEntity(state, id) || state.objects[id]);
1475
1668
  if (things.length === 0)
1476
1669
  return;
1477
1670
  for (const id of things)
1478
- state.thingNotes[id] = { seq: event.seq, at: event.at, text: event.summary.slice(0, THING_NOTE_TEXT) };
1479
- const ids = Object.keys(state.thingNotes);
1480
- if (ids.length <= MAX_THING_NOTES)
1671
+ state.thingNotes.items[id] = { seq: event.seq, at: event.at, text: event.summary.slice(0, THING_NOTE_TEXT) };
1672
+ const ids = Object.keys(state.thingNotes.items);
1673
+ if (ids.length <= BOUNDS.thingNotes)
1481
1674
  return;
1482
- for (const id of ids.sort((left, right) => state.thingNotes[left].seq - state.thingNotes[right].seq || (left < right ? -1 : left > right ? 1 : 0)).slice(0, ids.length - MAX_THING_NOTES))
1483
- delete state.thingNotes[id];
1675
+ const dropped = ids.sort((left, right) => state.thingNotes.items[left].seq - state.thingNotes.items[right].seq || (left < right ? -1 : left > right ? 1 : 0))
1676
+ .slice(0, ids.length - BOUNDS.thingNotes);
1677
+ state.thingNotes.fold = foldOf(state.thingNotes.fold, dropped.map(id => state.thingNotes.items[id]), 'thingNotes');
1678
+ for (const id of dropped)
1679
+ delete state.thingNotes.items[id];
1484
1680
  }
1485
1681
  // From engine 49 someone who comes to a place sees what lies there in the open, and how it plainly is,
1486
1682
  // but reads no words: what someone holds, what the world hides, and what is written, they learn only
1487
1683
  // by seeing it handled or by reading it.
1488
- function seeWhatLiesHere(state, personId, placeId) {
1489
- if (state.engine < THINGS_SEEN_ENGINE)
1684
+ function rescheduleContents(state, containerId, placeId) {
1685
+ if (placeId === null)
1490
1686
  return;
1491
- for (const id of state.entityPlaceIds[placeId] ?? []) {
1687
+ const inside = new Set();
1688
+ const walk = (id) => {
1689
+ for (const child of holds(state, id)) {
1690
+ if (inside.has(child))
1691
+ continue;
1692
+ inside.add(child);
1693
+ walk(child);
1694
+ }
1695
+ };
1696
+ walk(containerId);
1697
+ if (inside.size === 0)
1698
+ return;
1699
+ const move = (item) => item.targetId !== null && inside.has(item.targetId) ? { ...item, placeId } : item;
1700
+ state.schedule = state.schedule.map(move);
1701
+ state.predictions.items = state.predictions.items.map(move);
1702
+ }
1703
+ function seeWhatLiesHere(state, personId, placeId) {
1704
+ for (const id of holds(state, placeId)) {
1492
1705
  // Looked at first, so a thing already known is not rewritten.
1493
1706
  const seen = readEntity(state, id);
1494
- if (!seen || seen.holderId !== null || seen.hidden || seen.knownTo.includes(personId))
1707
+ if (!seen || seen.containerId !== placeId || seen.hidden || seen.knownTo.includes(personId))
1495
1708
  continue;
1496
1709
  const entity = state.entities[id];
1497
1710
  entity.knownTo = [...entity.knownTo, personId];
@@ -1507,7 +1720,7 @@ function seeWhatLiesHere(state, personId, placeId) {
1507
1720
  // thing, such as by reading it, knows all of it, its words too, unless it is sealed.
1508
1721
  function learnThings(state, event) {
1509
1722
  // The opening says itself who knows each of the world's own things.
1510
- if (state.engine < THINGS_SEEN_ENGINE || event.kind === 'opening')
1723
+ if ((event.kind === 'opening'))
1511
1724
  return;
1512
1725
  const perceivers = event.perceivedBy ?? event.witnessIds;
1513
1726
  const actor = event.kind === 'attempt' && event.actorId !== null && state.people[event.actorId] ? event.actorId : null;
@@ -1517,10 +1730,9 @@ function learnThings(state, event) {
1517
1730
  const seen = readEntity(state, id);
1518
1731
  if (!seen)
1519
1732
  continue;
1520
- const sealed = sealedPaper(state.engine, seen);
1521
1733
  const types = state.kinds[seen.kindId]?.properties ?? [];
1522
1734
  const unread = (propertyId, slot) => actor !== null && !slot.knownTo.includes(actor)
1523
- && !(sealed && types.find(property => property.id === propertyId)?.type === 'text');
1735
+ && !(sealedSlot(state, seen, propertyId) && types.find(property => property.id === propertyId)?.type === 'text');
1524
1736
  const learns = knowers.some(knower => !seen.knownTo.includes(knower)) || Object.entries(seen.properties).some(([propertyId, slot]) => unread(propertyId, slot));
1525
1737
  if (!learns)
1526
1738
  continue;
@@ -1536,30 +1748,10 @@ function learnThings(state, event) {
1536
1748
  // The things an event concerned: those it names and those its changes touch.
1537
1749
  function thingsOf(event) {
1538
1750
  const touched = event.effects.flatMap(effect => effect.kind === 'object.update' || effect.kind === 'object.create' ? [effect.objectId]
1539
- : effect.kind === 'entity.create' || effect.kind === 'property.set' || effect.kind === 'entity.move' || effect.kind === 'entity.condition' || effect.kind === 'relation.set'
1751
+ : effect.kind === 'entity.create' || effect.kind === 'property.set' || effect.kind === 'entity.move' || effect.kind === 'entity.condition' || effect.kind === 'cell.add' || effect.kind === 'relation.set'
1540
1752
  ? [effect.entityId] : []);
1541
1753
  return [...new Set([...(event.thingIds ?? []), ...touched])].slice(0, 8);
1542
1754
  }
1543
- // What a person holds goes with them: each thing they carry is now where they are.
1544
- function carryHeldEntities(state, personId, from, to) {
1545
- const carried = (state.entityPlaceIds[from] ?? []).filter(id => readEntity(state, id)?.holderId === personId);
1546
- if (carried.length === 0)
1547
- return;
1548
- // A place with nothing left has no list, as when a save is loaded.
1549
- const left = state.entityPlaceIds[from].filter(id => !carried.includes(id));
1550
- if (left.length > 0)
1551
- state.entityPlaceIds[from] = left;
1552
- else
1553
- delete state.entityPlaceIds[from];
1554
- for (const id of carried) {
1555
- state.entities[id].placeId = to;
1556
- (state.entityPlaceIds[to] ??= []).push(id);
1557
- }
1558
- if (plain(state.meterSchedule).some(item => item.targetId !== null && carried.includes(item.targetId))) {
1559
- state.meterSchedule = (isDraft(state.meterSchedule) ? current(state.meterSchedule) : state.meterSchedule)
1560
- .map(item => item.targetId !== null && carried.includes(item.targetId) ? { ...item, placeId: to } : item);
1561
- }
1562
- }
1563
1755
  // The player learns where people are by seeing them. Looking at a room also shows who is
1564
1756
  // no longer there: they stay known, last seen there, with their whereabouts now unknown.
1565
1757
  function observePlace(state, placeId, at) {
@@ -1567,11 +1759,11 @@ function observePlace(state, placeId, at) {
1567
1759
  if (person.isPlayer)
1568
1760
  continue;
1569
1761
  const sighting = state.sightings[person.id];
1570
- const gone = person.away !== undefined || state.engine >= LEFT_UNSEEN_ENGINE && person.departed !== undefined;
1762
+ const gone = person.offstage !== undefined || (person.departed !== undefined);
1571
1763
  if (person.placeId === placeId && !gone)
1572
1764
  state.sightings[person.id] = { placeId, at };
1573
1765
  else if (sighting?.placeId === placeId && !sighting.gone)
1574
- state.sightings[person.id] = { ...sighting, gone: true, ...(state.engine >= GONE_AT_ENGINE ? { goneAt: at } : {}) };
1766
+ state.sightings[person.id] = { ...sighting, gone: true, ...(({ goneAt: at })) };
1575
1767
  }
1576
1768
  }
1577
1769
  function leaveConversations(state, personId, placeId, at) {
@@ -1596,7 +1788,7 @@ function openConversation(state, placeId, participantIds, at, seq) {
1596
1788
  return existing;
1597
1789
  }
1598
1790
  let id = `conversation-${state.conversations.length + 1}`;
1599
- if (state.engine >= STABLE_CONVERSATION_ENGINE) {
1791
+ {
1600
1792
  let ordinal = 0;
1601
1793
  do {
1602
1794
  id = `conversation-${seq}-${++ordinal}`;
@@ -1637,83 +1829,236 @@ function noteUnanswered(state, event) {
1637
1829
  continue;
1638
1830
  for (const listenerId of line.toIds) {
1639
1831
  const entry = speaker.unanswered?.[listenerId];
1640
- const fresh = entry === undefined || event.at - entry.firstAt >= UNANSWERED_RESET_MINUTES;
1832
+ const fresh = entry === undefined || event.at - entry.firstAt >= pace(state.calendar, 'unansweredReset');
1641
1833
  speaker.unanswered = { ...speaker.unanswered, [listenerId]: fresh ? { lines: 1, firstAt: event.at } : { lines: entry.lines + 1, firstAt: entry.firstAt } };
1642
1834
  }
1643
1835
  }
1644
1836
  }
1645
- // A paper is listed under the person who wrote it, and leaves the list of anyone who no longer is its author.
1646
- function noteAuthor(state, entityId, previous, next) {
1647
- const authored = { ...state.authoredIds };
1648
- if (previous !== null && authored[previous])
1649
- authored[previous] = authored[previous].filter(id => id !== entityId);
1650
- if (next !== null && state.people[next])
1651
- authored[next] = [...(authored[next] ?? []).filter(id => id !== entityId), entityId];
1652
- state.authoredIds = authored;
1653
- }
1654
- // A vote's count so far, as anyone who sees it can read it.
1655
- function tally(decision) {
1656
- const cast = Object.values(decision.ballots ?? {});
1657
- const count = (choice) => cast.filter(value => value === choice).length;
1658
- return `yes ${count('yes')}, no ${count('no')}${count('abstain') > 0 ? `, abstaining ${count('abstain')}` : ''} of ${decision.members.length}`;
1659
- }
1660
- // The votes needed to pass: the number the decision names, or more than half its members.
1661
- function neededVotes(decision) {
1662
- const needed = decision.properties.needed?.value;
1663
- return typeof needed === 'number' && needed > 0 ? needed : Math.floor(decision.members.length / 2) + 1;
1664
- }
1665
- export function countResult(decision) {
1666
- const cast = Object.values(decision.ballots ?? {});
1667
- if (cast.filter(value => value === 'yes').length >= neededVotes(decision))
1668
- return 'passed';
1669
- return cast.length === 0 ? 'lapsed' : 'failed';
1670
- }
1671
- // Why no vote can be cast on a decision now, or null while it is open.
1672
- export function votingShut(state, decision, at) {
1673
- if (decision.result !== undefined)
1674
- return `was decided: ${decision.result}`;
1675
- const opensAt = decision.properties['opens-at']?.value;
1676
- if (typeof opensAt === 'number' && at < opensAt)
1677
- return `opens to votes at ${clockLabel(opensAt)}`;
1678
- const closesAt = decision.properties['closes-at']?.value;
1679
- if (typeof closesAt === 'number' && at >= closesAt)
1680
- return `closed to votes at ${clockLabel(closesAt)}`;
1837
+ // A person's situation changes in a typed way when they perceive something, are addressed, or a
1838
+ // deadline of theirs falls due. Their own acts are not news to them. The event seq is kept so a
1839
+ // routine activity that ends with nothing changed can carry on without a new decision.
1840
+ function noteSituation(state, event) {
1841
+ if (QUIET_KINDS.has(event.kind))
1842
+ return;
1843
+ const perceivers = event.perceivedBy ?? event.witnessIds;
1844
+ const addressed = new Set();
1845
+ for (const effect of event.effects) {
1846
+ if (effect.kind === 'say' || effect.kind === 'message' || effect.kind === 'dispatch')
1847
+ for (const id of effect.toIds)
1848
+ addressed.add(id);
1849
+ else if (effect.kind === 'commitment')
1850
+ addressed.add(effect.toId);
1851
+ }
1852
+ for (const personId of new Set([...perceivers, ...addressed])) {
1853
+ if (personId === event.actorId)
1854
+ continue;
1855
+ const person = state.people[personId];
1856
+ if (!person || person.isPlayer)
1857
+ continue;
1858
+ person.situationSeq = event.seq;
1859
+ }
1860
+ }
1861
+ function sameAsk(left, right) {
1862
+ const a = new Set(wordsOf(left));
1863
+ const b = new Set(wordsOf(right));
1864
+ if (a.size === 0 || b.size === 0)
1865
+ return false;
1866
+ let shared = 0;
1867
+ for (const word of a)
1868
+ if (b.has(word))
1869
+ shared += 1;
1870
+ return shared / Math.min(a.size, b.size) >= REPEAT_ASK_OVERLAP;
1871
+ }
1872
+ export function answeredAgain(state, personId) {
1873
+ const playerId = state.playerId;
1874
+ const person = state.people[personId];
1875
+ if (!person || person.isPlayer)
1876
+ return null;
1877
+ const conversation = state.conversations.find(candidate => candidate.endedAt === null && candidate.placeId === person.placeId
1878
+ && candidate.participantIds.includes(personId) && candidate.participantIds.includes(playerId));
1879
+ if (!conversation)
1880
+ return null;
1881
+ let asked = false, answers = 0, repeats = 0, firstAt = 0, answeredAt = 0, answeredSeq = 0;
1882
+ const asks = [];
1883
+ for (const line of conversation.lines) {
1884
+ if (line.speakerId === playerId && line.toIds.includes(personId)) {
1885
+ if (answers > 0)
1886
+ repeats += 1;
1887
+ firstAt = asked ? firstAt : line.at;
1888
+ asked = true;
1889
+ asks.push(line.text);
1890
+ }
1891
+ else if (line.speakerId === personId && line.toIds.includes(playerId)) {
1892
+ answers += 1;
1893
+ answeredAt = line.at;
1894
+ answeredSeq = line.seq;
1895
+ }
1896
+ }
1897
+ if (repeats === 0)
1898
+ return null;
1899
+ const first = asks[0];
1900
+ const sameAskRepeats = asks.slice(1).filter(text => sameAsk(text, first)).length;
1901
+ const changed = state.events.some(event => event.seq > answeredSeq && event.effects.some(effect => lastingChangeToken(effect) !== null));
1902
+ return changed ? null : { repeats, sameAskRepeats, answers, firstAt, answeredAt, answeredSeq };
1903
+ }
1904
+ export function saidAgain(state, personId, beforeSeq) {
1905
+ const person = state.people[personId];
1906
+ if (!person || person.isPlayer)
1907
+ return null;
1908
+ const conversation = state.conversations.find(candidate => candidate.endedAt === null && candidate.placeId === person.placeId
1909
+ && candidate.participantIds.includes(personId));
1910
+ if (!conversation)
1911
+ return null;
1912
+ const lines = conversation.lines.filter(line => line.speakerId === personId && (beforeSeq === undefined || line.seq <= beforeSeq));
1913
+ const last = lines.at(-1);
1914
+ if (last === undefined)
1915
+ return null;
1916
+ const key = [...last.toIds].sort().join(',');
1917
+ const same = lines.filter(line => [...line.toIds].sort().join(',') === key);
1918
+ if (same.length < REPEAT_ASK_EARLIER)
1919
+ return null;
1920
+ const earlier = same.slice(0, -1);
1921
+ if (!earlier.every(line => sameAsk(line.text, last.text)))
1922
+ return null;
1923
+ const first = same[0];
1924
+ const changed = state.events.some(event => event.seq > first.seq && (event.effects.some(effect => lastingChangeToken(effect) !== null)
1925
+ || event.effects.some(effect => effect.kind === 'move' && effect.personId === personId)));
1926
+ return changed ? null : { count: same.length, since: first.at, toIds: [...last.toIds] };
1927
+ }
1928
+ // An exchange is live while the player and this person have an open conversation here and its latest
1929
+ // line was between them, within a short span of game time.
1930
+ export function liveExchange(state, personId) {
1931
+ const person = state.people[personId];
1932
+ if (!person || person.isPlayer)
1933
+ return null;
1934
+ if ((state.people[state.playerId].placeId !== person.placeId))
1935
+ return null;
1936
+ const conversation = state.conversations.find(candidate => candidate.endedAt === null && candidate.placeId === person.placeId
1937
+ && candidate.participantIds.includes(personId) && candidate.participantIds.includes(state.playerId));
1938
+ const line = conversation?.lines.at(-1);
1939
+ if (!conversation || !line)
1940
+ return null;
1941
+ const between = line.speakerId === state.playerId && (line.toIds.includes(personId) || line.toIds.length === 0)
1942
+ || line.speakerId === personId && line.toIds.includes(state.playerId);
1943
+ if (!between)
1944
+ return null;
1945
+ const awaitingAnswer = line.speakerId === state.playerId;
1946
+ if (state.clock - line.at >= pace(state.calendar, 'exchangeTurn'))
1947
+ return null;
1948
+ if (!awaitingAnswer && state.playerTurnSeq !== undefined && state.playerTurnSeq > line.seq)
1949
+ return null;
1950
+ return { conversationId: conversation.id, lastLineAt: line.at, lastLineSeq: line.seq, lastLineText: line.text, awaitingAnswer };
1951
+ }
1952
+ function sealedSlot(state, entity, slotId) {
1953
+ const slot = state.kinds[entity.kindId]?.properties.find(property => property.id === slotId);
1954
+ if (slot?.sealedBy === undefined)
1955
+ return false;
1956
+ return entity.properties[slot.sealedBy]?.value === true;
1957
+ }
1958
+ const MAX_LAW_DEPTH = 4;
1959
+ const MAX_LAW_WRITES = 16;
1960
+ function changedSlots(effect) {
1961
+ if (effect.kind === 'property.set')
1962
+ return [{ entityId: effect.entityId, slotId: effect.propertyId }];
1963
+ if (effect.kind === 'cell.add')
1964
+ return [{ entityId: effect.entityId, slotId: effect.slotId }];
1965
+ return [];
1966
+ }
1967
+ function forbidCheck(state, event, effect) {
1968
+ const target = effect.kind === 'property.set' ? { entityId: effect.entityId, slotId: effect.propertyId, value: effect.value }
1969
+ : effect.kind === 'cell.add' ? { entityId: effect.entityId, slotId: effect.slotId, value: effect.option }
1970
+ : effect.kind === 'relation.set' ? { entityId: effect.entityId, slotId: effect.relationId, value: effect.targetId }
1971
+ : null;
1972
+ if (target === null)
1973
+ return;
1974
+ const entity = state.entities[target.entityId];
1975
+ const kind = entity === undefined ? undefined : state.kinds[entity.kindId];
1976
+ if (entity === undefined || kind === undefined)
1977
+ return;
1978
+ const env = { self: target.entityId, actor: event.actorId, target: effect.kind === 'cell.add' ? effect.personId : null, value: target.value, at: event.at };
1979
+ for (const law of kind.laws ?? []) {
1980
+ if (law.kind !== 'forbid')
1981
+ continue;
1982
+ if (!cueMatches(law.on, target.slotId))
1983
+ continue;
1984
+ if (law.when !== undefined && !evaluateCondition(state, env, law.when))
1985
+ continue;
1986
+ throw new LivingWorldError('effect-invalid', law.then);
1987
+ }
1988
+ }
1989
+ function actionEffect(state, env, entityId, action) {
1990
+ const lawState = state;
1991
+ if (action.op === 'set')
1992
+ return { kind: 'property.set', entityId, propertyId: action.slot, value: evaluateTerm(lawState, env, action.value) };
1993
+ if (action.op === 'add') {
1994
+ const personId = subjectId(env, action.person ?? 'actor');
1995
+ if (personId === null)
1996
+ return null;
1997
+ return { kind: 'cell.add', entityId, slotId: action.slot, option: String(evaluateTerm(lawState, env, action.option)), personId };
1998
+ }
1999
+ if (action.op === 'shift') {
2000
+ const slot = evaluateTerm(lawState, env, action.slot);
2001
+ const from = evaluateTerm(lawState, env, action.from);
2002
+ const to = evaluateTerm(lawState, env, action.to);
2003
+ return { kind: 'shift', slotId: String(slot), fromId: from === null ? null : String(from), toId: to === null ? null : String(to),
2004
+ amount: Number(evaluateTerm(lawState, env, action.amount)) };
2005
+ }
2006
+ if (action.op === 'link')
2007
+ return { kind: 'relation.set', entityId, relationId: action.relation, targetId: String(evaluateTerm(lawState, env, action.target)) };
2008
+ if (action.op === 'settle')
2009
+ return { kind: 'tension.update', tensionId: String(evaluateTerm(lawState, env, action.tension)), status: 'settled', note: null };
1681
2010
  return null;
1682
2011
  }
1683
- // A vote is counted when its last member votes or its time is up; a problem it settles is settled by the result.
1684
- function closeDecision(state, event, decision) {
1685
- decision.result = countResult(decision);
1686
- decision.condition = withSide(decision, 'result', decision.result, state.engine >= WHOLE_SIDES_ENGINE, state.engine >= SIDE_ORDER_ENGINE);
1687
- state.openDecisionIds = (state.openDecisionIds ?? []).filter(id => id !== decision.id);
1688
- state.schedule = state.schedule.filter(item => item.count?.entityId !== decision.id);
1689
- // The money a passed decision moves; a payment that cannot be made is left out, as the count still stands.
1690
- if (decision.result === 'passed')
1691
- for (const transfer of decision.transfers ?? []) {
1692
- try {
1693
- applyEffect(state, event, { kind: 'transfer', ...transfer });
1694
- }
1695
- catch (error) {
1696
- if (!(error instanceof LivingWorldError))
1697
- throw error;
1698
- }
1699
- }
1700
- const tension = decision.settles === undefined ? undefined : state.tensions.find(candidate => candidate.id === decision.settles);
1701
- if (tension?.status === 'open')
1702
- applyEffect(state, event, { kind: 'tension.update', tensionId: tension.id, status: 'settled', note: countNote(decision) });
1703
- }
1704
- // What a count writes as the settlement of the problem it settles: the question, the result and the count.
1705
- export function countNote(decision) {
1706
- return `${String(decision.properties.question?.value ?? decision.name).slice(0, 300)}: ${decision.result}, ${tally(decision)}.`;
1707
- }
1708
- // A vote's written opening or closing time puts its count on the schedule, in place of any earlier one.
1709
- function setCount(state, event, entityId, opens, at) {
1710
- state.schedule = state.schedule.filter(item => !(item.count?.entityId === entityId && item.count.opens === opens));
1711
- if (at === null || opens && at <= event.at)
2012
+ function scheduleLawContinuation(state, event, seed, at = event.at + pace(state.calendar, 'speech')) {
2013
+ const id = generatedId(state.engine, 'law', [event.seq, seed.entityId, seed.slotId], `law-${event.seq}-${seed.entityId}`.slice(0, 64));
2014
+ if (state.schedule.some(item => item.id === id))
2015
+ return;
2016
+ insertScheduled(state, { id, at, personId: null, kind: 'world', intent: 'law', placeId: siteOf(state, state.entities[seed.entityId]?.containerId ?? null),
2017
+ targetId: seed.entityId, sourceSeq: event.seq, importance: 3, law: { entityId: seed.entityId, slotId: seed.slotId } });
2018
+ }
2019
+ export function reactPass(state, event, seeds, depth) {
2020
+ if (seeds.length === 0)
1712
2021
  return;
1713
- const decision = state.entities[entityId];
1714
- insertScheduled(state, { id: generatedId(state.engine, opens ? 'opens' : 'count', [event.seq, entityId], `${opens ? 'opens' : 'count'}-${event.seq}-${entityId}`.slice(0, 64)), at: Math.max(at, event.at), personId: null, kind: 'count',
1715
- intent: `${opens ? 'Voting opens on' : 'Votes are counted on'} ${decision.name}`.slice(0, MAX_LINE), placeId: decision.placeId, targetId: null, sourceSeq: event.seq, importance: 5,
1716
- count: { entityId, opens } });
2022
+ if (depth > MAX_LAW_DEPTH) {
2023
+ scheduleLawContinuation(state, event, seeds[0]);
2024
+ return;
2025
+ }
2026
+ let writes = 0;
2027
+ const queue = [...seeds];
2028
+ const seen = new Set();
2029
+ while (queue.length > 0) {
2030
+ const seed = queue.shift();
2031
+ const key = `${seed.entityId}:${seed.slotId}`;
2032
+ if (seen.has(key))
2033
+ continue;
2034
+ seen.add(key);
2035
+ const entity = state.entities[seed.entityId];
2036
+ const kind = entity === undefined ? undefined : state.kinds[entity.kindId];
2037
+ if (entity === undefined || kind === undefined)
2038
+ continue;
2039
+ for (const law of kind.laws ?? []) {
2040
+ if (law.kind !== 'react')
2041
+ continue;
2042
+ if (!cueMatches(law.on, seed.slotId))
2043
+ continue;
2044
+ const env = { self: seed.entityId, actor: event.actorId, target: null, value: undefined, at: event.at };
2045
+ if (law.when !== undefined && !evaluateCondition(state, env, law.when))
2046
+ continue;
2047
+ for (const action of law.do) {
2048
+ if (writes >= MAX_LAW_WRITES) {
2049
+ scheduleLawContinuation(state, event, seed);
2050
+ return;
2051
+ }
2052
+ writes += 1;
2053
+ const effect = actionEffect(state, env, seed.entityId, action);
2054
+ if (effect === null)
2055
+ continue;
2056
+ applyEffect(state, event, effect, undefined, true);
2057
+ for (const changed of changedSlots(effect))
2058
+ queue.push(changed);
2059
+ }
2060
+ }
2061
+ }
1717
2062
  }
1718
2063
  // A thing's condition keeps a line for each named side; a change without a name is to its state. The
1719
2064
  // oldest other side gives way when a fifth arrives, and the line shows the state first and names the rest.
@@ -1752,7 +2097,7 @@ export function unansweredSince(state, speakerId, listenerId) {
1752
2097
  if (entry === undefined || entry.lines < UNANSWERED_LINES)
1753
2098
  return null;
1754
2099
  const waited = state.clock - entry.firstAt;
1755
- return waited >= UNANSWERED_MINUTES && waited < UNANSWERED_RESET_MINUTES ? entry.firstAt : null;
2100
+ return waited >= pace(state.calendar, 'unanswered') && waited < pace(state.calendar, 'unansweredReset') ? entry.firstAt : null;
1756
2101
  }
1757
2102
  function requirePerson(state, personId) {
1758
2103
  const person = state.people[personId];
@@ -1760,18 +2105,30 @@ function requirePerson(state, personId) {
1760
2105
  throw new LivingWorldError('effect-invalid', `Unknown person ${personId}`);
1761
2106
  return person;
1762
2107
  }
1763
- // A person's purse or an account, read and set the same way.
1764
- function purse(state, id) {
2108
+ const HOLDER_PERSON = 0;
2109
+ const HOLDER_ENTITY = 1;
2110
+ const HOLDER_PLACE = 2;
2111
+ function numberHolder(state, id) {
1765
2112
  const person = state.people[id];
1766
- if (person) {
1767
- if (person.money === null)
1768
- throw new LivingWorldError('effect-invalid', `${person.name} keeps no money in this world`);
1769
- return { name: person.name, person, account: null, allowsDebt: false, balance: () => person.money, set: (value) => { person.money = value; } };
1770
- }
1771
- const account = state.accounts?.[id];
1772
- if (!account)
1773
- throw new LivingWorldError('effect-invalid', `Unknown person or account ${id}`);
1774
- return { name: account.name, person: null, account, allowsDebt: account.allowsDebt, balance: () => account.balance, set: (value) => { account.balance = value; } };
2113
+ if (person)
2114
+ return { id, name: person.name, kind: HOLDER_PERSON, holderId: null, placeId: person.placeId };
2115
+ const entity = state.entities[id];
2116
+ if (entity)
2117
+ return { id, name: entity.name, kind: HOLDER_ENTITY, holderId: state.people[entity.containerId ?? ''] === undefined ? null : entity.containerId,
2118
+ placeId: state.places[entity.containerId ?? ''] === undefined ? null : entity.containerId };
2119
+ const place = state.places[id];
2120
+ if (place)
2121
+ return { id, name: place.name, kind: HOLDER_PLACE, holderId: null, placeId: place.id };
2122
+ return null;
2123
+ }
2124
+ function heldAmount(state, holderId, slotId) {
2125
+ return state.holdings[holderId]?.[slotId];
2126
+ }
2127
+ function setHeldAmount(state, holderId, slotId, value) {
2128
+ const held = state.holdings[holderId];
2129
+ if (held === undefined)
2130
+ throw new LivingWorldError('effect-invalid', `${holderId} keeps none of ${slotId}`);
2131
+ held[slotId] = value;
1775
2132
  }
1776
2133
  function requireKnown(state, id) {
1777
2134
  if (state.people[id] || readEntity(state, id) || state.objects[id] || state.places[id] || state.tensions.some(tension => tension.id === id))
@@ -1784,6 +2141,13 @@ function requirePlace(state, placeId) {
1784
2141
  throw new LivingWorldError('effect-invalid', `Unknown place ${placeId}`);
1785
2142
  return place;
1786
2143
  }
2144
+ function requireContainer(state, containerId) {
2145
+ if (containerId === null)
2146
+ return;
2147
+ if (state.places[containerId] || state.people[containerId])
2148
+ return;
2149
+ throw new LivingWorldError('effect-invalid', `Unknown container ${containerId}`);
2150
+ }
1787
2151
  function clamp(value) {
1788
2152
  return Math.max(-100, Math.min(100, value));
1789
2153
  }
@@ -1822,8 +2186,6 @@ function checkClockEvent(previous, event) {
1822
2186
  throw new LivingWorldError('effect-invalid', 'A tick cannot pass the server clock');
1823
2187
  }
1824
2188
  }
1825
- // Travel follows the place graph. Adjacent places are a short walk apart.
1826
- export const TRAVEL_MINUTES_PER_HOP = 3;
1827
2189
  export function travelPath(state, from, to) {
1828
2190
  if (!state.places[from] || !state.places[to])
1829
2191
  return null;