flux-sim-engine 0.2.0__py3-none-any.whl

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 (165) hide show
  1. flux_engine/__init__.py +22 -0
  2. flux_engine/_links.py +55 -0
  3. flux_engine/_vendor/__init__.py +5 -0
  4. flux_engine/_vendor/flux_spec/NOTICE +19 -0
  5. flux_engine/_vendor/flux_spec/VENDOR-NOTES.md +104 -0
  6. flux_engine/_vendor/flux_spec/__init__.py +9 -0
  7. flux_engine/_vendor/flux_spec/bundle.py +410 -0
  8. flux_engine/_vendor/flux_spec/enforce.py +316 -0
  9. flux_engine/_vendor/flux_spec/schema/flux-enforcement-0.5.0.json +121 -0
  10. flux_engine/_vendor/flux_spec/schema/flux-manifest-0.5.0.json +153 -0
  11. flux_engine/_vendor/flux_spec/schema/flux-schema-0.2.0.json +465 -0
  12. flux_engine/_vendor/flux_spec/schema/flux-schema-0.3.0.json +876 -0
  13. flux_engine/_vendor/flux_spec/schema/flux-schema-0.4.0.json +1601 -0
  14. flux_engine/_vendor/flux_spec/schema/flux-schema-0.4.1.json +1668 -0
  15. flux_engine/_vendor/flux_spec/schema/flux-schema-0.5.0.json +1669 -0
  16. flux_engine/_vendor/flux_spec/schema/flux-schema-latest.json +1669 -0
  17. flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.4.0.json +795 -0
  18. flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.4.1.json +852 -0
  19. flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.5.0.json +852 -0
  20. flux_engine/_vendor/flux_spec/validate.py +537 -0
  21. flux_engine/_vendor/flux_spec/vectors/enforcement-vectors.json +935 -0
  22. flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.3.json +5234 -0
  23. flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.4.json +5437 -0
  24. flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.5.json +5498 -0
  25. flux_engine/_vocabulary.py +141 -0
  26. flux_engine/accuracy/__init__.py +5 -0
  27. flux_engine/accuracy/_scoring/__init__.py +24 -0
  28. flux_engine/accuracy/accuracy_record.py +96 -0
  29. flux_engine/accuracy/policy.py +158 -0
  30. flux_engine/accuracy/records.py +264 -0
  31. flux_engine/accuracy/store.py +169 -0
  32. flux_engine/api/__init__.py +163 -0
  33. flux_engine/api/accuracy.py +209 -0
  34. flux_engine/api/agentic.py +134 -0
  35. flux_engine/api/calibration.py +125 -0
  36. flux_engine/api/claims.py +93 -0
  37. flux_engine/api/digests.py +73 -0
  38. flux_engine/api/emit.py +78 -0
  39. flux_engine/api/expressions.py +72 -0
  40. flux_engine/api/fidelity.py +110 -0
  41. flux_engine/api/lineage.py +78 -0
  42. flux_engine/api/stages.py +242 -0
  43. flux_engine/api/verdict.py +108 -0
  44. flux_engine/calibrate/__init__.py +5 -0
  45. flux_engine/calibrate/declared.py +253 -0
  46. flux_engine/calibrate/provenance.py +113 -0
  47. flux_engine/cli/__init__.py +2146 -0
  48. flux_engine/cli/__main__.py +17 -0
  49. flux_engine/cli/_documents.py +226 -0
  50. flux_engine/cli/_hints.py +118 -0
  51. flux_engine/cli/_init.py +152 -0
  52. flux_engine/cli/_progress.py +124 -0
  53. flux_engine/concordance/__init__.py +127 -0
  54. flux_engine/concordance/boundary/__init__.py +78 -0
  55. flux_engine/concordance/boundary/merkle.py +287 -0
  56. flux_engine/concordance/boundary/slice.py +429 -0
  57. flux_engine/concordance/boundary/statistic.py +561 -0
  58. flux_engine/concordance/boundary/store.py +334 -0
  59. flux_engine/concordance/boundary/vault.py +357 -0
  60. flux_engine/concordance/compiler.py +542 -0
  61. flux_engine/concordance/errors.py +189 -0
  62. flux_engine/concordance/gate.py +525 -0
  63. flux_engine/concordance/predicate.py +1217 -0
  64. flux_engine/concordance/record.py +554 -0
  65. flux_engine/concordance/verifier.py +583 -0
  66. flux_engine/core/__init__.py +5 -0
  67. flux_engine/core/artifact.py +99 -0
  68. flux_engine/core/canonical.py +369 -0
  69. flux_engine/core/clock.py +437 -0
  70. flux_engine/core/digest.py +288 -0
  71. flux_engine/core/errors.py +277 -0
  72. flux_engine/core/fixedpoint.py +929 -0
  73. flux_engine/core/lrm.py +158 -0
  74. flux_engine/core/rng.py +736 -0
  75. flux_engine/core/seedtree.py +891 -0
  76. flux_engine/core/trace.py +423 -0
  77. flux_engine/describe.py +207 -0
  78. flux_engine/engine.py +257 -0
  79. flux_engine/evidence/__init__.py +5 -0
  80. flux_engine/evidence/pack.py +411 -0
  81. flux_engine/evidence/report.py +243 -0
  82. flux_engine/expr/__init__.py +133 -0
  83. flux_engine/expr/ast.py +312 -0
  84. flux_engine/expr/attrs.py +386 -0
  85. flux_engine/expr/check.py +278 -0
  86. flux_engine/expr/compile.py +322 -0
  87. flux_engine/expr/errors.py +256 -0
  88. flux_engine/expr/lexer.py +297 -0
  89. flux_engine/expr/parser.py +313 -0
  90. flux_engine/expr/types.py +177 -0
  91. flux_engine/generator/__init__.py +97 -0
  92. flux_engine/generator/families.py +325 -0
  93. flux_engine/generator/paths.py +227 -0
  94. flux_engine/generator/rows.py +918 -0
  95. flux_engine/generator/statistics.py +524 -0
  96. flux_engine/governance/__init__.py +87 -0
  97. flux_engine/governance/audit.py +307 -0
  98. flux_engine/governance/gate.py +334 -0
  99. flux_engine/governance/skills.py +220 -0
  100. flux_engine/governance/sovereignty.py +251 -0
  101. flux_engine/lineage/__init__.py +5 -0
  102. flux_engine/lineage/emitter.py +398 -0
  103. flux_engine/py.typed +0 -0
  104. flux_engine/runtime/__init__.py +153 -0
  105. flux_engine/runtime/campaign.py +407 -0
  106. flux_engine/runtime/cast.py +283 -0
  107. flux_engine/runtime/detector.py +222 -0
  108. flux_engine/runtime/errors.py +58 -0
  109. flux_engine/runtime/experiment.py +311 -0
  110. flux_engine/runtime/journey.py +383 -0
  111. flux_engine/runtime/jurisdiction.py +72 -0
  112. flux_engine/runtime/payloads.py +124 -0
  113. flux_engine/runtime/signals.py +334 -0
  114. flux_engine/runtime/temperature.py +156 -0
  115. flux_engine/seam/__init__.py +5 -0
  116. flux_engine/seam/attest.py +290 -0
  117. flux_engine/seam/conform.py +448 -0
  118. flux_engine/seam/contract.py +605 -0
  119. flux_engine/seam/emit.py +488 -0
  120. flux_engine/seam/mapping.py +299 -0
  121. flux_engine/seam/resolve.py +1087 -0
  122. flux_engine/seam/sinks.py +157 -0
  123. flux_engine/spec/__init__.py +134 -0
  124. flux_engine/spec/bundle.py +25 -0
  125. flux_engine/spec/enforce.py +31 -0
  126. flux_engine/spec/validate.py +28 -0
  127. flux_engine/stages/__init__.py +30 -0
  128. flux_engine/stages/apply.py +447 -0
  129. flux_engine/stages/errors.py +315 -0
  130. flux_engine/stages/layout.py +292 -0
  131. flux_engine/stages/pipeline.py +600 -0
  132. flux_engine/stages/plan.py +241 -0
  133. flux_engine/stages/replay.py +83 -0
  134. flux_engine/stages/run.py +208 -0
  135. flux_engine/stages/ship.py +934 -0
  136. flux_engine/stages/validate.py +93 -0
  137. flux_engine/stages/verify.py +1129 -0
  138. flux_engine/starter/__init__.py +161 -0
  139. flux_engine/starter/bundle/detector.flux.yml +15 -0
  140. flux_engine/starter/bundle/journey.flux.yml +23 -0
  141. flux_engine/starter/bundle/module.flux.yml +16 -0
  142. flux_engine/starter/bundle/payment-recovery.fluid.yml +30 -0
  143. flux_engine/starter/bundle/persona.flux.yml +26 -0
  144. flux_engine/starter/bundle/signal.flux.yml +13 -0
  145. flux_engine/starter/bundle/simulation.flux.yml +29 -0
  146. flux_engine/starter/bundle/taxonomy.flux.yml +17 -0
  147. flux_engine/starter/bundle/treatment.flux.yml +13 -0
  148. flux_engine/starter/bundle/world.flux.yml +20 -0
  149. flux_engine/verticals/__init__.py +85 -0
  150. flux_engine/verticals/telco.py +89 -0
  151. flux_engine/world/__init__.py +89 -0
  152. flux_engine/world/derived.py +195 -0
  153. flux_engine/world/errors.py +41 -0
  154. flux_engine/world/families.py +260 -0
  155. flux_engine/world/population.py +602 -0
  156. flux_engine/world/tracing.py +66 -0
  157. flux_engine/world/values.py +121 -0
  158. flux_sim_engine-0.2.0.dist-info/METADATA +108 -0
  159. flux_sim_engine-0.2.0.dist-info/RECORD +165 -0
  160. flux_sim_engine-0.2.0.dist-info/WHEEL +5 -0
  161. flux_sim_engine-0.2.0.dist-info/entry_points.txt +2 -0
  162. flux_sim_engine-0.2.0.dist-info/licenses/LICENSE +202 -0
  163. flux_sim_engine-0.2.0.dist-info/licenses/NOTICE +10 -0
  164. flux_sim_engine-0.2.0.dist-info/licenses/flux_engine/_vendor/flux_spec/NOTICE +19 -0
  165. flux_sim_engine-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,386 @@
