structa-maestro 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 (55) hide show
  1. structa_maestro/__init__.py +294 -0
  2. structa_maestro/batch.py +564 -0
  3. structa_maestro/binding.py +206 -0
  4. structa_maestro/builder/__init__.py +0 -0
  5. structa_maestro/builder/result_builder.py +308 -0
  6. structa_maestro/cli.py +730 -0
  7. structa_maestro/confidence/__init__.py +49 -0
  8. structa_maestro/confidence/calibration.py +990 -0
  9. structa_maestro/confidence/normalizer.py +203 -0
  10. structa_maestro/config.py +111 -0
  11. structa_maestro/contracts/__init__.py +0 -0
  12. structa_maestro/contracts/enums.py +86 -0
  13. structa_maestro/contracts/models.py +229 -0
  14. structa_maestro/contracts/serialization.py +169 -0
  15. structa_maestro/documents/__init__.py +32 -0
  16. structa_maestro/documents/docx_parser.py +215 -0
  17. structa_maestro/documents/eml_parser.py +360 -0
  18. structa_maestro/documents/html_parser.py +337 -0
  19. structa_maestro/documents/inputs.py +277 -0
  20. structa_maestro/documents/loader.py +675 -0
  21. structa_maestro/documents/markdown_parser.py +225 -0
  22. structa_maestro/documents/models.py +33 -0
  23. structa_maestro/documents/normalization.py +24 -0
  24. structa_maestro/documents/pdf_parser.py +186 -0
  25. structa_maestro/documents/txt_parser.py +169 -0
  26. structa_maestro/engine.py +1201 -0
  27. structa_maestro/exceptions.py +38 -0
  28. structa_maestro/provenance/__init__.py +0 -0
  29. structa_maestro/provenance/associator.py +234 -0
  30. structa_maestro/py.typed +0 -0
  31. structa_maestro/review.py +1234 -0
  32. structa_maestro/schema/__init__.py +19 -0
  33. structa_maestro/schema/loader.py +616 -0
  34. structa_maestro/schema/models.py +269 -0
  35. structa_maestro/schema/pydantic_adapter.py +566 -0
  36. structa_maestro/schema/rules.py +526 -0
  37. structa_maestro/schema/serializer.py +156 -0
  38. structa_maestro/strategies/__init__.py +45 -0
  39. structa_maestro/strategies/base.py +101 -0
  40. structa_maestro/strategies/llm_anthropic.py +1142 -0
  41. structa_maestro/strategies/llm_config.py +154 -0
  42. structa_maestro/strategies/llm_gemini.py +1171 -0
  43. structa_maestro/strategies/llm_helpers.py +240 -0
  44. structa_maestro/strategies/llm_openai_compat.py +1183 -0
  45. structa_maestro/strategies/schema_compiler.py +248 -0
  46. structa_maestro/strategies/testing.py +71 -0
  47. structa_maestro/telemetry.py +800 -0
  48. structa_maestro/validation/__init__.py +0 -0
  49. structa_maestro/validation/cross_field.py +463 -0
  50. structa_maestro/validation/validator.py +531 -0
  51. structa_maestro-0.2.0.dist-info/METADATA +394 -0
  52. structa_maestro-0.2.0.dist-info/RECORD +55 -0
  53. structa_maestro-0.2.0.dist-info/WHEEL +4 -0
  54. structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
  55. structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,526 @@
