scjson 0.3.1__tar.gz → 0.3.3__tar.gz

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 (40) hide show
  1. {scjson-0.3.1/scjson.egg-info → scjson-0.3.3}/PKG-INFO +22 -3
  2. {scjson-0.3.1 → scjson-0.3.3}/README.md +21 -2
  3. {scjson-0.3.1 → scjson-0.3.3}/pyproject.toml +1 -2
  4. {scjson-0.3.1 → scjson-0.3.3}/scjson/cli.py +117 -7
  5. {scjson-0.3.1 → scjson-0.3.3}/scjson/context.py +280 -23
  6. scjson-0.3.3/scjson/engine.py +26 -0
  7. {scjson-0.3.1 → scjson-0.3.3}/scjson/jinja_gen.py +121 -13
  8. {scjson-0.3.1 → scjson-0.3.3/scjson.egg-info}/PKG-INFO +22 -3
  9. {scjson-0.3.1 → scjson-0.3.3}/scjson.egg-info/SOURCES.txt +3 -9
  10. scjson-0.3.3/tests/__pycache__/test_cli.cpython-311-pytest-8.4.1.pyc +0 -0
  11. scjson-0.3.3/tests/__pycache__/test_engine.cpython-311-pytest-8.4.1.pyc +0 -0
  12. scjson-0.3.3/tests/__pycache__/test_json_stream.cpython-311-pytest-8.4.1.pyc +0 -0
  13. scjson-0.3.1/scjson/dataclasses/__init__.py +0 -121
  14. scjson-0.3.1/scjson/dataclasses/generated.py +0 -1754
  15. scjson-0.3.1/scjson/dataclasses_strict/__init__.py +0 -121
  16. scjson-0.3.1/scjson/dataclasses_strict/generated.py +0 -1761
  17. scjson-0.3.1/scjson/engine.py +0 -170
  18. scjson-0.3.1/scjson/pydantic/__init__.py +0 -121
  19. scjson-0.3.1/scjson/pydantic/generated.py +0 -1185
  20. scjson-0.3.1/scjson/pydantic_strict/__init__.py +0 -121
  21. scjson-0.3.1/scjson/pydantic_strict/generated.py +0 -1188
  22. scjson-0.3.1/tests/__pycache__/test_cli.cpython-310-pytest-8.4.1.pyc +0 -0
  23. {scjson-0.3.1 → scjson-0.3.3}/LEGAL.md +0 -0
  24. {scjson-0.3.1 → scjson-0.3.3}/LICENSE +0 -0
  25. {scjson-0.3.1 → scjson-0.3.3}/MANIFEST.in +0 -0
  26. {scjson-0.3.1 → scjson-0.3.3}/scjson/CaseStyle.py +0 -0
  27. {scjson-0.3.1 → scjson-0.3.3}/scjson/SCXMLDocumentHandler.py +0 -0
  28. {scjson-0.3.1 → scjson-0.3.3}/scjson/__init__.py +0 -0
  29. {scjson-0.3.1 → scjson-0.3.3}/scjson/__main__.py +0 -0
  30. {scjson-0.3.1 → scjson-0.3.3}/scjson/activation.py +0 -0
  31. {scjson-0.3.1 → scjson-0.3.3}/scjson/events.py +0 -0
  32. {scjson-0.3.1 → scjson-0.3.3}/scjson/json_stream.py +0 -0
  33. {scjson-0.3.1 → scjson-0.3.3}/scjson.egg-info/dependency_links.txt +0 -0
  34. {scjson-0.3.1 → scjson-0.3.3}/scjson.egg-info/entry_points.txt +0 -0
  35. {scjson-0.3.1 → scjson-0.3.3}/scjson.egg-info/requires.txt +0 -0
  36. {scjson-0.3.1 → scjson-0.3.3}/scjson.egg-info/top_level.txt +0 -0
  37. {scjson-0.3.1 → scjson-0.3.3}/setup.cfg +0 -0
  38. {scjson-0.3.1 → scjson-0.3.3}/tests/test_cli.py +0 -0
  39. {scjson-0.3.1 → scjson-0.3.3}/tests/test_engine.py +0 -0
  40. {scjson-0.3.1 → scjson-0.3.3}/tests/test_json_stream.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scjson