1
+ # Copyright 2026 Agentics Transformation Limited
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """The ``attrmodel/1`` attribute model: three scopes derived from a bundle.
6
+
7
+ EXPR-SPEC §3: "A versioned, canonical JSON document (``attrmodel/1``) whose
8
+ digest is inside ``inputDigest``." This module derives that document from a
9
+ loaded FLUX bundle (``flux_engine.spec.validate.Bundle``) plus a vertical
10
+ pack, and hands the three scopes to the checker and the compiler.
11
+
12
+ The three scopes and where each name comes from:
13
+
14
+ ``subject`` -- ``Segment.spec.query``, ``Journey`` guards
15
+ ``id`` / ``ordinal`` from the population; ``persona`` from the
16
+ Simulation's ``personaRefs``; ``lifecycle`` from
17
+ ``World.spec.population.lifecycleMix``; ``market`` from
18
+ ``World.spec.population.markets``; ``traits.<name>`` and
19
+ ``worldview.<name>`` from the referenced Personas; the vertical pack's
20
+ own attributes on top.
21
+
22
+ ``event`` -- ``Detector.pattern[].predicate``, ``Journey.spec.trigger.condition``
23
+ The four CloudEvents context attributes plus ``data.<field>``, typed from
24
+ the Signal's ``dataschema`` when the caller resolved one, else from the
25
+ vertical pack's signal attributes. One scope per Signal, because a
26
+ predicate is written against one signal's payload.
27
+
28
+ ``observed`` -- ``Playback.spec.personaMapping[].behaviorPattern``
29
+ The vertical pack's aggregate features per observed subject. "Never raw
30
+ records."
31
+
32
+ Two resolutions worth stating:
33
+
34
+ * **``dataschema`` is resolved by the caller, not here.** EXPR-SPEC §3 types
35
+ payload fields "from the Signal's ``dataschema`` when it is a
36
+ bundled/fetchable JSON Schema". Fetching is I/O, and
37
+ ``flux_engine.expr`` is a kernel package that may not import ``os`` or
38
+ ``socket`` (the import-linter contract in pyproject.toml). The plan step
39
+ resolves the URI and passes the parsed schemas in through *dataschemas*;
40
+ a signal with no resolved schema falls back to the vertical pack.
41
+ * **``worldview.riskTolerance`` is an enum, not a number.** The §3 table types
42
+ ``worldview.<name>`` as ``number``, but the FLUX 0.5.0 schema declares
43
+ ``worldview.riskTolerance`` as ``{"enum": ["low", "medium", "high"]}`` -- a
44
+ string. The type is taken from the schema's closed set rather than from the
45
+ table's general case, so ``worldview.riskTolerance == 'high'`` type-checks
46
+ and ``worldview.riskTolerance > 3`` is ``FLX-6005``.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ from dataclasses import dataclass, field
52
+ from typing import Any, Dict, Mapping, Optional, Protocol, Sequence, Tuple
53
+
54
+ from flux_engine.expr.types import (
55
+ BOOL,
56
+ NUMBER,
57
+ SET_STRING,
58
+ STRING,
59
+ Scope,
60
+ ScopeModel,
61
+ Type,
62
+ enum_of,
63
+ nfc,
64
+ )
65
+
66
+ __all__ = [
67
+ "ATTR_MODEL_VERSION",
68
+ "AttributeModel",
69
+ "BundleLike",
70
+ "CONTEXT_ATTRIBUTES",
71
+ "VerticalPack",
72
+ "WORLDVIEW_ENUMS",
73
+ "build_attribute_model",
74
+ ]
75
+
76
+ #: The document version EXPR-SPEC §3 names. Bumping it is a spec change.
77
+ ATTR_MODEL_VERSION = "attrmodel/1"
78
+
79
+ #: The CloudEvents context attributes EXPR-SPEC §3 exposes in the ``event``
80
+ #: scope: "``type``, ``source``, ``time`` (string, RFC 3339), ``subject`` (the
81
+ #: subject id)". Closed -- ``id``, ``specversion`` and the rest of the CE
82
+ #: envelope are deliberately not addressable.
83
+ CONTEXT_ATTRIBUTES: Mapping[str, Type] = {
84
+ "type": STRING,
85
+ "source": STRING,
86
+ "time": STRING,
87
+ "subject": STRING,
88
+ }
89
+
90
+ #: Worldview keys the FLUX 0.5.0 schema declares as a closed string set. Every
91
+ #: other worldview key is a ``unitInterval`` and therefore ``number``.
92
+ WORLDVIEW_ENUMS: Mapping[str, Tuple[str, ...]] = {
93
+ "riskTolerance": ("high", "low", "medium"),
94
+ }
95
+
96
+ Document = Mapping[str, Any]
97
+
98
+
99
+ class BundleLike(Protocol):
100
+ """The one thing this module needs of a bundle: its schema-valid documents.
101
+
102
+ ``flux_engine.spec.validate.Bundle`` satisfies this structurally
103
+ (``Bundle.flux_docs`` is ``dict[str, dict]``, keyed by document id). Taking
104
+ the protocol rather than the class keeps the kernel free of the validator's
105
+ own imports and lets a test build a model from documents it holds in
106
+ memory.
107
+ """
108
+
109
+ @property
110
+ def flux_docs(self) -> Mapping[str, Any]:
111
+ """Schema-valid FLUX documents of the bundle, keyed by document id."""
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class VerticalPack:
116
+ """A vertical's contribution to the attribute model (EXPR-SPEC §3).
117
+
118
+ "vertical-pack attributes ... ``World.spec.vertical`` ->
119
+ ``verticals/<pack>.py`` (v0.1 stopgap; FLUX 0.6 RFC moves the declaration
120
+ into the spec)". The pack declares types only -- it never carries values,
121
+ so nothing here can leak a number into a hashed document.
122
+
123
+ ``signal_attributes`` is keyed by Signal document id; its inner mapping is
124
+ the payload field names, addressed as ``data.<field>``.
125
+ """
126
+
127
+ name: str
128
+ subject_attributes: Mapping[str, Type] = field(default_factory=dict)
129
+ signal_attributes: Mapping[str, Mapping[str, Type]] = field(default_factory=dict)
130
+ observed_features: Mapping[str, Type] = field(default_factory=dict)
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class AttributeModel:
135
+ """The three scopes of EXPR-SPEC §3, plus their canonical JSON document."""
136
+
137
+ vertical: str
138
+ subject: ScopeModel
139
+ event: Mapping[str, ScopeModel]
140
+ observed: ScopeModel
141
+
142
+ def event_scope(self, signal_id: str) -> ScopeModel:
143
+ """Return the ``event`` scope for *signal_id*; raise ``KeyError`` if absent."""
144
+ return self.event[nfc(signal_id)]
145
+
146
+ def to_document(self) -> Dict[str, Any]:
147
+ """Return the canonical ``attrmodel/1`` document.
148
+
149
+ Every mapping is emitted in sorted-key order and carries no numbers at
150
+ all, so the document is stable under KERNEL-SPEC §2 canonicalisation
151
+ and its digest can sit inside ``inputDigest`` (§11).
152
+ """
153
+ return {
154
+ "attrModelVersion": ATTR_MODEL_VERSION,
155
+ "vertical": self.vertical,
156
+ "scopes": {
157
+ "subject": self.subject.to_json(),
158
+ "event": {
159
+ signal_id: self.event[signal_id].to_json() for signal_id in sorted(self.event)
160
+ },
161
+ "observed": self.observed.to_json(),
162
+ },
163
+ }
164
+
165
+
166
+ # --- helpers ----------------------------------------------------------------
167
+
168
+
169
+ def _strip_range(ref: str) -> str:
170
+ """Drop an RFC-03 semver range from a reference (``mod@^2.1`` -> ``mod``)."""
171
+ return ref.split("@", 1)[0]
172
+
173
+
174
+ def _documents_of_kind(bundle: BundleLike, kind: str) -> Sequence[Tuple[str, Document]]:
175
+ """Return the bundle's documents of *kind*, in sorted-id order."""
176
+ return [
177
+ (doc_id, bundle.flux_docs[doc_id])
178
+ for doc_id in sorted(bundle.flux_docs, key=nfc)
179
+ if bundle.flux_docs[doc_id].get("kind") == kind
180
+ ]
181
+
182
+
183
+ def _select_simulation(bundle: BundleLike, simulation_id: Optional[str]) -> Tuple[str, Document]:
184
+ simulations = _documents_of_kind(bundle, "Simulation")
185
+ if simulation_id is not None:
186
+ for doc_id, doc in simulations:
187
+ if doc_id == simulation_id:
188
+ return doc_id, doc
189
+ raise ValueError(f"the bundle has no Simulation with id {simulation_id!r}")
190
+ if len(simulations) != 1:
191
+ raise ValueError(
192
+ "the bundle declares " f"{len(simulations)} Simulations; name one with simulation_id="
193
+ )
194
+ return simulations[0]
195
+
196
+
197
+ def _trait_type(name: str, declared: Any, seen: Dict[str, Type]) -> Type:
198
+ """Type one Persona trait (RFC-01: scalar, categorical or bounded normal)."""
199
+ if isinstance(declared, Mapping):
200
+ if declared.get("dist") == "categorical":
201
+ levels = sorted(nfc(level) for level in declared.get("levels", {}))
202
+ previous = seen.get(name)
203
+ if previous is not None and previous.levels:
204
+ levels = sorted(set(levels) | set(previous.levels))
205
+ return enum_of(levels)
206
+ return NUMBER # dist: normal
207
+ return NUMBER # 0.3.0-compatible scalar
208
+
209
+
210
+ def _merge_trait(name: str, new: Type, seen: Dict[str, Type]) -> None:
211
+ previous = seen.get(name)
212
+ if previous is not None and previous.kind is not new.kind:
213
+ raise ValueError(
214
+ f"trait '{name}' is declared as {previous.name} by one Persona and "
215
+ f"{new.name} by another; the attribute model needs one type per path"
216
+ )
217
+ seen[name] = new
218
+
219
+
220
+ def _subject_scope(
221
+ world: Document,
222
+ personas: Sequence[Tuple[str, Document]],
223
+ persona_ids: Sequence[str],
224
+ pack: VerticalPack,
225
+ ) -> ScopeModel:
226
+ attributes: Dict[str, Type] = {
227
+ "subject.id": STRING,
228
+ "subject.ordinal": NUMBER,
229
+ }
230
+ if persona_ids:
231
+ attributes["subject.persona"] = enum_of(persona_ids)
232
+
233
+ population = world.get("spec", {}).get("population", {})
234
+ lifecycle_mix = population.get("lifecycleMix", {})
235
+ if lifecycle_mix:
236
+ attributes["subject.lifecycle"] = enum_of(lifecycle_mix)
237
+ markets = population.get("markets", [])
238
+ if markets:
239
+ attributes["subject.market"] = enum_of(markets)
240
+
241
+ traits: Dict[str, Type] = {}
242
+ for _persona_id, persona in personas:
243
+ spec = persona.get("spec", {})
244
+ for name in sorted(spec.get("traits", {}) or {}, key=nfc):
245
+ _merge_trait(name, _trait_type(name, spec["traits"][name], traits), traits)
246
+ for name in sorted(spec.get("worldview", {}) or {}, key=nfc):
247
+ levels = WORLDVIEW_ENUMS.get(name)
248
+ declared = enum_of(levels) if levels is not None else NUMBER
249
+ attributes[f"subject.worldview.{nfc(name)}"] = declared
250
+ for name in sorted(traits, key=nfc):
251
+ attributes[f"subject.traits.{nfc(name)}"] = traits[name]
252
+
253
+ for name in sorted(pack.subject_attributes, key=nfc):
254
+ attributes[f"subject.{nfc(name)}"] = pack.subject_attributes[name]
255
+
256
+ return ScopeModel(Scope.SUBJECT, attributes, _bare_aliases(attributes, "subject."))
257
+
258
+
259
+ def _bare_aliases(attributes: Mapping[str, Type], prefix: str) -> Dict[str, str]:
260
+ """Sugar table: ``lifecycle`` -> ``subject.lifecycle`` "where unambiguous".
261
+
262
+ An alias is dropped when its bare spelling is already a canonical path of
263
+ the same scope, or when two canonical paths would claim it; a dropped
264
+ alias makes the bare spelling ``FLX-6004`` rather than a coin toss.
265
+ """
266
+ claims: Dict[str, list] = {}
267
+ for canonical in attributes:
268
+ if not canonical.startswith(prefix):
269
+ continue
270
+ claims.setdefault(canonical[len(prefix) :], []).append(canonical)
271
+ return {
272
+ bare: targets[0]
273
+ for bare, targets in sorted(claims.items())
274
+ if len(targets) == 1 and bare not in attributes
275
+ }
276
+
277
+
278
+ def _json_schema_type(declared: Mapping[str, Any]) -> Optional[Type]:
279
+ """Map one JSON Schema property to a flux-expr/1 type, or ``None``.
280
+
281
+ A property whose shape has no flux-expr/1 type (an object, a tuple, a
282
+ union) is simply not addressable: referencing it is ``FLX-6004``, which is
283
+ a better failure than inventing a type for it.
284
+ """
285
+ kind = declared.get("type")
286
+ if kind in ("number", "integer"):
287
+ return NUMBER
288
+ if kind == "boolean":
289
+ return BOOL
290
+ if kind == "string":
291
+ levels = declared.get("enum")
292
+ if isinstance(levels, Sequence) and not isinstance(levels, (str, bytes)) and levels:
293
+ if all(isinstance(level, str) for level in levels):
294
+ return enum_of(levels)
295
+ return None
296
+ return STRING
297
+ if kind == "array":
298
+ items = declared.get("items")
299
+ if isinstance(items, Mapping) and items.get("type") == "string":
300
+ return SET_STRING
301
+ return None
302
+
303
+
304
+ def _payload_types(
305
+ signal_id: str,
306
+ pack: VerticalPack,
307
+ dataschemas: Mapping[str, Document],
308
+ ) -> Mapping[str, Type]:
309
+ schema = dataschemas.get(signal_id)
310
+ if schema is not None:
311
+ properties = schema.get("properties", {})
312
+ typed: Dict[str, Type] = {}
313
+ for name in sorted(properties, key=nfc):
314
+ declared = properties[name]
315
+ if not isinstance(declared, Mapping):
316
+ continue
317
+ resolved = _json_schema_type(declared)
318
+ if resolved is not None:
319
+ typed[nfc(name)] = resolved
320
+ return typed
321
+ return {nfc(name): t for name, t in pack.signal_attributes.get(signal_id, {}).items()}
322
+
323
+
324
+ def _event_scope(
325
+ signal_id: str,
326
+ pack: VerticalPack,
327
+ dataschemas: Mapping[str, Document],
328
+ ) -> ScopeModel:
329
+ attributes: Dict[str, Type] = dict(CONTEXT_ATTRIBUTES)
330
+ payload = _payload_types(signal_id, pack, dataschemas)
331
+ for name in sorted(payload, key=nfc):
332
+ attributes[f"data.{name}"] = payload[name]
333
+ return ScopeModel(Scope.EVENT, attributes, _bare_aliases(attributes, "data."))
334
+
335
+
336
+ def build_attribute_model(
337
+ bundle: BundleLike,
338
+ pack: VerticalPack,
339
+ *,
340
+ simulation_id: Optional[str] = None,
341
+ dataschemas: Optional[Mapping[str, Document]] = None,
342
+ ) -> AttributeModel:
343
+ """Derive the ``attrmodel/1`` model for *bundle* under *pack*.
344
+
345
+ *simulation_id* names the Simulation whose ``personaRefs`` and ``worldRef``
346
+ scope the ``subject`` namespace; it may be omitted when the bundle holds
347
+ exactly one Simulation. *dataschemas* maps a Signal id to an already
348
+ resolved JSON Schema for its payload (see the module docstring for why
349
+ resolution is the caller's job).
350
+
351
+ An ``event`` scope is built for every Signal in the bundle, not only the
352
+ Simulation's ``signalRefs``, so a Detector or Journey guard written against
353
+ any bundled Signal can be checked from the same model.
354
+ """
355
+ _, simulation = _select_simulation(bundle, simulation_id)
356
+ spec = simulation.get("spec", {})
357
+
358
+ world_ref = _strip_range(str(spec.get("worldRef", "")))
359
+ world = bundle.flux_docs.get(world_ref)
360
+ if world is None:
361
+ raise ValueError(f"the Simulation's worldRef {world_ref!r} is not in the bundle")
362
+
363
+ persona_ids = [_strip_range(str(ref)) for ref in spec.get("personaRefs", []) or []]
364
+ personas = [
365
+ (persona_id, bundle.flux_docs[persona_id])
366
+ for persona_id in sorted(set(persona_ids), key=nfc)
367
+ if persona_id in bundle.flux_docs and bundle.flux_docs[persona_id].get("kind") == "Persona"
368
+ ]
369
+
370
+ resolved_schemas: Mapping[str, Document] = dataschemas or {}
371
+ event = {
372
+ signal_id: _event_scope(signal_id, pack, resolved_schemas)
373
+ for signal_id, _doc in _documents_of_kind(bundle, "Signal")
374
+ }
375
+
376
+ observed = ScopeModel(
377
+ Scope.OBSERVED,
378
+ {nfc(name): t for name, t in pack.observed_features.items()},
379
+ )
380
+
381
+ return AttributeModel(
382
+ vertical=pack.name,
383
+ subject=_subject_scope(world, personas, sorted(set(persona_ids), key=nfc), pack),
384
+ event=event,
385
+ observed=observed,
386
+ )
@@ -0,0 +1,278 @@
1
+ # Copyright 2026 Agentics Transformation Limited
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """Static type checker for ``flux-expr/1`` against a scope model (EXPR-SPEC §2).
6
+
7
+ EXPR-SPEC §2 is the whole contract of this module:
8
+
9
+ Static type check at plan time against the attribute model: unknown path
10
+ ``FLX-6004``; type mismatch (``market > 3``,
11
+ ``traits.digitalFluency.has('x')``) ``FLX-6005``; comparison between
12
+ different types is an error (no coercion; ``'1' == 1`` is ``FLX-6005``).
13
+
14
+ Everything the checker accepts, :mod:`flux_engine.expr.compile` guarantees to
15
+ evaluate without raising ("Runtime totality: a type-checked expression never
16
+ raises"), so the rules below are exactly the ones the closures are allowed to
17
+ assume.
18
+
19
+ Ambiguities in EXPR-SPEC resolved here, each in the restrictive direction the
20
+ closed-grammar policy calls for:
21
+
22
+ * **Ordering is numeric only.** ``<``, ``<=``, ``>``, ``>=`` accept
23
+ ``number`` on both sides and nothing else. The spec names ``market > 3``
24
+ (an enum against a number) as the ``FLX-6005`` example and never defines an
25
+ order over strings, enums or RFC 3339 ``time``; string ordering is a
26
+ flux-expr/2 request.
27
+ * **``enum`` compares as string, but the string methods stay on ``string``.**
28
+ EXPR-SPEC §2 says an enum "compares as string", which this checker honours
29
+ for ``==`` / ``!=`` / ``in``; §1 declares ``startsWith`` / ``endsWith`` /
30
+ ``contains`` "on ``string``", so an enum target is ``FLX-6005``.
31
+ * **``null`` is a null test, not a value comparison.** EXPR-SPEC §2 makes
32
+ ``null`` "a value any path may carry, not a type", and §2's runtime rules
33
+ give ``!= null`` a truth value of its own. The ``null`` literal is
34
+ therefore accepted only with ``==`` / ``!=`` and only against a *path*:
35
+ ``x == null`` means "x is null", ``x != null`` means "x is not null", and
36
+ ``null`` in any other position is ``FLX-6005``.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ from typing import Optional, Union
42
+
43
+ from flux_engine.expr.ast import (
44
+ And,
45
+ BoolLit,
46
+ Compare,
47
+ Expr,
48
+ In,
49
+ ListLit,
50
+ Method,
51
+ Node,
52
+ Not,
53
+ NullLit,
54
+ NumberLit,
55
+ Operand,
56
+ Or,
57
+ Path,
58
+ StringLit,
59
+ )
60
+ from flux_engine.expr.errors import EnumLiteralError, TypeMismatchError, UnknownPathError
61
+ from flux_engine.expr.types import BOOL, NUMBER, SET_STRING, STRING, ScopeModel, Type, TypeKind
62
+
63
+ __all__ = ["check", "type_of_path", "operand_type"]
64
+
65
+ #: The four ordering operators. ``==`` / ``!=`` are handled separately
66
+ #: because they admit every type, ordering admits only ``number``.
67
+ _ORDERING = ("<", "<=", ">", ">=")
68
+
69
+ #: Methods declared on ``string`` (EXPR-SPEC §1), each taking one string
70
+ #: literal.
71
+ _STRING_METHODS = ("startsWith", "endsWith", "contains")
72
+
73
+
74
+ def type_of_path(path: Path, model: ScopeModel) -> Type:
75
+ """Return the declared type of *path*, resolving sugar; raise ``FLX-6004``."""
76
+ declared = model.type_of(path.text)
77
+ if declared is None:
78
+ raise UnknownPathError(
79
+ f"'{path.text}' is not an attribute of the {model.scope.value} scope"
80
+ )
81
+ return declared
82
+
83
+
84
+ def operand_type(operand: Operand, model: ScopeModel) -> Optional[Type]:
85
+ """Return the type of an ``operand``; ``None`` for the ``null`` literal.
86
+
87
+ ``null`` has no type ("a value any path may carry, not a type"), so it is
88
+ the one operand that returns ``None`` and is handled by the caller.
89
+ """
90
+ if isinstance(operand, Path):
91
+ return type_of_path(operand, model)
92
+ if isinstance(operand, StringLit):
93
+ return STRING
94
+ if isinstance(operand, NumberLit):
95
+ return NUMBER
96
+ if isinstance(operand, BoolLit):
97
+ return BOOL
98
+ if isinstance(operand, NullLit):
99
+ return None
100
+ raise TypeMismatchError(f"not an operand: {type(operand).__name__}")
101
+
102
+
103
+ def _describe(operand: Operand, model: ScopeModel) -> str:
104
+ declared = operand_type(operand, model)
105
+ return "null" if declared is None else declared.name
106
+
107
+
108
+ def _check_enum_literal(declared: Type, literal: StringLit) -> None:
109
+ """A literal compared against an enum must be one of its levels (FLX-6003)."""
110
+ if literal.value not in declared.levels:
111
+ raise EnumLiteralError(
112
+ f"'{literal.value}' is not a level of {declared.name}; "
113
+ f"declared levels are {', '.join(declared.levels)}"
114
+ )
115
+
116
+
117
+ def _check_equality(node: Compare, model: ScopeModel) -> None:
118
+ """``==`` / ``!=``: same type, no coercion, with the enum-as-string rule."""
119
+ left, right = node.left, node.right
120
+
121
+ if isinstance(left, NullLit) or isinstance(right, NullLit):
122
+ other = right if isinstance(left, NullLit) else left
123
+ if isinstance(other, NullLit) or not isinstance(other, Path):
124
+ raise TypeMismatchError(
125
+ "the null literal tests a path for absence; write `<path> == null`"
126
+ )
127
+ type_of_path(other, model) # FLX-6004 for an unknown path
128
+ return
129
+
130
+ left_type = operand_type(left, model)
131
+ right_type = operand_type(right, model)
132
+ assert left_type is not None and right_type is not None # NullLit handled above
133
+
134
+ for declared in (left_type, right_type):
135
+ if declared.kind is TypeKind.SET_STRING:
136
+ raise TypeMismatchError(
137
+ "set<string> has no equality in flux-expr/1; use `in` or `has()`"
138
+ )
139
+
140
+ if left_type.kind is TypeKind.ENUM or right_type.kind is TypeKind.ENUM:
141
+ # "enum<...> (a string drawn from a declared closed set; compares as
142
+ # string; a literal outside the set is FLX-6003 at plan time)".
143
+ for declared, operand in ((left_type, right), (right_type, left)):
144
+ if declared.kind is TypeKind.ENUM and isinstance(operand, StringLit):
145
+ _check_enum_literal(declared, operand)
146
+ if {left_type.kind, right_type.kind} <= {TypeKind.ENUM, TypeKind.STRING}:
147
+ return
148
+ raise TypeMismatchError(
149
+ f"cannot compare {left_type.name} with {right_type.name}; there is no coercion"
150
+ )
151
+
152
+ if left_type != right_type:
153
+ raise TypeMismatchError(
154
+ f"cannot compare {left_type.name} with {right_type.name}; there is no coercion"
155
+ )
156
+
157
+
158
+ def _check_ordering(node: Compare, model: ScopeModel) -> None:
159
+ """``<`` ``<=`` ``>`` ``>=``: ``number`` on both sides, nothing else."""
160
+ for operand in (node.left, node.right):
161
+ declared = operand_type(operand, model)
162
+ if declared != NUMBER:
163
+ raise TypeMismatchError(
164
+ f"'{node.op}' orders numbers; found {_describe(operand, model)}"
165
+ )
166
+
167
+
168
+ def _check_membership(node: In, model: ScopeModel) -> None:
169
+ """``operand in list_lit`` / ``operand in path`` (right side ``set<string>``)."""
170
+ left_type = operand_type(node.left, model)
171
+ if left_type is None:
172
+ raise TypeMismatchError("the null literal is not a member test operand")
173
+
174
+ if isinstance(node.right, Path):
175
+ right_type = type_of_path(node.right, model)
176
+ if right_type != SET_STRING:
177
+ raise TypeMismatchError(
178
+ f"the right side of 'in' must be set<string>; '{node.right.text}' is "
179
+ f"{right_type.name}"
180
+ )
181
+ if left_type.kind not in (TypeKind.STRING, TypeKind.ENUM):
182
+ raise TypeMismatchError(
183
+ f"only a string or enum can be a member of set<string>; found {left_type.name}"
184
+ )
185
+ return
186
+
187
+ assert isinstance(node.right, ListLit)
188
+ for item in node.right.items:
189
+ item_type = operand_type(item, model)
190
+ if item_type is None:
191
+ raise TypeMismatchError("a list literal does not carry null")
192
+ if left_type.kind is TypeKind.ENUM:
193
+ if not isinstance(item, StringLit):
194
+ raise TypeMismatchError(
195
+ f"cannot test {left_type.name} against a {item_type.name} literal"
196
+ )
197
+ _check_enum_literal(left_type, item)
198
+ continue
199
+ if item_type != left_type:
200
+ raise TypeMismatchError(
201
+ f"list literal mixes {item_type.name} with {left_type.name}; there is no coercion"
202
+ )
203
+
204
+
205
+ def _check_method(node: Method, model: ScopeModel) -> None:
206
+ """The closed method set of EXPR-SPEC §1, each on its declared type."""
207
+ target_type = type_of_path(node.target, model)
208
+
209
+ if node.name == "isNull":
210
+ # "isNull() on any path" -- the one method with no receiver type
211
+ # constraint, because every path may carry null.
212
+ if node.args:
213
+ raise TypeMismatchError("isNull() takes no argument")
214
+ return
215
+
216
+ if len(node.args) != 1 or not isinstance(node.args[0], StringLit):
217
+ raise TypeMismatchError(f"{node.name}() takes exactly one string literal")
218
+
219
+ if node.name == "has":
220
+ if target_type != SET_STRING:
221
+ raise TypeMismatchError(
222
+ f"has() is declared on set<string>; '{node.target.text}' is {target_type.name}"
223
+ )
224
+ return
225
+
226
+ assert node.name in _STRING_METHODS
227
+ if target_type != STRING:
228
+ raise TypeMismatchError(
229
+ f"{node.name}() is declared on string; '{node.target.text}' is {target_type.name}"
230
+ )
231
+
232
+
233
+ def _check_expr(node: Union[Expr, Node], model: ScopeModel) -> Type:
234
+ """Type an expression node.
235
+
236
+ The return is always ``BOOL`` or an exception: the grammar gives ``&&``,
237
+ ``||`` and ``!`` nothing but predicates to join, since ``primary`` offers
238
+ no bare operand, and every other expression node is a predicate by
239
+ construction. A node that is not an expression at all -- an operand handed
240
+ in by a caller who built the AST itself -- falls through to the
241
+ ``FLX-6005`` at the end.
242
+ """
243
+ if isinstance(node, (And, Or)):
244
+ _check_expr(node.left, model)
245
+ _check_expr(node.right, model)
246
+ return BOOL
247
+ if isinstance(node, Not):
248
+ _check_expr(node.operand, model)
249
+ return BOOL
250
+ if isinstance(node, Compare):
251
+ if node.op in _ORDERING:
252
+ _check_ordering(node, model)
253
+ else:
254
+ _check_equality(node, model)
255
+ return BOOL
256
+ if isinstance(node, In):
257
+ _check_membership(node, model)
258
+ return BOOL
259
+ if isinstance(node, Method):
260
+ _check_method(node, model)
261
+ return BOOL
262
+ if isinstance(node, BoolLit):
263
+ return BOOL
264
+ raise TypeMismatchError(f"{type(node).__name__} is not a predicate")
265
+
266
+
267
+ def check(node: Expr, model: ScopeModel) -> Type:
268
+ """Type-check *node* against *model*; return its type, which is always ``bool``.
269
+
270
+ Every expression node of the grammar is a predicate -- ``primary`` offers
271
+ no bare operand -- so the returned type is ``bool`` or the call raised:
272
+ ``FLX-6003`` for a literal outside an enum's declared levels, ``FLX-6004``
273
+ for a path the scope does not declare, ``FLX-6005`` for any type mismatch
274
+ (an operand node passed in directly included). A node that survives this
275
+ call can be compiled into a total closure (EXPR-SPEC §2, "Runtime
276
+ totality").
277
+ """
278
+ return _check_expr(node, model)