@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,10 +1,40 @@
1
1
  import { current, isDraft, original } from 'immer';
2
- import { BOUNDED_IDENTIFIERS_ENGINE, generatedId } from './identifiers.js';
3
- import { FULL_SCHEDULE_INTENT_ENGINE, scheduledSchema, LivingWorldError, ONE_CHECK_ENGINE, SELF_HOLD_ENGINE, SIGHT_NAMED_ENGINE, entityRefs } from './types.js';
4
- const LEVELS = ['none', 'low', 'medium', 'high'];
5
- // The one channel that reaches every place: a broadcast, a city-wide alarm, public news. Only a
6
- // world's own data may define a kind that signals on it.
7
- export const GLOBAL_SIGNAL_CHANNEL = 'global';
2
+ import { levelSchema } from './open-world.js';
3
+ import { phrase } from './phrases.js';
4
+ import { generatedId } from './identifiers.js';
5
+ import { scheduledSchema, LivingWorldError, entityRefs } from './types.js';
6
+ import { BOUNDS, foldOf } from './state.js';
7
+ import { attemptedKinds, evaluateCondition, evaluateTerm, lawCueSlot } from './core/laws.js';
8
+ import { holds, moveWithin, siteOf } from './space.js';
9
+ const LEVELS = levelSchema.options;
10
+ export function lastingChangeToken(effect) {
11
+ switch (effect.kind) {
12
+ case 'tension.create':
13
+ return `tension:open:${[...effect.participantIds].sort().join(',')}`;
14
+ case 'tension.update':
15
+ return `tension:${effect.tensionId}:${effect.status}`;
16
+ case 'entity.create':
17
+ return `entity:${effect.kindId}`;
18
+ case 'person.create':
19
+ return 'person:new';
20
+ case 'property.set':
21
+ return `property:${effect.entityId}:${effect.propertyId}`;
22
+ case 'entity.condition':
23
+ return `condition:${effect.entityId}:${effect.aspect ?? effect.condition}`;
24
+ case 'cell.add':
25
+ return `cell:${effect.entityId}:${effect.slotId}:${effect.option}:${effect.personId}`;
26
+ case 'object.update':
27
+ return `object:${effect.objectId}:${effect.aspect ?? effect.condition ?? ''}`;
28
+ case 'shift':
29
+ return `shift:${effect.slotId}:${effect.fromId}:${effect.toId}`;
30
+ case 'hold':
31
+ return `hold:${effect.personId}`;
32
+ case 'deadline.passed':
33
+ return 'deadline:passed';
34
+ default:
35
+ return null;
36
+ }
37
+ }
8
38
  // Signals follow the entities as they stand after all of an act's changes, so something made and
9
39
  // linked in the same act signals too.