1
+ """Declarative, immutable cross-field and conditional validation rule models (Spec 004)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass
7
+ from datetime import date, datetime
8
+ from decimal import Decimal, InvalidOperation
9
+ from enum import StrEnum
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from structa_maestro.contracts.enums import FieldType
13
+ from structa_maestro.exceptions import SchemaDefinitionError
14
+
15
+ if TYPE_CHECKING:
16
+ from structa_maestro.schema.models import FieldSpec
17
+
18
+ _NUMERIC_TYPES = frozenset({FieldType.INTEGER, FieldType.DECIMAL})
19
+ _ORDERED_OPERATORS = frozenset({"lt", "lte", "gt", "gte"})
20
+ _SCALAR_COMPARABLE_TYPES = frozenset(
21
+ {FieldType.STRING, FieldType.INTEGER, FieldType.DECIMAL, FieldType.BOOLEAN, FieldType.DATE}
22
+ )
23
+
24
+
25
+ class ComparisonOperator(StrEnum):
26
+ """Comparison operators for field-to-field rules."""
27
+
28
+ EQ = "eq"
29
+ NE = "ne"
30
+ LT = "lt"
31
+ LTE = "lte"
32
+ GT = "gt"
33
+ GTE = "gte"
34
+
35
+
36
+ class ConditionOperator(StrEnum):
37
+ """Predicate operators for controlling fields in conditional presence rules."""
38
+
39
+ IS_PRESENT = "is_present"
40
+ IS_MISSING = "is_missing"
41
+ EQUALS = "equals"
42
+ NOT_EQUALS = "not_equals"
43
+ IN = "in"
44
+
45
+
46
+ class RuleSeverity(StrEnum):
47
+ """Diagnostic severity emitted when a cross-field rule is violated."""
48
+
49
+ ERROR = "error"
50
+ WARNING = "warning"
51
+
52
+
53
+ class ConditionalPresenceKind(StrEnum):
54
+ """Kinds of conditional presence rules."""
55
+
56
+ REQUIRED_IF = "required_if"
57
+ FORBIDDEN_IF = "forbidden_if"
58
+
59
+
60
+ class GroupPresenceKind(StrEnum):
61
+ """Kinds of multi-field group presence rules."""
62
+
63
+ MUTUALLY_EXCLUSIVE = "mutually_exclusive"
64
+ AT_LEAST_ONE_OF = "at_least_one_of"
65
+
66
+
67
+ def _normalize_rule_id(rule_id: str) -> str:
68
+ if not isinstance(rule_id, str) or not rule_id.strip():
69
+ raise SchemaDefinitionError("ValidationRule.rule_id must be a non-empty string.")
70
+ return rule_id.strip()
71
+
72
+
73
+ def _normalize_severity(value: RuleSeverity | str) -> RuleSeverity:
74
+ if isinstance(value, RuleSeverity):
75
+ return value
76
+ if isinstance(value, str):
77
+ try:
78
+ return RuleSeverity(value.strip().lower())
79
+ except ValueError as exc:
80
+ raise SchemaDefinitionError(
81
+ f"Invalid rule severity {value!r}; expected 'error' or 'warning'."
82
+ ) from exc
83
+ raise SchemaDefinitionError("ValidationRule.severity must be a RuleSeverity or string.")
84
+
85
+
86
+ def _normalize_message(message: str | None) -> str | None:
87
+ if message is None:
88
+ return None
89
+ if not isinstance(message, str) or not message.strip():
90
+ raise SchemaDefinitionError("ValidationRule.message must be a non-empty string or None.")
91
+ return message.strip()
92
+
93
+
94
+ def _normalize_path(path: str, label: str) -> str:
95
+ if not isinstance(path, str) or not path.strip():
96
+ raise SchemaDefinitionError(f"{label} must be a non-empty field path.")
97
+ cleaned = path.strip()
98
+ parts = cleaned.split(".")
99
+ if any(not part.strip() for part in parts):
100
+ raise SchemaDefinitionError(f"Invalid field path {path!r} for {label}.")
101
+ return cleaned
102
+
103
+
104
+ @dataclass(frozen=True, slots=True)
105
+ class ComparisonRule:
106
+ """Declarative comparison rule asserting left_field <op> right_field within a record."""
107
+
108
+ rule_id: str
109
+ left_field: str
110
+ operator: ComparisonOperator
111
+ right_field: str
112
+ severity: RuleSeverity = RuleSeverity.ERROR
113
+ message: str | None = None
114
+
115
+ def __post_init__(self) -> None:
116
+ object.__setattr__(self, "rule_id", _normalize_rule_id(self.rule_id))
117
+ left = _normalize_path(self.left_field, "ComparisonRule.left_field")
118
+ right = _normalize_path(self.right_field, "ComparisonRule.right_field")
119
+ if left == right:
120
+ raise SchemaDefinitionError(
121
+ f"ComparisonRule {self.rule_id!r} cannot compare a field to itself ({left!r})."
122
+ )
123
+ object.__setattr__(self, "left_field", left)
124
+ object.__setattr__(self, "right_field", right)
125
+
126
+ if isinstance(self.operator, ComparisonOperator):
127
+ op = self.operator
128
+ elif isinstance(self.operator, str):
129
+ try:
130
+ op = ComparisonOperator(self.operator.strip().lower())
131
+ except ValueError as exc:
132
+ valid = ", ".join(o.value for o in ComparisonOperator)
133
+ raise SchemaDefinitionError(
134
+ f"Invalid ComparisonRule.operator {self.operator!r}; expected one of: {valid}."
135
+ ) from exc
136
+ else:
137
+ raise SchemaDefinitionError("ComparisonRule.operator must be a ComparisonOperator.")
138
+ object.__setattr__(self, "operator", op)
139
+ object.__setattr__(self, "severity", _normalize_severity(self.severity))
140
+ object.__setattr__(self, "message", _normalize_message(self.message))
141
+
142
+
143
+ @dataclass(frozen=True, slots=True)
144
+ class ArithmeticTerm:
145
+ """Signed numeric scalar or collection-sum operand in an ArithmeticRule."""
146
+
147
+ field: str
148
+ sign: int = 1
149
+ item_field: str | None = None
150
+ treat_missing_as_zero: bool = False
151
+
152
+ def __post_init__(self) -> None:
153
+ object.__setattr__(self, "field", _normalize_path(self.field, "ArithmeticTerm.field"))
154
+ if isinstance(self.sign, bool) or self.sign not in (-1, 1):
155
+ raise SchemaDefinitionError("ArithmeticTerm.sign must be 1 or -1.")
156
+ if self.item_field is not None:
157
+ object.__setattr__(
158
+ self,
159
+ "item_field",
160
+ _normalize_path(self.item_field, "ArithmeticTerm.item_field"),
161
+ )
162
+ if not isinstance(self.treat_missing_as_zero, bool):
163
+ raise SchemaDefinitionError("ArithmeticTerm.treat_missing_as_zero must be a boolean.")
164
+
165
+
166
+ @dataclass(frozen=True, slots=True)
167
+ class ArithmeticRule:
168
+ """Declarative exact-decimal arithmetic balance rule: sum(terms) == target_field (+/- tol)."""
169
+
170
+ rule_id: str
171
+ terms: tuple[ArithmeticTerm, ...]
172
+ target_field: str
173
+ tolerance: Decimal = Decimal("0")
174
+ severity: RuleSeverity = RuleSeverity.ERROR
175
+ message: str | None = None
176
+
177
+ def __post_init__(self) -> None:
178
+ object.__setattr__(self, "rule_id", _normalize_rule_id(self.rule_id))
179
+ if not isinstance(self.terms, tuple) or not self.terms:
180
+ raise SchemaDefinitionError(
181
+ f"ArithmeticRule {self.rule_id!r} must define a non-empty tuple of ArithmeticTerm."
182
+ )
183
+ if not all(isinstance(t, ArithmeticTerm) for t in self.terms):
184
+ raise SchemaDefinitionError(
185
+ f"ArithmeticRule {self.rule_id!r} terms must all be ArithmeticTerm instances."
186
+ )
187
+ object.__setattr__(
188
+ self,
189
+ "target_field",
190
+ _normalize_path(self.target_field, "ArithmeticRule.target_field"),
191
+ )
192
+
193
+ raw_tol: Any = self.tolerance
194
+ if isinstance(raw_tol, bool):
195
+ raise SchemaDefinitionError("ArithmeticRule.tolerance cannot be a boolean.")
196
+ if isinstance(raw_tol, Decimal):
197
+ tol = raw_tol
198
+ elif isinstance(raw_tol, (int, float, str)):
199
+ try:
200
+ tol = Decimal(str(raw_tol).strip())
201
+ except InvalidOperation as exc:
202
+ raise SchemaDefinitionError(
203
+ f"Invalid ArithmeticRule.tolerance: {raw_tol!r}"
204
+ ) from exc
205
+ else:
206
+ raise SchemaDefinitionError(f"Invalid ArithmeticRule.tolerance: {raw_tol!r}")
207
+ if tol.is_nan() or tol.is_infinite() or tol < Decimal("0"):
208
+ raise SchemaDefinitionError("ArithmeticRule.tolerance must be a finite Decimal >= 0.")
209
+ object.__setattr__(self, "tolerance", tol)
210
+ object.__setattr__(self, "severity", _normalize_severity(self.severity))
211
+ object.__setattr__(self, "message", _normalize_message(self.message))
212
+
213
+
214
+ @dataclass(frozen=True, slots=True)
215
+ class FieldCondition:
216
+ """Declarative predicate evaluated against a single controlling field."""
217
+
218
+ field: str
219
+ operator: ConditionOperator
220
+ value: Any = None
221
+ values: tuple[Any, ...] | None = None
222
+
223
+ def __post_init__(self) -> None:
224
+ object.__setattr__(self, "field", _normalize_path(self.field, "FieldCondition.field"))
225
+ if isinstance(self.operator, ConditionOperator):
226
+ op = self.operator
227
+ elif isinstance(self.operator, str):
228
+ try:
229
+ op = ConditionOperator(self.operator.strip().lower())
230
+ except ValueError as exc:
231
+ valid = ", ".join(o.value for o in ConditionOperator)
232
+ raise SchemaDefinitionError(
233
+ f"Invalid FieldCondition.operator {self.operator!r}; expected one of: {valid}."
234
+ ) from exc
235
+ else:
236
+ raise SchemaDefinitionError("FieldCondition.operator must be a ConditionOperator.")
237
+ object.__setattr__(self, "operator", op)
238
+
239
+ if op in (ConditionOperator.IS_PRESENT, ConditionOperator.IS_MISSING):
240
+ if self.value is not None or self.values is not None:
241
+ raise SchemaDefinitionError(
242
+ f"FieldCondition with operator {op.value!r} must not set 'value' or 'values'."
243
+ )
244
+ elif op in (ConditionOperator.EQUALS, ConditionOperator.NOT_EQUALS):
245
+ if self.value is None:
246
+ raise SchemaDefinitionError(
247
+ f"FieldCondition with operator {op.value!r} requires a non-None 'value'."
248
+ )
249
+ if self.values is not None:
250
+ raise SchemaDefinitionError(
251
+ f"FieldCondition with operator {op.value!r} must not set 'values'."
252
+ )
253
+ elif op == ConditionOperator.IN:
254
+ if self.value is not None:
255
+ raise SchemaDefinitionError(
256
+ "FieldCondition with operator 'in' must not set 'value'."
257
+ )
258
+ if not isinstance(self.values, tuple) or not self.values:
259
+ raise SchemaDefinitionError(
260
+ "FieldCondition with operator 'in' requires a non-empty 'values' tuple."
261
+ )
262
+ if any(v is None for v in self.values):
263
+ raise SchemaDefinitionError(
264
+ "FieldCondition.values for 'in' cannot contain None entries."
265
+ )
266
+
267
+
268
+ @dataclass(frozen=True, slots=True)
269
+ class ConditionalPresenceRule:
270
+ """Declarative required_if or forbidden_if rule gated by a FieldCondition."""
271
+
272
+ rule_id: str
273
+ kind: ConditionalPresenceKind
274
+ when: FieldCondition
275
+ target_fields: tuple[str, ...]
276
+ severity: RuleSeverity = RuleSeverity.ERROR
277
+ message: str | None = None
278
+
279
+ def __post_init__(self) -> None:
280
+ object.__setattr__(self, "rule_id", _normalize_rule_id(self.rule_id))
281
+ if isinstance(self.kind, ConditionalPresenceKind):
282
+ kind = self.kind
283
+ elif isinstance(self.kind, str):
284
+ try:
285
+ kind = ConditionalPresenceKind(self.kind.strip().lower())
286
+ except ValueError as exc:
287
+ raise SchemaDefinitionError(
288
+ f"Invalid ConditionalPresenceRule.kind {self.kind!r}."
289
+ ) from exc
290
+ else:
291
+ raise SchemaDefinitionError(
292
+ "ConditionalPresenceRule.kind must be ConditionalPresenceKind."
293
+ )
294
+ object.__setattr__(self, "kind", kind)
295
+
296
+ if not isinstance(self.when, FieldCondition):
297
+ raise SchemaDefinitionError(
298
+ "ConditionalPresenceRule.when must be a FieldCondition instance."
299
+ )
300
+ if not isinstance(self.target_fields, tuple) or not self.target_fields:
301
+ raise SchemaDefinitionError(
302
+ f"ConditionalPresenceRule {self.rule_id!r} must specify non-empty target_fields."
303
+ )
304
+ normalized_targets = tuple(
305
+ _normalize_path(t, "ConditionalPresenceRule.target_fields") for t in self.target_fields
306
+ )
307
+ if len(set(normalized_targets)) != len(normalized_targets):
308
+ raise SchemaDefinitionError(
309
+ f"ConditionalPresenceRule {self.rule_id!r} target_fields must be unique."
310
+ )
311
+ if self.when.field in normalized_targets:
312
+ raise SchemaDefinitionError(
313
+ f"ConditionalPresenceRule {self.rule_id!r} controlling field "
314
+ f"{self.when.field!r} cannot also appear in target_fields."
315
+ )
316
+ object.__setattr__(self, "target_fields", normalized_targets)
317
+ object.__setattr__(self, "severity", _normalize_severity(self.severity))
318
+ object.__setattr__(self, "message", _normalize_message(self.message))
319
+
320
+
321
+ @dataclass(frozen=True, slots=True)
322
+ class GroupPresenceRule:
323
+ """Declarative mutually_exclusive or at_least_one_of rule across >= 2 distinct fields."""
324
+
325
+ rule_id: str
326
+ kind: GroupPresenceKind
327
+ fields: tuple[str, ...]
328
+ severity: RuleSeverity = RuleSeverity.ERROR
329
+ message: str | None = None
330
+
331
+ def __post_init__(self) -> None:
332
+ object.__setattr__(self, "rule_id", _normalize_rule_id(self.rule_id))
333
+ if isinstance(self.kind, GroupPresenceKind):
334
+ kind = self.kind
335
+ elif isinstance(self.kind, str):
336
+ try:
337
+ kind = GroupPresenceKind(self.kind.strip().lower())
338
+ except ValueError as exc:
339
+ raise SchemaDefinitionError(
340
+ f"Invalid GroupPresenceRule.kind {self.kind!r}."
341
+ ) from exc
342
+ else:
343
+ raise SchemaDefinitionError("GroupPresenceRule.kind must be GroupPresenceKind.")
344
+ object.__setattr__(self, "kind", kind)
345
+
346
+ if not isinstance(self.fields, tuple) or len(self.fields) < 2:
347
+ raise SchemaDefinitionError(
348
+ f"GroupPresenceRule {self.rule_id!r} requires at least 2 distinct fields."
349
+ )
350
+ normalized = tuple(_normalize_path(f, "GroupPresenceRule.fields") for f in self.fields)
351
+ if len(set(normalized)) != len(normalized):
352
+ raise SchemaDefinitionError(
353
+ f"GroupPresenceRule {self.rule_id!r} fields must all be distinct."
354
+ )
355
+ object.__setattr__(self, "fields", normalized)
356
+ object.__setattr__(self, "severity", _normalize_severity(self.severity))
357
+ object.__setattr__(self, "message", _normalize_message(self.message))
358
+
359
+
360
+ ValidationRule = ComparisonRule | ArithmeticRule | ConditionalPresenceRule | GroupPresenceRule
361
+
362
+
363
+ def resolve_schema_field_spec(
364
+ fields: Mapping[str, FieldSpec],
365
+ path: str,
366
+ ) -> FieldSpec:
367
+ """Resolve a top-level or dot-separated nested object path against declared FieldSpecs."""
368
+ segments = path.split(".")
369
+ current_map: Mapping[str, FieldSpec] = fields
370
+ current_spec: FieldSpec | None = None
371
+
372
+ for idx, seg in enumerate(segments):
373
+ spec = current_map.get(seg)
374
+ if spec is None:
375
+ raise SchemaDefinitionError(
376
+ f"Validation rule references unknown field path {path!r} (missing {seg!r})."
377
+ )
378
+ current_spec = spec
379
+ if idx < len(segments) - 1:
380
+ if spec.field_type != FieldType.OBJECT or not spec.properties:
381
+ raise SchemaDefinitionError(
382
+ f"Validation rule path {path!r} traverses non-object field {seg!r}."
383
+ )
384
+ current_map = spec.properties
385
+
386
+ if current_spec is None:
387
+ raise SchemaDefinitionError(f"Validation rule references invalid field path {path!r}.")
388
+ return current_spec
389
+
390
+
391
+ def _types_compatible_for_comparison(
392
+ left_type: FieldType,
393
+ right_type: FieldType,
394
+ operator: ComparisonOperator,
395
+ ) -> bool:
396
+ if left_type not in _SCALAR_COMPARABLE_TYPES or right_type not in _SCALAR_COMPARABLE_TYPES:
397
+ return False
398
+ if operator.value in _ORDERED_OPERATORS:
399
+ if left_type == FieldType.BOOLEAN or right_type == FieldType.BOOLEAN:
400
+ return False
401
+ if left_type in _NUMERIC_TYPES and right_type in _NUMERIC_TYPES:
402
+ return True
403
+ return left_type == right_type
404
+ # Equality / inequality
405
+ if left_type in _NUMERIC_TYPES and right_type in _NUMERIC_TYPES:
406
+ return True
407
+ return left_type == right_type
408
+
409
+
410
+ def _is_literal_compatible(val: Any, field_type: FieldType) -> bool:
411
+ if field_type == FieldType.STRING:
412
+ return isinstance(val, str)
413
+ if field_type == FieldType.BOOLEAN:
414
+ return isinstance(val, bool)
415
+ if field_type == FieldType.INTEGER:
416
+ return not isinstance(val, bool) and isinstance(val, int)
417
+ if field_type == FieldType.DECIMAL:
418
+ if isinstance(val, bool) or not isinstance(val, (Decimal, int, float)):
419
+ return False
420
+ dec = val if isinstance(val, Decimal) else Decimal(str(val))
421
+ return not (dec.is_nan() or dec.is_infinite())
422
+ if field_type == FieldType.DATE:
423
+ return isinstance(val, date) and not isinstance(val, datetime)
424
+ return False
425
+
426
+
427
+ def validate_schema_rules(
428
+ fields: Mapping[str, FieldSpec],
429
+ rules: tuple[ValidationRule, ...],
430
+ ) -> None:
431
+ """Eagerly validate every declared cross-field rule against ExtractionSchema fields."""
432
+ if not isinstance(rules, tuple):
433
+ raise SchemaDefinitionError("ExtractionSchema.rules must be a tuple of ValidationRule.")
434
+
435
+ seen_ids: set[str] = set()
436
+ for rule in rules:
437
+ if not isinstance(
438
+ rule,
439
+ (ComparisonRule, ArithmeticRule, ConditionalPresenceRule, GroupPresenceRule),
440
+ ):
441
+ raise SchemaDefinitionError(f"Unsupported validation rule object: {rule!r}")
442
+ if rule.rule_id in seen_ids:
443
+ raise SchemaDefinitionError(
444
+ f"Duplicate cross-field validation rule_id: {rule.rule_id!r}"
445
+ )
446
+ seen_ids.add(rule.rule_id)
447
+
448
+ if isinstance(rule, ComparisonRule):
449
+ left_spec = resolve_schema_field_spec(fields, rule.left_field)
450
+ right_spec = resolve_schema_field_spec(fields, rule.right_field)
451
+ if not _types_compatible_for_comparison(
452
+ left_spec.field_type,
453
+ right_spec.field_type,
454
+ rule.operator,
455
+ ):
456
+ raise SchemaDefinitionError(
457
+ f"ComparisonRule {rule.rule_id!r}: operator {rule.operator.value!r} "
458
+ f"is incompatible with types {left_spec.field_type.value!r} and "
459
+ f"{right_spec.field_type.value!r}."
460
+ )
461
+
462
+ elif isinstance(rule, ArithmeticRule):
463
+ target_spec = resolve_schema_field_spec(fields, rule.target_field)
464
+ if target_spec.field_type not in _NUMERIC_TYPES:
465
+ raise SchemaDefinitionError(
466
+ f"ArithmeticRule {rule.rule_id!r}: target_field {rule.target_field!r} "
467
+ f"must be integer or decimal, got {target_spec.field_type.value!r}."
468
+ )
469
+ for term in rule.terms:
470
+ term_spec = resolve_schema_field_spec(fields, term.field)
471
+ if term.item_field is not None:
472
+ if (
473
+ term_spec.field_type != FieldType.ARRAY
474
+ or term_spec.items is None
475
+ or term_spec.items.field_type != FieldType.OBJECT
476
+ or not term_spec.items.properties
477
+ ):
478
+ raise SchemaDefinitionError(
479
+ f"ArithmeticRule {rule.rule_id!r}: term {term.field!r} with "
480
+ f"item_field {term.item_field!r} requires an array of objects."
481
+ )
482
+ item_spec = resolve_schema_field_spec(
483
+ term_spec.items.properties,
484
+ term.item_field,
485
+ )
486
+ if item_spec.field_type not in _NUMERIC_TYPES:
487
+ raise SchemaDefinitionError(
488
+ f"ArithmeticRule {rule.rule_id!r}: item_field "
489
+ f"{term.field}[].{term.item_field} must be numeric, got "
490
+ f"{item_spec.field_type.value!r}."
491
+ )
492
+ elif term_spec.field_type == FieldType.ARRAY:
493
+ if term_spec.items is None or term_spec.items.field_type not in _NUMERIC_TYPES:
494
+ raise SchemaDefinitionError(
495
+ f"ArithmeticRule {rule.rule_id!r}: array term {term.field!r} without "
496
+ "item_field must contain numeric items."
497
+ )
498
+ elif term_spec.field_type not in _NUMERIC_TYPES:
499
+ raise SchemaDefinitionError(
500
+ f"ArithmeticRule {rule.rule_id!r}: term {term.field!r} must be numeric, "
501
+ f"got {term_spec.field_type.value!r}."
502
+ )
503
+
504
+ elif isinstance(rule, ConditionalPresenceRule):
505
+ cond_spec = resolve_schema_field_spec(fields, rule.when.field)
506
+ if rule.when.operator in (ConditionOperator.EQUALS, ConditionOperator.NOT_EQUALS):
507
+ if not _is_literal_compatible(rule.when.value, cond_spec.field_type):
508
+ raise SchemaDefinitionError(
509
+ f"ConditionalPresenceRule {rule.rule_id!r}: condition value "
510
+ f"{rule.when.value!r} is incompatible with field "
511
+ f"{rule.when.field!r} ({cond_spec.field_type.value})."
512
+ )
513
+ elif rule.when.operator == ConditionOperator.IN and rule.when.values is not None:
514
+ for val in rule.when.values:
515
+ if not _is_literal_compatible(val, cond_spec.field_type):
516
+ raise SchemaDefinitionError(
517
+ f"ConditionalPresenceRule {rule.rule_id!r}: condition 'in' value "
518
+ f"{val!r} is incompatible with field {rule.when.field!r} "
519
+ f"({cond_spec.field_type.value})."
520
+ )
521
+ for tf in rule.target_fields:
522
+ resolve_schema_field_spec(fields, tf)
523
+
524
+ elif isinstance(rule, GroupPresenceRule):
525
+ for fname in rule.fields:
526
+ resolve_schema_field_spec(fields, fname)
@@ -0,0 +1,156 @@
1
+ """Lossless declarative dictionary and JSON serialization for ExtractionSchema (Spec 007)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import date
7
+ from decimal import Decimal
8
+ from typing import Any
9
+
10
+ from structa_maestro.contracts.enums import FieldType
11
+ from structa_maestro.schema.models import ExtractionSchema, FieldSpec
12
+ from structa_maestro.schema.rules import (
13
+ ArithmeticRule,
14
+ ComparisonRule,
15
+ ConditionalPresenceRule,
16
+ ValidationRule,
17
+ )
18
+
19
+
20
+ def _encode_json_scalar(value: Any) -> Any:
21
+ if isinstance(value, Decimal):
22
+ return str(value)
23
+ if isinstance(value, date):
24
+ return value.isoformat()
25
+ return value
26
+
27
+
28
+ def _serialize_field_spec(spec: FieldSpec) -> dict[str, Any]:
29
+ out: dict[str, Any] = {
30
+ "type": spec.field_type.value,
31
+ "required": spec.required,
32
+ "nullable": spec.nullable,
33
+ }
34
+ if spec.description is not None:
35
+ out["description"] = spec.description
36
+
37
+ c = spec.constraints
38
+ if c.min_value is not None:
39
+ out["min_value"] = _encode_json_scalar(c.min_value)
40
+ if c.max_value is not None:
41
+ out["max_value"] = _encode_json_scalar(c.max_value)
42
+ if c.min_length is not None:
43
+ out["min_length"] = c.min_length
44
+ if c.max_length is not None:
45
+ out["max_length"] = c.max_length
46
+ if c.min_items is not None:
47
+ out["min_items"] = c.min_items
48
+ if c.max_items is not None:
49
+ out["max_items"] = c.max_items
50
+ if c.pattern is not None:
51
+ out["pattern"] = c.pattern
52
+ if c.allowed_values is not None:
53
+ out["allowed_values"] = [_encode_json_scalar(v) for v in c.allowed_values]
54
+
55
+ if spec.field_type == FieldType.OBJECT and spec.properties is not None:
56
+ out["properties"] = {
57
+ prop_name: _serialize_field_spec(prop_spec)
58
+ for prop_name, prop_spec in spec.properties.items()
59
+ }
60
+ out["allow_additional_fields"] = spec.allow_additional_fields
61
+
62
+ if spec.field_type == FieldType.ARRAY and spec.items is not None:
63
+ out["items"] = _serialize_field_spec(spec.items)
64
+
65
+ return out
66
+
67
+
68
+ def _serialize_rule(rule: ValidationRule) -> dict[str, Any]:
69
+ if isinstance(rule, ComparisonRule):
70
+ out: dict[str, Any] = {
71
+ "rule_id": rule.rule_id,
72
+ "kind": "comparison",
73
+ "left_field": rule.left_field,
74
+ "operator": rule.operator.value,
75
+ "right_field": rule.right_field,
76
+ "severity": rule.severity.value,
77
+ }
78
+ if rule.message is not None:
79
+ out["message"] = rule.message
80
+ return out
81
+
82
+ if isinstance(rule, ArithmeticRule):
83
+ terms: list[dict[str, Any]] = []
84
+ for term in rule.terms:
85
+ t_dict: dict[str, Any] = {
86
+ "field": term.field,
87
+ "sign": term.sign,
88
+ "treat_missing_as_zero": term.treat_missing_as_zero,
89
+ }
90
+ if term.item_field is not None:
91
+ t_dict["item_field"] = term.item_field
92
+ terms.append(t_dict)
93
+ out = {
94
+ "rule_id": rule.rule_id,
95
+ "kind": "arithmetic",
96
+ "terms": terms,
97
+ "target_field": rule.target_field,
98
+ "tolerance": str(rule.tolerance),
99
+ "severity": rule.severity.value,
100
+ }
101
+ if rule.message is not None:
102
+ out["message"] = rule.message
103
+ return out
104
+
105
+ if isinstance(rule, ConditionalPresenceRule):
106
+ when_dict: dict[str, Any] = {
107
+ "field": rule.when.field,
108
+ "operator": rule.when.operator.value,
109
+ }
110
+ if rule.when.value is not None:
111
+ when_dict["value"] = _encode_json_scalar(rule.when.value)
112
+ if rule.when.values is not None:
113
+ when_dict["values"] = [_encode_json_scalar(v) for v in rule.when.values]
114
+ out = {
115
+ "rule_id": rule.rule_id,
116
+ "kind": rule.kind.value,
117
+ "when": when_dict,
118
+ "target_fields": list(rule.target_fields),
119
+ "severity": rule.severity.value,
120
+ }
121
+ if rule.message is not None:
122
+ out["message"] = rule.message
123
+ return out
124
+
125
+ # GroupPresenceRule
126
+ out = {
127
+ "rule_id": rule.rule_id,
128
+ "kind": rule.kind.value,
129
+ "fields": list(rule.fields),
130
+ "severity": rule.severity.value,
131
+ }
132
+ if rule.message is not None:
133
+ out["message"] = rule.message
134
+ return out
135
+
136
+
137
+ def serialize_schema_to_dict(schema: ExtractionSchema) -> dict[str, Any]:
138
+ """Serialize an ExtractionSchema into a JSON-safe declarative dictionary."""
139
+ out: dict[str, Any] = {
140
+ "schema_id": schema.schema_id,
141
+ "schema_version": schema.schema_version,
142
+ "cardinality": schema.cardinality.value,
143
+ "allow_additional_fields": schema.allow_additional_fields,
144
+ "max_depth": schema.max_depth,
145
+ "fields": {
146
+ field_name: _serialize_field_spec(spec) for field_name, spec in schema.fields.items()
147
+ },
148
+ }
149
+ if schema.rules:
150
+ out["rules"] = [_serialize_rule(rule) for rule in schema.rules]
151
+ return out
152
+
153
+
154
+ def serialize_schema_to_json(schema: ExtractionSchema, *, indent: int | None = None) -> str:
155
+ """Serialize an ExtractionSchema into a declarative JSON string."""
156
+ return json.dumps(serialize_schema_to_dict(schema), indent=indent, ensure_ascii=False)