3
- Version: 0.3.1
3
+ Version: 0.3.3
4
4
  Summary: A JSON-based serialization of SCXML (State Chart XML) for modern tooling, interoperability, and education.
5
5
  Author-email: Ira Abbott <ira@mycloud.blue>
6
6
  License-Expression: BSD-1-Clause
@@ -133,6 +133,26 @@ Operational conformance testing is performed via [uber_test.py](https://github.c
133
133
  ```
134
134
  Note: [uber_test.py](https://github.com/SoftOboros/scjson/blob/main/py/uber_test.py) applies all scxml files in [Zhornyak's ScxmlEditor-Tutorial](https://alexzhornyak.github.io/ScxmlEditor-Tutorial/) which provides a robest set of scxml test vectors useful for standard compliance verification. This is the only file in the test suite which fails to verify round-trip.
135
135
 
136
+ ### Uber Test Harness
137
+
138
+ Run across all languages or a single language with alias support:
139
+
140
+ ```bash
141
+ # All languages detected on PATH
142
+ python py/uber_test.py
143
+
144
+ # Single language (aliases allowed): py, python, js, ts, javascript, rs, rust, swift, java, csharp
145
+ python py/uber_test.py -l js
146
+ python py/uber_test.py -l swfit # typo tolerated → swift
147
+
148
+ # Limit the corpus and treat consensus as warnings only
149
+ python py/uber_test.py -l swift -s "Examples/Qt/StopWatch/*.scxml" --consensus-warn
150
+ ```
151
+
152
+ - `-s/--subset` filters SCXML files by a glob relative to `tutorial/`.
153
+ - `--consensus-warn` downgrades mismatches to warnings when reference languages (Python/JavaScript/Rust) match the canonical structure.
154
+ - The harness normalizes structural differences (see INFERENCE.md) to produce actionable diffs and prints a triage line with a recommendation.
155
+
136
156
  ## Model Variants
137
157
 
138
158
  The Python package exposes four sets of generated models that mirror the
@@ -238,5 +258,4 @@ docker pull iraa/scjson:latest
238
258
 
239
259
  ## License
240
260
 
241
- All source code in this directory is released under the BSD&nbsp;1-Clause license. See [LICENSE](./LICENSE) and [LEGAL.md](./LEGAL.md) for details.
242
-
261
+ All source code in this directory is released under the BSD 1-Clause license. See [LICENSE](./LICENSE) and [LEGAL.md](./LEGAL.md) for details.
@@ -118,6 +118,26 @@ Operational conformance testing is performed via [uber_test.py](https://github.c
118
118
  ```
119
119
  Note: [uber_test.py](https://github.com/SoftOboros/scjson/blob/main/py/uber_test.py) applies all scxml files in [Zhornyak's ScxmlEditor-Tutorial](https://alexzhornyak.github.io/ScxmlEditor-Tutorial/) which provides a robest set of scxml test vectors useful for standard compliance verification. This is the only file in the test suite which fails to verify round-trip.
120
120
 
121
+ ### Uber Test Harness
122
+
123
+ Run across all languages or a single language with alias support:
124
+
125
+ ```bash
126
+ # All languages detected on PATH
127
+ python py/uber_test.py
128
+
129
+ # Single language (aliases allowed): py, python, js, ts, javascript, rs, rust, swift, java, csharp
130
+ python py/uber_test.py -l js
131
+ python py/uber_test.py -l swfit # typo tolerated → swift
132
+
133
+ # Limit the corpus and treat consensus as warnings only
134
+ python py/uber_test.py -l swift -s "Examples/Qt/StopWatch/*.scxml" --consensus-warn
135
+ ```
136
+
137
+ - `-s/--subset` filters SCXML files by a glob relative to `tutorial/`.
138
+ - `--consensus-warn` downgrades mismatches to warnings when reference languages (Python/JavaScript/Rust) match the canonical structure.
139
+ - The harness normalizes structural differences (see INFERENCE.md) to produce actionable diffs and prints a triage line with a recommendation.
140
+
121
141
  ## Model Variants
122
142
 
123
143
  The Python package exposes four sets of generated models that mirror the
@@ -223,5 +243,4 @@ docker pull iraa/scjson:latest
223
243
 
224
244
  ## License
225
245
 
226
- All source code in this directory is released under the BSD&nbsp;1-Clause license. See [LICENSE](./LICENSE) and [LEGAL.md](./LEGAL.md) for details.
227
-
246
+ All source code in this directory is released under the BSD 1-Clause license. See [LICENSE](./LICENSE) and [LEGAL.md](./LEGAL.md) for details.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "scjson"
3
- version = "0.3.1"
3
+ version = "0.3.3"
4
4
  description = "A JSON-based serialization of SCXML (State Chart XML) for modern tooling, interoperability, and education."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.8"
@@ -17,4 +17,3 @@ build-backend = "setuptools.build_meta"
17
17
 
18
18
  [tool.setuptools]
19
19
  packages = ["scjson"]
20
-
@@ -14,6 +14,7 @@ import click
14
14
  from pathlib import Path
15
15
  from .SCXMLDocumentHandler import SCXMLDocumentHandler
16
16
  from .context import DocumentContext
17
+ from .events import Event
17
18
  from .json_stream import JsonStreamDecoder
18
19
  from .jinja_gen import JinjaGenPydantic
19
20
  from importlib.metadata import version, PackageNotFoundError
@@ -217,18 +218,28 @@ def typescript(output: Path | None):
217
218
  print(f"Convert Scjson type for typescript - Path: {output}")
218
219
  Gen = JinjaGenPydantic(output=output)
219
220
  base_dir = os.path.abspath(output)
220
- interfaces = Gen.interfaces
221
- schemas = Gen.schemas
222
- all_arrays = Gen.all_arrays
223
221
  os.makedirs(base_dir, exist_ok=True)
224
222
  is_runtime = True
225
223
  file_name = "scjsonProps.ts"
226
224
  file_description = "Properties runtime file for scjson types"
227
225
  Gen.render_to_file(file_name, "scjson_props.ts.jinja2", locals())
228
- is_runtime = False
229
- file_name = "scjsonProps.d.ts"
230
- file_description = "Properties definition file for scjson types"
231
- Gen.render_to_file(f"types/{file_name}", "scjson_props.ts.jinja2", locals())
226
+ #is_runtime = False
227
+ #file_name = "scjsonProps.d.ts"
228
+ #file_description = "Properties definition file for scjson types"
229
+ #Gen.render_to_file(f"types/{file_name}", "scjson_props.ts.jinja2", locals())
230
+
231
+
232
+ @main.command(help="Create Rust type files for scjson")
233
+ @click.option("--output", "-o", type=click.Path(path_type=Path), help="Output file base.")
234
+ def rust(output: Path | None):
235
+ """Create Rust structs and enums for scjson."""
236
+ print(f"Convert Scjson type for rust - Path: {output}")
237
+ Gen = JinjaGenPydantic(output=output, lang="rust")
238
+ base_dir = os.path.abspath(output)
239
+ os.makedirs(base_dir, exist_ok=True)
240
+ file_name = "scjson_props.rs"
241
+ file_description = "Properties file for scjson types"
242
+ Gen.render_to_file(file_name, "scjson_props.rs.jinja2", locals())
232
243
 
233
244
 
234
245
  @main.command(help="Export scjson.schema.json")
@@ -296,5 +307,104 @@ def run(input_path: Path, workdir: Path | None, is_xml: bool) -> None:
296
307
  if sink is not sys.stdout:
297
308
  sink.close()
298
309
 
310
+
311
+ @main.command(help="Emit a standardized JSONL execution trace for a document.")
312
+ @click.option(
313
+ "--input",
314
+ "-I",
315
+ "input_path",
316
+ required=True,
317
+ type=click.Path(exists=True, path_type=Path),
318
+ help="SCJSON/SCXML document",
319
+ )
320
+ @click.option(
321
+ "--events",
322
+ "-e",
323
+ "events_path",
324
+ required=False,
325
+ type=click.Path(exists=False, path_type=Path),
326
+ help="JSONL stream of events; defaults to stdin when omitted",
327
+ )
328
+ @click.option("--xml", "is_xml", is_flag=True, default=False, help="Input is SCXML")
329
+ @click.option(
330
+ "--out",
331
+ "-o",
332
+ "out_path",
333
+ required=False,
334
+ type=click.Path(path_type=Path),
335
+ help="Destination trace file; defaults to stdout",
336
+ )
337
+ def engine_trace(input_path: Path, events_path: Path | None, is_xml: bool, out_path: Path | None) -> None:
338
+ """Produce a JSON lines trace of engine steps for comparison harnesses.
339
+
340
+ Parameters
341
+ ----------
342
+ input_path: Path
343
+ SCJSON or SCXML chart.
344
+ events_path: Path | None
345
+ Optional JSONL file of events; reads stdin when omitted.
346
+ is_xml: bool
347
+ Treat ``input_path`` as SCXML when ``True``.
348
+ out_path: Path | None
349
+ Optional destination file; writes to stdout when omitted.
350
+
351
+ Returns
352
+ -------
353
+ None
354
+ Writes one JSON object per line.
355
+ """
356
+
357
+ ctx = (
358
+ DocumentContext.from_xml_file(input_path)
359
+ if is_xml
360
+ else DocumentContext.from_json_file(input_path)
361
+ )
362
+
363
+ sink: TextIO
364
+ if out_path:
365
+ out_path.parent.mkdir(parents=True, exist_ok=True)
366
+ sink = open(out_path, "w", encoding="utf-8")
367
+ else:
368
+ sink = sys.stdout
369
+
370
+ stream_handle: TextIO | None = None
371
+ try:
372
+ # Initial snapshot step (step 0)
373
+ filtered_start = ctx._filter_states(ctx.configuration)
374
+ init = {
375
+ "step": 0,
376
+ "event": None,
377
+ "firedTransitions": [],
378
+ "enteredStates": sorted(filtered_start, key=ctx._activation_order_key),
379
+ "exitedStates": [],
380
+ "configuration": sorted(filtered_start, key=ctx._activation_order_key),
381
+ "actionLog": [],
382
+ "datamodelDelta": dict(ctx.data_model),
383
+ }
384
+ sink.write(dumps(init) + "\n")
385
+
386
+ # Event stream
387
+ if events_path:
388
+ stream_handle = open(events_path, "r", encoding="utf-8")
389
+ stream: TextIO = stream_handle
390
+ else:
391
+ stream = sys.stdin
392
+
393
+ step_no = 1
394
+ for msg in JsonStreamDecoder(stream):
395
+ evt_name = msg.get("event") or msg.get("name")
396
+ if not evt_name:
397
+ continue
398
+ evt_data = msg.get("data")
399
+ trace = ctx.trace_step(Event(name=evt_name, data=evt_data))
400
+ trace["step"] = step_no
401
+ sink.write(dumps(trace) + "\n")
402
+ step_no += 1
403
+ finally:
404
+ if sink is not sys.stdout:
405
+ sink.close()
406
+ if stream_handle is not None:
407
+ stream_handle.close()
408
+
299
409
  if __name__ == "__main__":
300
410
  main()
@@ -11,7 +11,7 @@ Runtime execution context with onentry/onexit and history support.
11
11
  """
12
12
 
13
13
  from pathlib import Path
14
- from typing import Any, Dict, List, Optional, Set
14
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
15
15
  import logging
16
16
 
17
17
  from pydantic import BaseModel, ConfigDict, Field
@@ -47,6 +47,7 @@ class DocumentContext(BaseModel):
47
47
  activations: Dict[str, ActivationRecord] = Field(default_factory=dict)
48
48
  history: Dict[str, List[str]] = Field(default_factory=dict)
49
49
  action_log: List[str] = Field(default_factory=list)
50
+ activation_order: Dict[str, int] = Field(default_factory=dict)
50
51
 
51
52
  # ------------------------------------------------------------------ #
52
53
  # Interpreter API – the real engine would call these
@@ -65,26 +66,179 @@ class DocumentContext(BaseModel):
65
66
  def microstep(self) -> None:
66
67
  """Execute one microstep of the interpreter."""
67
68
  evt = self.events.pop()
68
- if not evt:
69
- return
69
+ event_consumed = evt is not None
70
+ triggered = False
71
+
72
+ if evt is not None:
73
+ result = self._execute_transition(evt)
74
+ if result:
75
+ act, trans, _, _ = result
76
+ triggered = True
77
+ logger.info(
78
+ "[microstep] %s -> %s on %s",
79
+ act.id,
80
+ ",".join(trans.target),
81
+ evt.name,
82
+ )
83
+
84
+ while True:
85
+ result = self._execute_transition(None)
86
+ if not result:
87
+ break
88
+ triggered = True
89
+ act, trans, _, _ = result
90
+ logger.info(
91
+ "[microstep] %s -> %s on %s",
92
+ act.id,
93
+ ",".join(trans.target),
94
+ trans.event or "<epsilon>",
95
+ )
96
+
97
+ if event_consumed and not triggered and evt is not None:
98
+ logger.info("[microstep] consumed event: %s", evt.name)
99
+
100
+ def _activation_order_key(self, state_id: str) -> int:
101
+ return self.activation_order.get(state_id, len(self.activation_order) + 1)
70
102
 
71
- for state_id in list(self.configuration):
103
+ def _select_transition(self, evt: Event | None) -> tuple[ActivationRecord, TransitionSpec] | None:
104
+ """Return the first enabled transition for ``evt`` respecting document order."""
105
+
106
+ event_name = evt.name if evt is not None else None
107
+ for state_id in sorted(self.configuration, key=self._activation_order_key):
72
108
  act = self.activations.get(state_id)
73
109
  if not act:
74
110
  continue
75
111
  for trans in act.transitions:
76
- if trans.event is None or trans.event == evt.name:
77
- if trans.cond is None or self._eval_condition(trans.cond, act):
78
- self._fire_transition(act, trans)
79
- logger.info(
80
- "[microstep] %s -> %s on %s",
81
- act.id,
82
- ",".join(trans.target),
83
- evt.name,
84
- )
85
- return
86
-
87
- logger.info("[microstep] consumed event: %s", evt.name)
112
+ if evt is None:
113
+ if trans.event is not None:
114
+ continue
115
+ else:
116
+ if trans.event != event_name:
117
+ continue
118
+ if trans.cond is None or self._eval_condition(trans.cond, act):
119
+ return act, trans
120
+ return None
121
+
122
+ def _execute_transition(
123
+ self, evt: Event | None
124
+ ) -> Optional[Tuple[ActivationRecord, TransitionSpec, Set[str], Set[str]]]:
125
+ sel = self._select_transition(evt)
126
+ if not sel:
127
+ return None
128
+ act, trans = sel
129
+ entered, exited = self._fire_transition(act, trans)
130
+ return act, trans, entered, exited
131
+
132
+ def trace_step(self, evt: Event | None = None) -> dict:
133
+ """Execute one microstep and return a standardized trace entry."""
134
+
135
+ if evt is not None:
136
+ event_obj = evt
137
+ else:
138
+ event_obj = self.events.pop()
139
+
140
+ config_before = set(self.configuration)
141
+ dm_before = dict(self.data_model)
142
+ action_count_before = len(self.action_log)
143
+ fired: List[Dict[str, Any]] = []
144
+ entered: Set[str] = set()
145
+ exited: Set[str] = set()
146
+
147
+ if event_obj is not None:
148
+ result = self._execute_transition(event_obj)
149
+ if result:
150
+ act, trans, ent, ex = result
151
+ fired.append(
152
+ {
153
+ "source": act.id,
154
+ "targets": list(trans.target),
155
+ "event": trans.event,
156
+ "cond": trans.cond,
157
+ }
158
+ )
159
+ entered.update(ent)
160
+ exited.update(ex)
161
+
162
+ while True:
163
+ result = self._execute_transition(None)
164
+ if not result:
165
+ break
166
+ act, trans, ent, ex = result
167
+ fired.append(
168
+ {
169
+ "source": act.id,
170
+ "targets": list(trans.target),
171
+ "event": trans.event,
172
+ "cond": trans.cond,
173
+ }
174
+ )
175
+ entered.update(ent)
176
+ exited.update(ex)
177
+
178
+ dm_delta: Dict[str, Any] = {
179
+ k: self.data_model[k]
180
+ for k in self.data_model
181
+ if dm_before.get(k) != self.data_model[k]
182
+ }
183
+ for key in dm_before:
184
+ if key not in self.data_model:
185
+ dm_delta[key] = None
186
+ actions = self.action_log[action_count_before:]
187
+
188
+ event_payload = (
189
+ {"name": event_obj.name, "data": event_obj.data}
190
+ if event_obj is not None
191
+ else None
192
+ )
193
+
194
+ config_after = set(self.configuration)
195
+ if not entered:
196
+ entered = config_after - config_before
197
+ if not exited:
198
+ exited = config_before - config_after
199
+
200
+ filtered_entered = self._filter_states(entered)
201
+ if not filtered_entered:
202
+ filtered_entered = self._filter_states(config_after - config_before)
203
+
204
+ filtered_exited = self._filter_states(exited)
205
+ if not filtered_exited:
206
+ filtered_exited = self._filter_states(config_before - config_after)
207
+
208
+ filtered_config = self._filter_states(self.configuration)
209
+
210
+ filtered_transitions: List[Dict[str, Any]] = []
211
+ for item in fired:
212
+ src = item["source"]
213
+ targets = [t for t in item["targets"] if self._is_user_state(t)]
214
+ if not self._is_user_state(src):
215
+ if not targets:
216
+ continue
217
+ continue # skip synthetic transitions entirely
218
+ filtered_transitions.append(
219
+ {
220
+ "source": src,
221
+ "targets": targets,
222
+ "event": item["event"],
223
+ "cond": item["cond"],
224
+ }
225
+ )
226
+
227
+ return {
228
+ "event": event_payload,
229
+ "firedTransitions": filtered_transitions,
230
+ "enteredStates": sorted(filtered_entered, key=self._activation_order_key),
231
+ "exitedStates": sorted(filtered_exited, key=self._activation_order_key),
232
+ "configuration": sorted(filtered_config, key=self._activation_order_key),
233
+ "actionLog": actions,
234
+ "datamodelDelta": dm_delta,
235
+ }
236
+
237
+ def _is_user_state(self, state_id: str) -> bool:
238
+ return bool(state_id) and state_id != self.root_activation.id and not state_id.startswith("$generated-")
239
+
240
+ def _filter_states(self, ids: Iterable[str]) -> List[str]:
241
+ return [sid for sid in ids if self._is_user_state(sid)]
88
242
 
89
243
  # ------------------------------------------------------------------ #
90
244
  # Construction helpers
@@ -105,6 +259,7 @@ class DocumentContext(BaseModel):
105
259
  ctx._index_activations(root_state)
106
260
  ctx.configuration.add(root_state.id)
107
261
  ctx._enter_initial_states(root_state)
262
+ ctx.drain_internal()
108
263
  return ctx
109
264
 
110
265
  # ------------------------------------------------------------------ #
@@ -168,6 +323,8 @@ class DocumentContext(BaseModel):
168
323
  def _index_activations(self, act: ActivationRecord) -> None:
169
324
  """Populate ``self.activations`` with the activation tree."""
170
325
  self.activations[act.id] = act
326
+ if act.id not in self.activation_order:
327
+ self.activation_order[act.id] = len(self.activation_order)
171
328
  for child in act.children:
172
329
  self._index_activations(child)
173
330
 
@@ -294,13 +451,113 @@ class DocumentContext(BaseModel):
294
451
  else:
295
452
  self._enter_state(act)
296
453
 
297
- def _fire_transition(self, source: ActivationRecord, trans: TransitionSpec) -> None:
298
- if source.id in self.configuration:
299
- self._exit_state(source)
300
- for tid in trans.target:
301
- target = self.activations.get(tid)
302
- if target:
303
- self._enter_target(target)
454
+ def _fire_transition(
455
+ self, source: ActivationRecord, trans: TransitionSpec
456
+ ) -> tuple[Set[str], Set[str]]:
457
+ before = set(self.configuration)
458
+
459
+ exit_list = self._compute_exit_set(source, trans.target)
460
+ for act in exit_list:
461
+ if act.id in self.configuration:
462
+ self._exit_state(act)
463
+
464
+ enter_list = self._compute_entry_list(source, trans.target)
465
+ for act in enter_list:
466
+ if act.id not in self.configuration:
467
+ self._enter_target(act)
468
+
469
+ after = set(self.configuration)
470
+ entered = after - before
471
+ exited = before - after
472
+ return entered, exited
473
+
474
+ def _depth(self, act: ActivationRecord) -> int:
475
+ depth = 0
476
+ cur = act
477
+ while cur.parent:
478
+ depth += 1
479
+ cur = cur.parent
480
+ return depth
481
+
482
+ def _least_common_ancestor(
483
+ self, first: ActivationRecord, second: ActivationRecord
484
+ ) -> Optional[ActivationRecord]:
485
+ ancestors: Set[str] = set()
486
+ cur = first
487
+ while cur:
488
+ ancestors.add(cur.id)
489
+ cur = cur.parent
490
+ cur = second
491
+ while cur:
492
+ if cur.id in ancestors:
493
+ return cur
494
+ cur = cur.parent
495
+ return None
496
+
497
+ def _compute_exit_set(
498
+ self, source: ActivationRecord, targets: List[str]
499
+ ) -> List[ActivationRecord]:
500
+ exit_set: Dict[str, ActivationRecord] = {}
501
+
502
+ if not targets:
503
+ cur = source
504
+ while cur:
505
+ exit_set[cur.id] = cur
506
+ cur = cur.parent
507
+ else:
508
+ for tid in targets:
509
+ target_act = self.activations.get(tid)
510
+ if not target_act:
511
+ continue
512
+ normalized_target = (
513
+ target_act.parent
514
+ if isinstance(target_act.node, History)
515
+ else target_act
516
+ )
517
+ lca = self._least_common_ancestor(source, normalized_target or self.root_activation)
518
+ cur = source
519
+ while cur and cur is not lca:
520
+ exit_set[cur.id] = cur
521
+ cur = cur.parent
522
+
523
+ ordered = sorted(exit_set.values(), key=self._depth, reverse=True)
524
+ return ordered
525
+
526
+ def _compute_entry_list(
527
+ self, source: ActivationRecord, targets: List[str]
528
+ ) -> List[ActivationRecord]:
529
+ enter_order: List[ActivationRecord] = []
530
+ seen: Set[str] = set()
531
+
532
+ for tid in targets or []:
533
+ target_act = self.activations.get(tid)
534
+ if not target_act:
535
+ continue
536
+ normalized_target = (
537
+ target_act.parent
538
+ if isinstance(target_act.node, History)
539
+ else target_act
540
+ )
541
+ lca = self._least_common_ancestor(source, normalized_target or self.root_activation)
542
+ path: List[ActivationRecord] = []
543
+ cur = target_act
544
+ while cur and cur is not lca:
545
+ path.append(cur)
546
+ cur = cur.parent
547
+ for act in reversed(path):
548
+ if act.id not in seen:
549
+ seen.add(act.id)
550
+ enter_order.append(act)
551
+
552
+ return enter_order
553
+
554
+ def drain_internal(self) -> None:
555
+ """Execute eventless transitions until quiescent."""
556
+
557
+ while True:
558
+ result = self._execute_transition(None)
559
+ if not result:
560
+ break
304
561
 
305
562
  @classmethod
306
563
  def from_json_file(cls, path: str | Path) -> "DocumentContext":
@@ -0,0 +1,26 @@
1
+ """
2
+ Agent Name: python-engine-compat
3
+
4
+ Part of the scjson project.
5
+ Developed by Softoboros Technology Inc.
6
+ Licensed under the BSD 1-Clause License.
7
+
8
+ Deprecated compatibility shim that re-exports the runtime engine API from the
9
+ primary modules (`context`, `activation`, `events`). New code should import from
10
+ those modules directly.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from .activation import ActivationRecord, ActivationStatus, TransitionSpec
16
+ from .context import DocumentContext
17
+ from .events import Event, EventQueue
18
+
19
+ __all__ = [
20
+ "ActivationRecord",
21
+ "ActivationStatus",
22
+ "TransitionSpec",
23
+ "DocumentContext",
24
+ "Event",
25
+ "EventQueue",
26
+ ]