10
40
  export function signalsFor(state, effects) {
@@ -16,7 +46,7 @@ export function signalsFor(state, effects) {
16
46
  const entity = state.entities[id];
17
47
  if (!entity)
18
48
  return undefined;
19
- const copy = { kindId: entity.kindId, placeId: entity.placeId,
49
+ const copy = { kindId: entity.kindId, containerId: entity.containerId,
20
50
  properties: Object.fromEntries(Object.entries(entity.properties).map(([key, slot]) => [key, slot.value])),
21
51
  relations: Object.fromEntries(Object.entries(entity.relations).map(([key, slot]) => [key, slot.targetId])) };
22
52
  view.set(id, copy);
@@ -26,7 +56,7 @@ export function signalsFor(state, effects) {
26
56
  const touch = (entityId, propertyId) => { (touched.get(entityId) ?? touched.set(entityId, new Set()).get(entityId)).add(propertyId); };
27
57
  for (const effect of effects) {
28
58
  if (effect.kind === 'entity.create') {
29
- view.set(effect.entityId, { kindId: effect.kindId, placeId: effect.placeId, properties: { ...effect.initialProperties }, relations: {} });
59
+ view.set(effect.entityId, { kindId: effect.kindId, containerId: effect.containerId, properties: { ...effect.initialProperties }, relations: {} });
30
60
  for (const propertyId of Object.keys(effect.initialProperties ?? {}))
31
61
  touch(effect.entityId, propertyId);
32
62
  }
@@ -56,15 +86,19 @@ export function signalsFor(state, effects) {
56
86
  for (const mechanic of kind.mechanics) {
57
87
  if (mechanic.kind !== 'signal' || mechanic.propertyId !== propertyId)
58
88
  continue;
59
- if (mechanic.channel === GLOBAL_SIGNAL_CHANNEL) {
60
- signals.push({ sourcePlaceId: source.placeId, targetPlaceId: null, channel: mechanic.channel, sourceId: entityId });
89
+ const channel = state.channels[mechanic.channel];
90
+ if (channel === undefined)
91
+ continue;
92
+ const sourcePlaceId = siteOf(state, source.containerId);
93
+ if (channel.reach >= Object.keys(state.places).length) {
94
+ signals.push({ sourcePlaceId, targetPlaceId: null, channel: mechanic.channel, sourceId: entityId });
61
95
  continue;
62
96
  }
63
97
  const targetId = source.relations[mechanic.relationId];
64
98
  const target = targetId ? read(targetId) : undefined;
65
99
  if (!target)
66
100
  continue;
67
- signals.push({ sourcePlaceId: source.placeId, targetPlaceId: target.placeId, channel: mechanic.channel, sourceId: entityId });
101
+ signals.push({ sourcePlaceId, targetPlaceId: siteOf(state, target.containerId), channel: mechanic.channel, sourceId: entityId });
68
102
  }
69
103
  }
70
104
  }
@@ -74,23 +108,49 @@ export function signalsFor(state, effects) {
74
108
  // signal carries only its sense and where it came from.
75
109
  export function signalNotice(state, effects, observed = null) {
76
110
  const signals = signalsFor(state, effects);
77
- const broadcast = signals.find(signal => signal.channel === GLOBAL_SIGNAL_CHANNEL);
111
+ const broadcast = signals.find(signal => signal.targetPlaceId === null);
78
112
  if (broadcast) {
79
- const name = state.entities[broadcast.sourceId]?.name ?? effects.flatMap(effect => effect.kind === 'entity.create' && effect.entityId === broadcast.sourceId ? [effect.name] : [])[0] ?? 'A broadcast';
80
- return `${name}: ${observed ?? 'an announcement'}`.slice(0, 2000);
113
+ const name = state.entities[broadcast.sourceId]?.name ?? effects.flatMap(effect => effect.kind === 'entity.create' && effect.entityId === broadcast.sourceId ? [effect.name] : [])[0] ?? phrase('signal.broadcast');
114
+ return `${name}: ${observed ?? phrase('signal.announcement')}`.slice(0, 2000);
81
115
  }
82
116
  const signal = signals[0];
83
117
  if (!signal)
84
118
  return null;
85
- const from = signal.sourcePlaceId ? state.places[signal.sourcePlaceId]?.name ?? signal.sourcePlaceId : 'nearby';
86
- // What is seen is the thing itself, named by its kind, never by a name that may be someone's.
87
- if (signal.channel === 'sight' && state.engine >= SIGHT_NAMED_ENGINE) {
119
+ const from = signal.sourcePlaceId ? state.places[signal.sourcePlaceId]?.name ?? signal.sourcePlaceId : phrase('notice.nearby');
120
+ const channel = state.channels[signal.channel];
121
+ if (channel?.namesKind === true) {
88
122
  const kindId = state.entities[signal.sourceId]?.kindId ?? effects.flatMap(effect => effect.kind === 'entity.create' && effect.entityId === signal.sourceId ? [effect.kindId] : [])[0];
89
123
  const kind = kindId === undefined ? undefined : state.kinds[kindId]?.name;
90
124
  if (kind)
91
- return `${kind} can be seen ${signal.sourcePlaceId ? `at ${from}` : from}.`;
125
+ return phrase('signal.seen', { kind, where: signal.sourcePlaceId ? phrase('signal.at', { place: from }) : from });
126
+ }
127
+ return phrase('signal.notice', { notice: channel?.notice ?? phrase('signal.noticeFallback'), place: from });
128
+ }
129
+ function findCrossed(condition) {
130
+ if (condition === undefined)
131
+ return null;
132
+ if (condition.op === 'crossed')
133
+ return condition;
134
+ if (condition.op === 'allOf' || condition.op === 'anyOf') {
135
+ for (const part of condition.of) {
136
+ const found = findCrossed(part);
137
+ if (found !== null)
138
+ return found;
139
+ }
92
140
  }
93
- return `A ${signal.channel.replace(/-/gu, ' ')} reaches from ${from}.`;
141
+ return null;
142
+ }
143
+ function crossingRule(law, propertyId) {
144
+ if (law.kind !== 'react' || lawCueSlot(law.on) !== propertyId)
145
+ return null;
146
+ const crossed = findCrossed(law.when);
147
+ const happen = law.do.find((action) => action.op === 'happen');
148
+ if (crossed === null || happen === undefined)
149
+ return null;
150
+ return { threshold: crossed.threshold, direction: crossed.direction, intent: happen.intent, after: happen.delayMinutes, minImportance: happen.minImportance };
151
+ }
152
+ function lawState(state) {
153
+ return state;
94
154
  }
95
155
  export function importanceFloorForEffects(state, effects) {
96
156
  const created = new Map(effects.filter((effect) => effect.kind === 'entity.create')
@@ -102,12 +162,14 @@ export function importanceFloorForEffects(state, effects) {
102
162
  const kindId = state.entities[effect.entityId]?.kindId ?? created.get(effect.entityId);
103
163
  if (!kindId)
104
164
  continue;
105
- for (const mechanic of state.kinds[kindId]?.mechanics ?? []) {
106
- if (mechanic.kind !== 'trigger' || mechanic.propertyId !== effect.propertyId)
165
+ for (const law of state.kinds[kindId]?.laws ?? []) {
166
+ const rule = crossingRule(law, effect.propertyId);
167
+ if (rule === null)
107
168
  continue;
108
- const active = mechanic.direction === 'at-least' ? effect.value >= mechanic.threshold : effect.value <= mechanic.threshold;
109
- if (active)
110
- floor = Math.max(floor, mechanic.minImportance ?? 1);
169
+ const env = { self: effect.entityId, actor: null, target: null, value: effect.value, previous: null, at: state.clock };
170
+ if (law.when !== undefined && !evaluateCondition(lawState(state), env, law.when))
171
+ continue;
172
+ floor = Math.max(floor, rule.minImportance ?? 1);
111
173
  }
112
174
  }
113
175
  return floor;
@@ -140,37 +202,35 @@ function orderedIds(state, rawIndex) {
140
202
  }
141
203
  return ordered;
142
204
  }
143
- // The things in an index whose kind carries a mechanic, computed once per version of that index.
144
- const mechanicSubsets = new WeakMap();
145
- function withMechanic(state, rawSource, mechanicKind) {
205
+ const lawSubsets = new WeakMap();
206
+ function withLaws(state, rawSource, tag, match) {
146
207
  if (rawSource === undefined)
147
208
  return [];
148
209
  // Inside the reducer the index is a draft: its current value is the frozen original when this event
149
210
  // has not touched it (a cache hit), or a fresh copy that this event changed (computed, not cached).
150
211
  const source = isDraft(rawSource) ? current(rawSource) : rawSource;
151
- let subsets = mechanicSubsets.get(source);
152
- const cached = subsets?.get(mechanicKind);
212
+ let subsets = lawSubsets.get(source);
213
+ const cached = subsets?.get(tag);
153
214
  if (cached !== undefined)
154
215
  return cached;
155
216
  const ids = Array.isArray(source) ? source : Object.keys(source);
156
- const subset = ids.filter(id => state.kinds[readEntity(state, id)?.kindId ?? '']?.mechanics.some(mechanic => mechanic.kind === mechanicKind));
217
+ const subset = ids.filter(id => (state.kinds[readEntity(state, id)?.kindId ?? '']?.laws ?? []).some(law => match(law)));
157
218
  if (Object.isFrozen(source)) {
158
219
  if (subsets === undefined) {
159
220
  subsets = new Map();
160
- mechanicSubsets.set(source, subsets);
221
+ lawSubsets.set(source, subsets);
161
222
  }
162
- subsets.set(mechanicKind, subset);
223
+ subsets.set(tag, subset);
163
224
  }
164
225
  return subset;
165
226
  }
166
- // Every thing near the given names, or at the place, whose kind carries the mechanic: what a rule reads.
167
- export function nearWithMechanic(state, nearIds, placeId, mechanicKind) {
168
- const ids = new Set(withMechanic(state, state.worldEntityIds, mechanicKind));
227
+ function nearWithLaws(state, nearIds, placeId, tag, match) {
228
+ const ids = new Set(withLaws(state, state.worldEntityIds, tag, match));
169
229
  for (const nearId of nearIds)
170
- for (const entityId of withMechanic(state, state.globalEntityRefs[nearId], mechanicKind))
230
+ for (const entityId of withLaws(state, state.globalEntityRefs[nearId], tag, match))
171
231
  ids.add(entityId);
172
232
  if (placeId !== null)
173
- for (const entityId of withMechanic(state, state.entityPlaceIds[placeId], mechanicKind))
233
+ for (const entityId of withLaws(state, holds(state, placeId), tag, match))
174
234
  ids.add(entityId);
175
235
  return [...ids];
176
236
  }
@@ -189,7 +249,7 @@ export function placelessNear(state, nearIds, newestPerName = Number.POSITIVE_IN
189
249
  }
190
250
  export function unindexPlaceless(state, entityId) {
191
251
  const entity = state.entities[entityId];
192
- if (!entity || entity.placeId !== null)
252
+ if (!entity || entity.containerId !== null)
193
253
  return;
194
254
  delete state.worldEntityIds[entityId];
195
255
  for (const ref of entityRefs(state.kinds, entity)) {
@@ -203,7 +263,7 @@ export function unindexPlaceless(state, entityId) {
203
263
  }
204
264
  export function indexPlaceless(state, entityId) {
205
265
  const entity = state.entities[entityId];
206
- if (!entity || entity.placeId !== null)
266
+ if (!entity || entity.containerId !== null)
207
267
  return;
208
268
  const refs = entityRefs(state.kinds, entity);
209
269
  if (refs.length === 0)
@@ -215,7 +275,7 @@ export function indexPlaceless(state, entityId) {
215
275
  // names it keeps naming keep it where it was, so the index stays in creation order.
216
276
  export function reindexPlaceless(state, entityId, previousRefs) {
217
277
  const entity = state.entities[entityId];
218
- if (!entity || entity.placeId !== null)
278
+ if (!entity || entity.containerId !== null)
219
279
  return;
220
280
  const refs = entityRefs(state.kinds, entity);
221
281
  const kept = new Set(refs);
@@ -237,45 +297,65 @@ export function reindexPlaceless(state, entityId, previousRefs) {
237
297
  if (!previousRefs.includes(ref))
238
298
  (state.globalEntityRefs[ref] ??= {})[entityId] = true;
239
299
  }
240
- // Every gate that holds on a subject now, with the action kinds it blocks. The engine's own
241
- // action kinds are move, speak, message and act; a ruling's action kind names a specific act.
242
- // Each gate also names who keeps its subject: the one its value names, or, when its value is no id,
243
- // the others its thing names.
300
+ function onSlot(condition) {
301
+ if (condition === undefined)
302
+ return null;
303
+ if (condition.op === 'on')
304
+ return condition.slot;
305
+ if (condition.op === 'allOf' || condition.op === 'anyOf') {
306
+ for (const part of condition.of) {
307
+ const slot = onSlot(part);
308
+ if (slot !== null)
309
+ return slot;
310
+ }
311
+ }
312
+ return null;
313
+ }
314
+ function besideIds(state, env, condition) {
315
+ if (condition === undefined)
316
+ return [];
317
+ if (condition.op === 'beside') {
318
+ const value = evaluateTerm(lawState(state), env, condition.other);
319
+ return typeof value === 'string' ? [value] : [];
320
+ }
321
+ if (condition.op === 'allOf' || condition.op === 'anyOf')
322
+ return condition.of.flatMap(part => besideIds(state, env, part));
323
+ return [];
324
+ }
244
325
  export function gatesOn(state, subjectId) {
245
- const subjectPlaceId = state.people[subjectId]?.placeId ?? state.entities[subjectId]?.placeId ?? null;
246
- const gates = [];
247
- for (const entityId of nearWithMechanic(state, [subjectId], subjectPlaceId, 'gate')) {
326
+ const subjectPlaceId = state.people[subjectId]?.placeId ?? siteOf(state, state.entities[subjectId]?.containerId ?? null);
327
+ const gates = new Map();
328
+ for (const entityId of nearWithLaws(state, [subjectId], subjectPlaceId, 'attempted-forbid', law => law.kind === 'forbid' && attemptedKinds(law.on).length > 0)) {
248
329
  const entity = readEntity(state, entityId);
249
330
  const kind = state.kinds[entity.kindId];
250
- for (const mechanic of kind.mechanics) {
251
- if (mechanic.kind !== 'gate')
331
+ for (const law of kind.laws ?? []) {
332
+ if (law.kind !== 'forbid')
252
333
  continue;
253
- if (entity.properties[mechanic.subjectPropertyId]?.value !== subjectId)
334
+ const actionKinds = attemptedKinds(law.on);
335
+ if (actionKinds.length === 0)
254
336
  continue;
255
- const value = entity.properties[mechanic.propertyId]?.value;
256
- // From engine 42 no one is kept in place by a hold they have on themselves.
257
- if (state.engine >= SELF_HOLD_ENGINE && value === subjectId)
337
+ const env = { self: entityId, actor: subjectId, target: null, value: undefined, at: state.clock };
338
+ if (law.when !== undefined && !evaluateCondition(lawState(state), env, law.when))
258
339
  continue;
259
- if (mechanic.atLeast !== undefined) {
260
- const levels = ['none', 'low', 'medium', 'high'];
261
- if (typeof value !== 'string' || !levels.includes(value)
262
- || levels.indexOf(value) < levels.indexOf(mechanic.atLeast))
263
- continue;
340
+ const propertyId = onSlot(law.when) ?? '';
341
+ const keeperIds = besideIds(state, env, law.when);
342
+ const key = `${entity.id}:${propertyId}`;
343
+ const gate = gates.get(key);
344
+ if (gate === undefined)
345
+ gates.set(key, { entityId: entity.id, name: entity.name, propertyId, actionKinds: [...actionKinds], keeperIds });
346
+ else {
347
+ gate.actionKinds = [...new Set([...gate.actionKinds, ...actionKinds])];
348
+ gate.keeperIds = [...new Set([...gate.keeperIds, ...keeperIds])];
264
349
  }
265
- const keeperIds = (kind.properties.find(slot => slot.id === mechanic.propertyId)?.type === 'id' ? [value]
266
- : kind.properties.filter(slot => slot.type === 'id' && slot.id !== mechanic.subjectPropertyId).map(slot => entity.properties[slot.id]?.value))
267
- .filter((id) => typeof id === 'string');
268
- if (value !== undefined && value !== false && value !== 0 && value !== 'none')
269
- gates.push({ entityId: entity.id, name: entity.name, propertyId: mechanic.propertyId, actionKinds: mechanic.blockedActionKinds, keeperIds });
270
350
  }
271
351
  }
272
- return gates;
352
+ return [...gates.values()];
273
353
  }
274
354
  // Someone else, there with the person, who can keep them where they are.
275
355
  function keeps(state, personId, keeperId) {
276
356
  const person = state.people[personId];
277
357
  const keeper = state.people[keeperId];
278
- return keeperId !== personId && person !== undefined && keeper !== undefined && keeper.placeId === person.placeId && keeper.away === undefined && keeper.departed === undefined;
358
+ return keeperId !== personId && person !== undefined && keeper !== undefined && keeper.placeId === person.placeId && keeper.offstage === undefined && keeper.departed === undefined;
279
359
  }
280
360
  // The gates that stop a person taking a kind of act now. A gate on moving holds only while another
281
361
  // person there keeps them: with no keeper, a thing as keeper, or the keeper gone, it keeps no one.
@@ -297,15 +377,18 @@ export function blockedActionKinds(state, subjectId) {
297
377
  || gate.keeperIds.some(keeperId => keeps(state, subjectId, keeperId)))))].sort();
298
378
  }
299
379
  export function normViolationsFor(state, actorId, placeId, actionKind) {
300
- const actor = state.people[actorId];
301
380
  const violations = [];
302
381
  const near = new Set([actorId, placeId, ...Object.values(state.people).filter(person => person.placeId === placeId).map(person => person.id)]);
303
- for (const entityId of nearWithMechanic(state, near, placeId, 'norm')) {
382
+ for (const entityId of nearWithLaws(state, near, placeId, 'attempted-react', law => law.kind === 'react' && attemptedKinds(law.on).includes(actionKind)
383
+ && law.do.some(action => action.op === 'violation'))) {
304
384
  const entity = readEntity(state, entityId);
305
- for (const mechanic of state.kinds[entity.kindId].mechanics) {
306
- if (mechanic.kind !== 'norm' || !mechanic.forbidden || mechanic.actionKind !== actionKind)
385
+ for (const law of state.kinds[entity.kindId].laws ?? []) {
386
+ if (law.kind !== 'react' || !attemptedKinds(law.on).includes(actionKind))
307
387
  continue;
308
- if (mechanic.roleId !== null && mechanic.roleId !== actor.roleId)
388
+ if (!law.do.some(action => action.op === 'violation'))
389
+ continue;
390
+ const env = { self: entityId, actor: actorId, target: null, value: undefined, at: state.clock };
391
+ if (law.when !== undefined && !evaluateCondition(lawState(state), env, law.when))
309
392
  continue;
310
393
  violations.push({ kind: 'norm.violation', normEntityId: entity.id, actionKind, actorId });
311
394
  }
@@ -347,43 +430,38 @@ export function spreadLevel(state, sourceId, propertyId, value, seq, at) {
347
430
  }
348
431
  }
349
432
  }
350
- export function runTriggers(state, entityId, propertyId, previous, next, at, seq) {
433
+ export function runTriggers(state, entityId, propertyId, previous, next, at, seq, scheduled) {
351
434
  const entity = state.entities[entityId];
352
- for (const [index, mechanic] of state.kinds[entity.kindId].mechanics.entries()) {
353
- if (mechanic.kind !== 'trigger' || mechanic.propertyId !== propertyId)
435
+ for (const [index, law] of (state.kinds[entity.kindId].laws ?? []).entries()) {
436
+ const rule = crossingRule(law, propertyId);
437
+ if (rule === null)
354
438
  continue;
355
- const crossed = mechanic.direction === 'at-least'
356
- ? (previous === null || previous < mechanic.threshold) && next >= mechanic.threshold
357
- : (previous === null || previous > mechanic.threshold) && next <= mechanic.threshold;
358
- if (!crossed)
439
+ const env = { self: entityId, actor: null, target: null, value: next, previous, at };
440
+ if (law.when !== undefined && !evaluateCondition(lawState(state), env, law.when))
359
441
  continue;
360
442
  // A thing made already past the threshold joins a check of its kind and trigger pending at its
361
443
  // place; a change to a thing that was already there always arms its own.
362
444
  const series = generatedId(state.engine, 'trigger', [entity.kindId, index], `trigger-${entity.kindId}-${index}`.slice(0, 64));
363
- const once = state.engine >= ONE_CHECK_ENGINE;
364
- if (once && entity.introducedSeq === seq && state.schedule.some(item => item.series === series && item.placeId === entity.placeId))
445
+ if ((entity.introducedSeq === seq) && state.schedule.some(item => item.series === series && item.placeId === siteOf(state, entity.containerId)))
365
446
  continue;
366
447
  const id = generatedId(state.engine, 'trigger', [entityId, propertyId, seq, index], undefined, true);
367
- if (state.engine >= BOUNDED_IDENTIFIERS_ENGINE && plain(state.schedule).some(item => item.id === id))
448
+ if (scheduled ? scheduled.has(id) : plain(state.schedule).some(item => item.id === id))
368
449
  continue;
369
450
  insertScheduled(state, {
370
- id, at: at + mechanic.delayMinutes,
371
- personId: null, kind: 'world', intent: mechanic.intent, placeId: entity.placeId,
372
- targetId: entityId, sourceSeq: seq, importance: mechanic.minImportance ?? 5, ...(once ? { series } : {}),
451
+ id, at: at + rule.after,
452
+ personId: null, kind: 'world', intent: rule.intent, placeId: siteOf(state, entity.containerId),
453
+ targetId: entityId, sourceSeq: seq, importance: rule.minImportance ?? 5, ...(({ series })),
373
454
  });
455
+ scheduled?.add(id);
374
456
  }
375
457
  }
376
458
  // Engines from 32 on keep a growing value as its last written value, the time it was written, and
377
459
  // the rates of its time changes. Readers see the value at their own time, and each threshold it will
378
460
  // cross is scheduled when the value is written, so no event has to touch every growing thing.
379
- export const LAZY_METER_ENGINE = 32;
380
461
  // From this engine on, gates block speech and messages in the reducer as well as movement.
381
- export const ACT_GATE_ENGINE = 36;
382
- export const TIDY_PLACE_INDEX_ENGINE = 39;
383
462
  // From this engine on, recovery is decided where an event happens, never from another place.
384
- export const LOCAL_RECOVERY_ENGINE = 36;
385
463
  function meterRate(state, entity, propertyId) {
386
- return state.kinds[entity.kindId].mechanics.reduce((rate, mechanic) => mechanic.kind === 'change' && mechanic.propertyId === propertyId && !mechanic.onEvent ? rate + mechanic.deltaPerMinute : rate, 0);
464
+ return state.kinds[entity.kindId].mechanics.reduce((total, mechanic) => mechanic.kind === 'change' && mechanic.propertyId === propertyId && !mechanic.onEvent ? total + mechanic.deltaPerMinute : total, 0);
387
465
  }
388
466
  export function currentValue(state, entity, propertyId, at) {
389
467
  const slot = entity.properties[propertyId];
@@ -398,29 +476,37 @@ export function plain(value) {
398
476
  return isDraft(value) ? original(value) : value;
399
477
  }
400
478
  export function insertScheduled(state, item, list = 'schedule') {
401
- if (state.engine >= FULL_SCHEDULE_INTENT_ENGINE) {
479
+ {
402
480
  const parsed = scheduledSchema.safeParse(item);
403
481
  if (!parsed.success)
404
482
  throw new LivingWorldError('effect-invalid', `Generated schedule is invalid: ${parsed.error.message}`);
405
483
  }
484
+ const scheduled = item;
406
485
  // Inside the reducer, splicing a large draft array traps every shifted element; one plain copy does not.
407
- let items = state[list];
486
+ let items = list === 'predictions' ? state.predictions.items : state.schedule;
408
487
  if (isDraft(items)) {
409
488
  // An unchanged draft's current value is the previous state's own array, so copy it.
410
489
  items = current(items).slice();
411
- state[list] = items;
490
+ if (list === 'predictions')
491
+ state.predictions.items = items;
492
+ else
493
+ state.schedule = items;
412
494
  }
413
495
  let low = 0;
414
496
  let high = items.length;
415
497
  while (low < high) {
416
498
  const middle = (low + high) >> 1;
417
499
  const other = items[middle];
418
- if (other.at < item.at || (other.at === item.at && other.id <= item.id))
500
+ if (other.at < scheduled.at || (other.at === scheduled.at && other.sourceSeq <= scheduled.sourceSeq))
419
501
  low = middle + 1;
420
502
  else
421
503
  high = middle;
422
504
  }
423
- items.splice(low, 0, item);
505
+ items.splice(low, 0, scheduled);
506
+ if (list === 'predictions' && items.length > BOUNDS.predictions) {
507
+ state.predictions.fold = foldOf(state.predictions.fold, items.slice(0, items.length - BOUNDS.predictions), 'predictions');
508
+ state.predictions.items = items.slice(items.length - BOUNDS.predictions);
509
+ }
424
510
  }
425
511
  // A prediction's id names its thing, slot, the write it was made from and its trigger.
426
512
  function predictedSlot(item) {
@@ -449,7 +535,7 @@ export function predictionReady(state, item) {
449
535
  // Stale due predictions go; a due one on a thing that is not loaded waits without holding back the rest.
450
536
  export function dropStalePredictions(state, now) {
451
537
  // Reading an element through a draft copies the whole list; a read-only scan reads the list itself.
452
- const items = plain(state.meterSchedule);
538
+ const items = plain(state.predictions.items);
453
539
  let due = 0;
454
540
  let stale = 0;
455
541
  while (due < items.length && items[due].at <= now) {
@@ -459,7 +545,12 @@ export function dropStalePredictions(state, now) {
459
545
  }
460
546
  if (stale === 0)
461
547
  return;
462
- state.meterSchedule = [...items.slice(0, due).filter(item => !stalePrediction(state, item)), ...items.slice(due)];
548
+ const dropped = items.slice(0, due).filter(item => stalePrediction(state, item));
549
+ if (dropped.length === 0)
550
+ return;
551
+ state.predictions.fold = foldOf(state.predictions.fold, dropped, 'predictions');
552
+ const removed = new Set(dropped.map(item => item.id));
553
+ state.predictions.items = plain(state.predictions.items).filter(item => !removed.has(item.id));
463
554
  }
464
555
  // Before a growing slot is written, a crossing its value already made stays a real event: its
465
556
  // prediction moves to the schedule, where the new write cannot erase it.
@@ -468,19 +559,20 @@ export function keepPassedCrossings(state, entityId, propertyId, at) {
468
559
  const slot = entity?.properties[propertyId];
469
560
  if (!entity || !slot)
470
561
  return;
471
- const delays = state.kinds[entity.kindId].mechanics.map(mechanic => mechanic.kind === 'trigger' ? mechanic.delayMinutes : 0);
472
- const latest = at + Math.max(0, ...delays);
473
- const passed = plain(state.meterSchedule).filter(item => {
562
+ const waits = (state.kinds[entity.kindId].laws ?? []).map(law => crossingRule(law, propertyId)?.after ?? 0);
563
+ const latest = at + Math.max(0, ...waits);
564
+ const passed = plain(state.predictions.items).filter(item => {
474
565
  if (item.at > latest || item.sourceSeq !== slot.changedSeq)
475
566
  return false;
476
567
  const predicted = predictedSlot(item);
477
568
  return predicted !== null && predicted.entityId === entityId && predicted.propertyId === propertyId
478
- && item.at - (delays[predicted.index] ?? 0) <= at;
569
+ && item.at - (waits[predicted.index] ?? 0) <= at;
479
570
  });
480
571
  if (passed.length === 0)
481
572
  return;
482
573
  const ids = new Set(passed.map(item => item.id));
483
- state.meterSchedule = (isDraft(state.meterSchedule) ? current(state.meterSchedule) : state.meterSchedule).filter(item => !ids.has(item.id));
574
+ state.predictions.fold = foldOf(state.predictions.fold, passed, 'predictions');
575
+ state.predictions.items = (isDraft(state.predictions.items) ? current(state.predictions.items) : state.predictions.items).filter(item => !ids.has(item.id));
484
576
  for (const item of passed) {
485
577
  const slot = predictedSlot(item);
486
578
  const { prediction: _prediction, ...settled } = item;
@@ -489,33 +581,37 @@ export function keepPassedCrossings(state, entityId, propertyId, at) {
489
581
  }
490
582
  export function predictCrossings(state, entityId, propertyId, seq) {
491
583
  // An event can write a slot more than once. Only its final value predicts future crossings.
492
- if (state.engine >= BOUNDED_IDENTIFIERS_ENGINE && plain(state.meterSchedule).some(item => item.targetId === entityId
493
- && item.prediction?.propertyId === propertyId && item.sourceSeq === seq)) {
494
- state.meterSchedule = plain(state.meterSchedule).filter(item => item.targetId !== entityId
495
- || item.prediction?.propertyId !== propertyId || item.sourceSeq !== seq);
584
+ const samePrediction = (item) => {
585
+ const predicted = predictedSlot(item);
586
+ return predicted !== null && predicted.entityId === entityId && predicted.propertyId === propertyId && item.sourceSeq === seq;
587
+ };
588
+ if ((plain(state.predictions.items).some(samePrediction))) {
589
+ state.predictions.items = plain(state.predictions.items).filter(item => !samePrediction(item));
496
590
  }
497
591
  const entity = state.entities[entityId];
498
592
  const slot = entity.properties[propertyId];
499
- const rate = meterRate(state, entity, propertyId);
500
- if (!slot || typeof slot.value !== 'number' || rate === 0)
593
+ const speed = meterRate(state, entity, propertyId);
594
+ if (!slot || typeof slot.value !== 'number' || speed === 0)
501
595
  return;
502
- for (const [index, mechanic] of state.kinds[entity.kindId].mechanics.entries()) {
503
- if (mechanic.kind !== 'trigger' || mechanic.propertyId !== propertyId)
596
+ for (const [index, law] of (state.kinds[entity.kindId].laws ?? []).entries()) {
597
+ const rule = crossingRule(law, propertyId);
598
+ if (rule === null)
504
599
  continue;
505
- const gap = mechanic.threshold - slot.value;
506
- const ahead = mechanic.direction === 'at-least' ? rate > 0 && gap > 0 : rate < 0 && gap < 0;
600
+ const distance = rule.threshold - slot.value;
601
+ const ahead = rule.direction === 'at-least' ? speed > 0 && distance > 0 : speed < 0 && distance < 0;
507
602
  if (!ahead)
508
603
  continue;
509
604
  insertScheduled(state, {
510
- id: generatedId(state.engine, 'meter', [entityId, propertyId, seq, index], undefined, true), at: slot.updatedAt + Math.ceil(gap / rate) + mechanic.delayMinutes,
511
- personId: null, kind: 'world', intent: mechanic.intent, placeId: entity.placeId,
512
- targetId: entityId, sourceSeq: seq, importance: mechanic.minImportance ?? 5,
513
- ...(state.engine >= BOUNDED_IDENTIFIERS_ENGINE ? { prediction: { propertyId, index } } : {}),
514
- }, 'meterSchedule');
605
+ id: generatedId(state.engine, 'meter', [entityId, propertyId, seq, index], undefined, true), at: slot.updatedAt + Math.ceil(distance / speed) + rule.after,
606
+ personId: null, kind: 'world', intent: rule.intent, placeId: siteOf(state, entity.containerId),
607
+ targetId: entityId, sourceSeq: seq, importance: rule.minImportance ?? 5,
608
+ ...(({ prediction: { propertyId, index } })),
609
+ }, 'predictions');
515
610
  }
516
611
  }
517
612
  export function advanceScopedEntities(state, placeId, to, seq) {
518
- const ids = [...state.globalEntityIds, ...(placeId === null ? [] : state.entityPlaceIds[placeId] ?? [])];
613
+ const ids = [...state.globalEntityIds, ...(placeId === null ? [] : holds(state, placeId))];
614
+ const scheduled = new Set(plain(state.schedule).map(item => item.id));
519
615
  for (const entityId of ids) {
520
616
  const entity = state.entities[entityId];
521
617
  for (const mechanic of state.kinds[entity.kindId].mechanics) {
@@ -530,7 +626,7 @@ export function advanceScopedEntities(state, placeId, to, seq) {
530
626
  throw new Error(`Property ${mechanic.propertyId} exceeds a finite number`);
531
627
  entity.properties[mechanic.propertyId] = { ...slot, value: next, changedSeq: seq, previousSeq: slot.changedSeq, updatedAt: to };
532
628
  state.changes.push({ seq, entityId: entity.id, slotKind: 'property', slotId: mechanic.propertyId, value: next });
533
- runTriggers(state, entity.id, mechanic.propertyId, previous, next, to, seq);
629
+ runTriggers(state, entity.id, mechanic.propertyId, previous, next, to, seq, scheduled);
534
630
  }
535
631
  }
536
632
  }
@@ -545,43 +641,31 @@ export function applyEventChanges(state, event) {
545
641
  continue;
546
642
  if (entity.properties[mechanic.onEvent.subjectPropertyId]?.value !== effect.personId)
547
643
  continue;
548
- const lazy = state.engine >= LAZY_METER_ENGINE;
549
644
  const previous = entity.properties[mechanic.propertyId];
550
- const previousValue = lazy ? currentValue(state, entity, mechanic.propertyId, event.at) : previous?.value;
645
+ const previousValue = (currentValue(state, entity, mechanic.propertyId, event.at));
551
646
  if (previousValue === mechanic.onEvent.value)
552
647
  continue;
553
- if (lazy)
554
- keepPassedCrossings(state, entity.id, mechanic.propertyId, event.at);
648
+ keepPassedCrossings(state, entity.id, mechanic.propertyId, event.at);
555
649
  entity.properties[mechanic.propertyId] = {
556
650
  value: mechanic.onEvent.value, changedSeq: event.seq, previousSeq: previous?.changedSeq ?? null,
557
651
  knownTo: [...new Set([...(previous?.knownTo ?? []), ...event.effects.flatMap(item => item.kind === 'move' ? [item.personId] : [])])],
558
652
  updatedAt: event.at,
559
653
  };
560
- if (entity.placeId !== effect.placeId) {
654
+ if (entity.containerId !== effect.placeId) {
655
+ const wasGlobal = entity.containerId === null;
561
656
  unindexPlaceless(state, entity.id);
562
- if (entity.placeId === null)
657
+ moveWithin(state, entity.id, effect.placeId);
658
+ if (wasGlobal)
563
659
  state.globalEntityIds = state.globalEntityIds.filter(id => id !== entity.id);
564
- else {
565
- const left = (state.entityPlaceIds[entity.placeId] ?? []).filter(id => id !== entity.id);
566
- // From this engine a place with nothing left has no list, as when a save is loaded.
567
- if (left.length === 0 && state.engine >= TIDY_PLACE_INDEX_ENGINE)
568
- delete state.entityPlaceIds[entity.placeId];
569
- else
570
- state.entityPlaceIds[entity.placeId] = left;
571
- }
572
- ;
573
- (state.entityPlaceIds[effect.placeId] ??= []).push(entity.id);
574
- entity.placeId = effect.placeId;
575
- if (plain(state.meterSchedule).some(item => item.targetId === entity.id)) {
576
- state.meterSchedule = (isDraft(state.meterSchedule) ? current(state.meterSchedule) : state.meterSchedule)
660
+ if (plain(state.predictions.items).some(item => item.targetId === entity.id)) {
661
+ state.predictions.items = (isDraft(state.predictions.items) ? current(state.predictions.items) : state.predictions.items)
577
662
  .map(item => item.targetId === entity.id ? { ...item, placeId: effect.placeId } : item);
578
663
  }
579
664
  }
580
665
  state.changes.push({ seq: event.seq, entityId: entity.id, slotKind: 'property', slotId: mechanic.propertyId, value: mechanic.onEvent.value });
581
666
  if (typeof mechanic.onEvent.value === 'number')
582
667
  runTriggers(state, entity.id, mechanic.propertyId, typeof previousValue === 'number' ? previousValue : null, mechanic.onEvent.value, event.at, event.seq);
583
- if (lazy)
584
- predictCrossings(state, entity.id, mechanic.propertyId, event.seq);
668
+ predictCrossings(state, entity.id, mechanic.propertyId, event.seq);
585
669
  }
586
670
  }
587
671
  }