structa-maestro 0.2.0__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.
- structa_maestro-0.2.0/.gitignore +124 -0
- structa_maestro-0.2.0/CHANGELOG.md +101 -0
- structa_maestro-0.2.0/LICENSE +21 -0
- structa_maestro-0.2.0/PKG-INFO +394 -0
- structa_maestro-0.2.0/README.md +341 -0
- structa_maestro-0.2.0/SECURITY.md +47 -0
- structa_maestro-0.2.0/pyproject.toml +117 -0
- structa_maestro-0.2.0/src/structa_maestro/__init__.py +294 -0
- structa_maestro-0.2.0/src/structa_maestro/batch.py +564 -0
- structa_maestro-0.2.0/src/structa_maestro/binding.py +206 -0
- structa_maestro-0.2.0/src/structa_maestro/builder/__init__.py +0 -0
- structa_maestro-0.2.0/src/structa_maestro/builder/result_builder.py +308 -0
- structa_maestro-0.2.0/src/structa_maestro/cli.py +730 -0
- structa_maestro-0.2.0/src/structa_maestro/confidence/__init__.py +49 -0
- structa_maestro-0.2.0/src/structa_maestro/confidence/calibration.py +990 -0
- structa_maestro-0.2.0/src/structa_maestro/confidence/normalizer.py +203 -0
- structa_maestro-0.2.0/src/structa_maestro/config.py +111 -0
- structa_maestro-0.2.0/src/structa_maestro/contracts/__init__.py +0 -0
- structa_maestro-0.2.0/src/structa_maestro/contracts/enums.py +86 -0
- structa_maestro-0.2.0/src/structa_maestro/contracts/models.py +229 -0
- structa_maestro-0.2.0/src/structa_maestro/contracts/serialization.py +169 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/__init__.py +32 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/docx_parser.py +215 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/eml_parser.py +360 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/html_parser.py +337 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/inputs.py +277 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/loader.py +675 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/markdown_parser.py +225 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/models.py +33 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/normalization.py +24 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/pdf_parser.py +186 -0
- structa_maestro-0.2.0/src/structa_maestro/documents/txt_parser.py +169 -0
- structa_maestro-0.2.0/src/structa_maestro/engine.py +1201 -0
- structa_maestro-0.2.0/src/structa_maestro/exceptions.py +38 -0
- structa_maestro-0.2.0/src/structa_maestro/provenance/__init__.py +0 -0
- structa_maestro-0.2.0/src/structa_maestro/provenance/associator.py +234 -0
- structa_maestro-0.2.0/src/structa_maestro/py.typed +0 -0
- structa_maestro-0.2.0/src/structa_maestro/review.py +1234 -0
- structa_maestro-0.2.0/src/structa_maestro/schema/__init__.py +19 -0
- structa_maestro-0.2.0/src/structa_maestro/schema/loader.py +616 -0
- structa_maestro-0.2.0/src/structa_maestro/schema/models.py +269 -0
- structa_maestro-0.2.0/src/structa_maestro/schema/pydantic_adapter.py +566 -0
- structa_maestro-0.2.0/src/structa_maestro/schema/rules.py +526 -0
- structa_maestro-0.2.0/src/structa_maestro/schema/serializer.py +156 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/__init__.py +45 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/base.py +101 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/llm_anthropic.py +1142 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/llm_config.py +154 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/llm_gemini.py +1171 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/llm_helpers.py +240 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/llm_openai_compat.py +1183 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/schema_compiler.py +248 -0
- structa_maestro-0.2.0/src/structa_maestro/strategies/testing.py +71 -0
- structa_maestro-0.2.0/src/structa_maestro/telemetry.py +800 -0
- structa_maestro-0.2.0/src/structa_maestro/validation/__init__.py +0 -0
- structa_maestro-0.2.0/src/structa_maestro/validation/cross_field.py +463 -0
- structa_maestro-0.2.0/src/structa_maestro/validation/validator.py +531 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# =============================================================================
|
|
2
|
+
# Spec Kit & Generated Specs
|
|
3
|
+
# =============================================================================
|
|
4
|
+
.specify/
|
|
5
|
+
.speckit/
|
|
6
|
+
.agents/
|
|
7
|
+
specs/
|
|
8
|
+
|
|
9
|
+
# =============================================================================
|
|
10
|
+
# Lean 4 Formal Assurance Build Artifacts
|
|
11
|
+
# =============================================================================
|
|
12
|
+
formal/.lake/
|
|
13
|
+
|
|
14
|
+
# =============================================================================
|
|
15
|
+
# Python — Bytecode & Caches
|
|
16
|
+
# =============================================================================
|
|
17
|
+
__pycache__/
|
|
18
|
+
*.py[codz]
|
|
19
|
+
*$py.class
|
|
20
|
+
*.so
|
|
21
|
+
|
|
22
|
+
# =============================================================================
|
|
23
|
+
# Python — Packaging & Distribution
|
|
24
|
+
# =============================================================================
|
|
25
|
+
.Python
|
|
26
|
+
build/
|
|
27
|
+
develop-eggs/
|
|
28
|
+
dist/
|
|
29
|
+
downloads/
|
|
30
|
+
eggs/
|
|
31
|
+
.eggs/
|
|
32
|
+
lib/
|
|
33
|
+
lib64/
|
|
34
|
+
parts/
|
|
35
|
+
sdist/
|
|
36
|
+
var/
|
|
37
|
+
wheels/
|
|
38
|
+
share/python-wheels/
|
|
39
|
+
*.egg-info/
|
|
40
|
+
.installed.cfg
|
|
41
|
+
*.egg
|
|
42
|
+
MANIFEST
|
|
43
|
+
|
|
44
|
+
# =============================================================================
|
|
45
|
+
# Python — Virtual Environments
|
|
46
|
+
# =============================================================================
|
|
47
|
+
.venv/
|
|
48
|
+
venv/
|
|
49
|
+
ENV/
|
|
50
|
+
env/
|
|
51
|
+
env.bak/
|
|
52
|
+
venv.bak/
|
|
53
|
+
|
|
54
|
+
# =============================================================================
|
|
55
|
+
# Testing, Coverage, Linting & Type Checking
|
|
56
|
+
# =============================================================================
|
|
57
|
+
.pytest_cache/
|
|
58
|
+
.hypothesis/
|
|
59
|
+
.tox/
|
|
60
|
+
.nox/
|
|
61
|
+
.coverage
|
|
62
|
+
.coverage.*
|
|
63
|
+
coverage.xml
|
|
64
|
+
htmlcov/
|
|
65
|
+
cover/
|
|
66
|
+
*.cover
|
|
67
|
+
*.py,cover
|
|
68
|
+
.cache/
|
|
69
|
+
.mypy_cache/
|
|
70
|
+
.dmypy.json
|
|
71
|
+
dmypy.json
|
|
72
|
+
.pyre/
|
|
73
|
+
.pytype/
|
|
74
|
+
.ruff_cache/
|
|
75
|
+
.ipynb_checkpoints/
|
|
76
|
+
|
|
77
|
+
# =============================================================================
|
|
78
|
+
# Environment Variables & Secrets
|
|
79
|
+
# =============================================================================
|
|
80
|
+
.env
|
|
81
|
+
.env.*
|
|
82
|
+
!.env.example
|
|
83
|
+
*.pem
|
|
84
|
+
*.key
|
|
85
|
+
|
|
86
|
+
# =============================================================================
|
|
87
|
+
# Documentation Builds
|
|
88
|
+
# =============================================================================
|
|
89
|
+
docs/_build/
|
|
90
|
+
site/
|
|
91
|
+
|
|
92
|
+
# =============================================================================
|
|
93
|
+
# Logs & Temporary Files
|
|
94
|
+
# =============================================================================
|
|
95
|
+
*.log
|
|
96
|
+
logs/
|
|
97
|
+
tmp/
|
|
98
|
+
temp/
|
|
99
|
+
*.tmp
|
|
100
|
+
*.bak
|
|
101
|
+
*.swp
|
|
102
|
+
*.swo
|
|
103
|
+
*~
|
|
104
|
+
|
|
105
|
+
# =============================================================================
|
|
106
|
+
# Editors & IDEs
|
|
107
|
+
# =============================================================================
|
|
108
|
+
.vscode/
|
|
109
|
+
.idea/
|
|
110
|
+
.zed/
|
|
111
|
+
*.sublime-project
|
|
112
|
+
*.sublime-workspace
|
|
113
|
+
|
|
114
|
+
# =============================================================================
|
|
115
|
+
# Operating System Files
|
|
116
|
+
# =============================================================================
|
|
117
|
+
.DS_Store
|
|
118
|
+
.DS_Store?
|
|
119
|
+
._*
|
|
120
|
+
.Spotlight-V100
|
|
121
|
+
.Trashes
|
|
122
|
+
ehthumbs.db
|
|
123
|
+
Thumbs.db
|
|
124
|
+
Desktop.ini
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `structa-maestro` and its Canonical Output Record Contract are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.2.0] - 2026-11-26
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
- **Native Google Gemini Sync & Async Extraction Strategies (`GeminiLLMStrategy`, `AsyncGeminiLLMStrategy`, CLI `--provider gemini`)**:
|
|
13
|
+
- Added hardened, zero-extra-dependency `GeminiLLMStrategy` (`httpx.Client`) and `AsyncGeminiLLMStrategy` (`httpx.AsyncClient` + non-blocking `asyncio.sleep`) in `src/structa_maestro/strategies/llm_gemini.py` targeting Google Gemini's native `POST {base_url}/v1beta/models/{model}:generateContent` endpoint strictly behind Structa's Strategy-to-Contract Firewall (zero Gemini wire-field leakage; Contract `v1.0` unchanged).
|
|
14
|
+
- Enforced header-only `x-goog-api-key` authentication (never appending API keys to URL query strings), eager URL/model/config validation (`base_url` query/fragment rejection, `/v1beta` and `models/` normalization), and extended `sanitize_message` in `src/structa_maestro/config.py` to scrub `x-goog-api-key`, Google `AIza...` tokens, and `?key=` / `&key=` query parameters.
|
|
15
|
+
- Implemented `StructuredOutputMode` parity (`STRICT_WITH_FALLBACK` sending `responseMimeType="application/json"` + compiled closed `responseJsonSchema` with single-step JSON-object fallback, `STRICT` fail-fast with `strict_schema_incompatible`, and `JSON_OBJECT`), Gemini 2.5 `thought: true` part filtering, permanent non-retryable `provider_refusal` on `promptFeedback.blockReason` and safety/recitation/prohibited `finishReason`, `MAX_TOKENS` handling, `RetryPolicy` (`408`/`429`/`5xx`, `Retry-After`, deadlines), `InputBudgetPolicy`, delimiter neutralization, reference-counted `async with`, idempotent `aclose()`, caller-owned `http_client` preservation, and leak-free `asyncio.CancelledError` propagation.
|
|
16
|
+
- Added `parse_gemini_token_usage` in `src/structa_maestro/telemetry.py` mapping `usageMetadata` (`promptTokenCount`, `candidatesTokenCount`, `totalTokenCount`) cumulatively into `StrategyTelemetry` without fabricating missing counts.
|
|
17
|
+
- Exported `GeminiLLMStrategy` and `AsyncGeminiLLMStrategy` from `structa_maestro` and `structa_maestro.strategies`, extended CLI `--provider` to `openai|anthropic|gemini` (`gemini-2.5-flash`, `https://generativelanguage.googleapis.com`, `GEMINI_API_KEY`, `--max-tokens` forwarded to `max_output_tokens`), added offline runnable example `examples/gemini_strategy_example.py`, unit/integration/CLI/public-API/security tests, and synchronized `README.md`, `docs/api.md`, `docs/architecture.md`, `docs/configuration.md`, and `CHANGELOG.md`.
|
|
18
|
+
- **Stateless Human Review & Correction Workflow (`structa_maestro.review`, `review-plan`, `apply-review`)**:
|
|
19
|
+
- Added pure, zero-dependency human review triage and correction primitives in `src/structa_maestro/review.py` (`ReviewPolicy`, `ReviewReason`, `ProvenanceSummary`, `ReviewItem`, `ReviewPlan`, `plan_review`, `ReviewAction`, `FieldReviewDecision`, `RecordReviewDecision`, `ReviewSubmission`, `ReviewAuditEntry`, `ReviewAudit`, `ReviewApplicationResult`, `apply_review`), exported from top-level `structa_maestro`.
|
|
20
|
+
- Implemented deterministic multi-scope triage (`plan_review`) separating low/uncalibrated/missing confidence, unverified/conflicting/missing provenance, ambiguity, field/record/result validation failures, and partial/failed processing without mutating `ExtractionResult`.
|
|
21
|
+
- Implemented immutable decision application (`apply_review`) supporting `APPROVE`, `CORRECT`, `MARK_MISSING`, and `REJECT_RECORD` with mandatory `DeterministicValidator` single-field, cross-field, and cardinality re-validation, strict non-coercion, zero fabricated source provenance, seamless `bind_records` compatibility, and privacy-safe `ReviewAudit` redaction by default (`redact_values=True`).
|
|
22
|
+
- Added offline thin CLI subcommands `structa-maestro review-plan` and `structa-maestro apply-review` (with `5 MiB` file caps, `--audit-json`, and exit codes `0`/`2`/`1`), offline runnable example `examples/human_review_workflow_example.py`, comprehensive unit/contract/Hypothesis/CLI tests, and synchronized `README.md`, `docs/api.md`, `docs/architecture.md`, `docs/configuration.md`, and `CHANGELOG.md`.
|
|
23
|
+
- **Empirical Confidence Calibration (`structa_maestro.confidence`, `--calibrator`, `python -m evals calibrate`)**:
|
|
24
|
+
- Added a stateless, zero-dependency empirical confidence calibration framework in `src/structa_maestro/confidence/calibration.py` providing the runtime-checkable `ConfidenceCalibrator` protocol, immutable versioned pure-JSON `CalibrationModel` (`artifact_version="1.0"`, `extra="forbid"`, `5 MiB` load cap, `to_dict`/`from_dict`/`to_json`/`from_json`/`to_file`/`from_file`), deterministic pure-stdlib fitting (`fit_calibrator`) for isotonic regression (PAVA + piecewise-linear interpolation), monotonic clamped-logit Platt scaling, and uniform/quantile histogram binning, plus deterministic `compute_calibration_metrics` (`ece`, `mce`, `brier_score`, per-bin reliability summaries).
|
|
25
|
+
- Integrated optional `calibrator: ConfidenceCalibrator | None = None` across `ConfidenceNormalizer`, `ResultBuilder`, `ExtractionEngine`, `extract`, `aextract`, `extract_batch`, `aextract_batch`, and thin CLI `--calibrator <path>` on `extract` & `extract-batch`, preserving 100% backward compatibility (`calibrated=False` when omitted), transparent method attribution (`<method>+calibrated:<calibrator>`), `confidence_calibration_scale_mismatch` warnings on non-matching scales, and fault-isolated fallback (`calibrated=False` + `confidence_calibration_failed` warning) on calibrator exceptions or invalid return values.
|
|
26
|
+
- Added `evals/calibration.py` and `python -m evals calibrate` for deterministic labeled sample loading/extraction, stratified K-fold cross-validation, Markdown calibration reports, and verified artifact export (keeping `evals/` excluded from published wheels/sdists and maintaining `0.0000` delta on the 50-case golden baseline).
|
|
27
|
+
- Added offline runnable example `examples/confidence_calibration_example.py`, comprehensive unit/contract/Hypothesis/CLI/evaluation tests, and synchronized `README.md`, `docs/api.md`, `docs/architecture.md`, `docs/configuration.md`, `docs/formal-assurance.md`, and `CHANGELOG.md`.
|
|
28
|
+
- **Formal Assurance Increment 4: Provenance Association, Source-Span Mapping & Full Result Assembly Soundness (`formal/`, 134 Audited Theorems)**:
|
|
29
|
+
- Added two pure Lean 4 modules (`ProvenanceAssociation.lean`, `ResultAssembly.lean`) formally specifying `DocumentSegment`, `_location_from_span` (segment overlap, multi-segment `line_end` clamping, no-overlap fallback), `_bound_excerpt`, `_parse_relationship`, multi-item `ProvenanceAssociator.associate` (foreign-doc rejection, blank-quote silent skip, unlocated `UNVERIFIED`, located `DIRECT` scalar-conflict downgrade to `CONFLICTING`), `formatRecordId` (`record-NNN`), `ConfidenceNormalizer` warnings, and end-to-end `ResultBuilder.build` behind the Strategy-to-Contract Firewall (with `_find_span` and `_scalar_value_supported_by_excerpt` cleanly abstracted).
|
|
30
|
+
- Added 26 new machine-checked theorems (bringing the audited total in `formal/AxiomAuditMain.lean` to **134** theorems across **2,515** kernel-replayed declarations with zero `sorryAx` and core Lean axioms only), culminating in `build_result_satisfies_valid_extraction_result` proving that every `ExtractionResult` assembled by `buildResult` satisfies `ValidExtractionResult` (Contract `v1.0` soundness), alongside `formatRecordId` injectivity, `MISSING` value sanitization, `ambiguous` warning emission, provenance fault isolation forcing `PARTIAL`, validation-only record warning propagation, and empty-failure `extraction_failed` synthesis.
|
|
31
|
+
- Extended `formal/StructaFormal/Oracle.lean` (`location_from_span`, `associate_provenance`, `build_result`) and `tests/conformance/` (`provenance_assembly_reference.py`, `test_provenance_assembly_conformance.py`, `test_lean_oracle_conformance.py`) with Layer 1 deterministic + Hypothesis tests and Layer 2 Lean oracle differential checks across span vectors, multi-item provenance association, 10 curated `ResultBuilder.build` scenarios, and Hypothesis-generated `StrategyOutput` inputs.
|
|
32
|
+
- Updated `docs/formal-assurance.md`, `formal/README.md`, `README.md`, `docs/architecture.md`, and `CHANGELOG.md` with the 134-theorem inventory, expanded assurance matrix, and explicit verification boundaries (zero changes to `src/structa_maestro/`, Contract `v1.0`, or published wheel/sdist contents).
|
|
33
|
+
- **Formal Assurance Increment 3: Declarative Cross-Field & Conditional Validation Semantics (`formal/`, 108 Audited Theorems)**:
|
|
34
|
+
- Extended `formal/StructaFormal/` with the 5 cross-field rule enums in `Enums.lean` (`ComparisonOperator`, `ConditionOperator`, `RuleSeverity`, `ConditionalPresenceKind`, `GroupPresenceKind`) and three new pure Lean 4 modules (`CrossFieldModels.lean`, `CrossFieldInvariants.lean`, `CrossFieldValidation.lean`) formally specifying `ComparisonRule`, `ArithmeticTerm`, `ArithmeticRule`, `FieldCondition`, `ConditionalPresenceRule`, `GroupPresenceRule`, dot-separated path resolution, exact rational balance evaluation (including scalar, numeric array, and array-of-objects `item_field` sums), strict non-coercion skips, and `ERROR` vs. `WARNING` severity separation.
|
|
35
|
+
- Added 30 new machine-checked theorems (bringing the audited total in `formal/AxiomAuditMain.lean` to **108** theorems across **2,159** kernel-replayed declarations with zero `sorryAx` and core Lean axioms only), covering rule well-formedness, determinism, exact rational balance within tolerance, `treat_missing_as_zero`, `is_missing` vs. explicit `null`, nullable `required_if`, `forbidden_if`, `mutually_exclusive`/`at_least_one_of`, `ERROR` rule invalidation of valid fields, and `WARNING` rules never entering `ValidationOutcome.errors` or invalidating valid records.
|
|
36
|
+
- Extended `formal/StructaFormal/Oracle.lean` (backward-compatible optional `"rules"` support and `"warnings"` response field) and `tests/conformance/` (`cross_field_reference.py`, `test_cross_field_conformance.py`, `test_lean_oracle_conformance.py`) with Layer 1 deterministic + Hypothesis tests and Layer 2 Lean oracle differential tests asserting exact agreement on schema validity, record/field statuses, ordered `(field_path, code)` errors, and ordered `(field_path, code)` warnings.
|
|
37
|
+
- Updated `docs/formal-assurance.md`, `formal/README.md`, `README.md`, `docs/architecture.md`, and `CHANGELOG.md` with the 108-theorem inventory and explicit boundaries (zero changes to `src/structa_maestro/`, Contract `v1.0`, or published wheel/sdist contents).
|
|
38
|
+
- **Formal Assurance Increment 2: Schema Well-Formedness & Deterministic Validation Semantics (`formal/`, 78 Audited Theorems)**:
|
|
39
|
+
- Extended `formal/StructaFormal/` with `ExtractionCardinality` in `Enums.lean` and three new pure Lean 4 modules (`SchemaModels.lean`, `SchemaInvariants.lean`, `DeterministicValidation.lean`) formally specifying `ExtractionSchema`, `FieldSpec`, `FieldConstraints`, lossless tagged `RuntimeValue`, and `DeterministicValidator` single-field, nested `OBJECT`/`ARRAY`, extra-field, and `SINGLE`/`MULTIPLE` result cardinality validation (with regex matching abstracted as `PatternMatcher := String → String → Bool` and cross-field rules / Pydantic introspection explicitly out of scope).
|
|
40
|
+
- Added 32 new machine-checked theorems (bringing the audited total in `formal/AxiomAuditMain.lean` to **78** theorems across **1,521** kernel-replayed declarations with zero `sorryAx` and core Lean axioms only), covering schema identity/uniqueness/depth/type-constraint invariants, validation determinism, strict non-coercion (`"42"` vs `INTEGER`, `bool` vs `INTEGER`/`DECIMAL`, `datetime` vs `DATE`, non-finite decimals), presence/nullability separation, extra-field rules, diagnostic soundness, record `VALID ↔ ∀ field VALID`, and cardinality semantics.
|
|
41
|
+
- Extended `formal/StructaFormal/Oracle.lean` (`schema_well_formed`, `validate_record`, `validate_result_cardinality`) and `tests/conformance/` (`schema_reference.py`, `test_schema_validation_conformance.py`, `test_lean_oracle_conformance.py`) with Layer 1 deterministic + Hypothesis tests and Layer 2 Lean oracle differential tests asserting exact agreement on statuses and ordered `(field_path, code)` diagnostic error lists.
|
|
42
|
+
- Updated `docs/formal-assurance.md`, `formal/README.md`, and `README.md` with the expanded theorem inventory, assurance matrix, and verification boundaries (zero changes to `src/structa_maestro/`, Contract `v1.0`, or published wheel/sdist contents).
|
|
43
|
+
- **Formal Assurance Layer for Canonical Output Record Contract v1.0 (`formal/`, Lean 4 + Lake, Two-Layer Conformance & CI)**:
|
|
44
|
+
- Added an independent, zero-external-dependency Lean 4 formal project under `formal/` (pinned to `leanprover/lean4:v4.36.0` via `formal/lean-toolchain`, `warningAsError = true`, excluded from Python wheels/sdists with zero runtime dependency) modeling all 7 Contract v1.0 enums, all 10 Contract v1.0 models, and selected deterministic pipeline-assembly rules (`DeterministicValidator` outcomes, `ConfidenceNormalizer`, `ProvenanceAssociator` classification, and `ResultBuilder` status assembly).
|
|
45
|
+
- Added 46 machine-checked theorems across `FieldInvariants.lean`, `ValidationInvariants.lean`, `ConfidenceInvariants.lean`, `ProvenanceInvariants.lean`, `IdentityInvariants.lean`, `StatusAssembly.lean`, and `Models.lean` (`isValid*_iff` bridges), verified via `structa-axiom-audit` (`lake test`, performing `Lean.Kernel.Environment.replay` kernel replay and `Lean.collectAxioms` checks confirming zero `sorryAx` and core Lean axioms only).
|
|
46
|
+
- Added a two-layer Python-to-Lean conformance suite under `tests/conformance/`: Layer 1 always-on deterministic + Hypothesis conformance tests (no Lean required) and Layer 2 standalone JSONL Lean oracle differential conformance (`structa-formal-oracle`, mandatory when `STRUCTA_REQUIRE_LEAN_ORACLE=1`).
|
|
47
|
+
- Added `.github/workflows/formal-assurance.yml`, gated `.github/workflows/release.yml` publishing on formal verification passing, added packaging/runtime-isolation assertions in `tests/compatibility/test_public_api.py`, and documented guarantees, assumptions, and boundaries in `docs/formal-assurance.md`, `formal/README.md`, `docs/architecture.md`, and `README.md`.
|
|
48
|
+
- **Native Anthropic Messages API Sync & Async Strategies (`AnthropicLLMStrategy`, `AsyncAnthropicLLMStrategy`, CLI `--provider anthropic`)**:
|
|
49
|
+
- Added hardened, zero-dependency `AnthropicLLMStrategy` (`httpx.Client`) and `AsyncAnthropicLLMStrategy` (`httpx.AsyncClient` + non-blocking `asyncio.sleep`) targeting Anthropic's `/v1/messages` API with forced `tool_use` structured output (`emit_extraction_result`), single-step JSON-text fallback, bounded retries (including `429`/`529` overloaded + `Retry-After` + deadlines), `InputBudgetPolicy`, delimiter neutralization, `x-api-key` scrubbing, reference-counted `async with`, idempotent `aclose()`, and `asyncio.CancelledError` propagation.
|
|
50
|
+
- Added `parse_anthropic_token_usage` mapping `input_tokens` → `prompt_tokens` and `output_tokens` → `completion_tokens` cumulatively into `StrategyTelemetry` (leaving omitted `total_tokens` as `None`).
|
|
51
|
+
- Exported `AnthropicLLMStrategy` and `AsyncAnthropicLLMStrategy` from `structa_maestro` and `structa_maestro.strategies`, added backward-compatible CLI `--provider openai|anthropic` and `--max-tokens` flags, added offline runnable example `examples/anthropic_strategy_example.py`, and updated `README.md`, `docs/api.md`, `docs/architecture.md`, and `docs/configuration.md`.
|
|
52
|
+
- **Hardened Zero-Dependency HTML, Markdown & EML Document Parsers (`DocumentFormat.HTML`, `MARKDOWN`, `EML`)**:
|
|
53
|
+
- Extended `DocumentFormat`, `SUPPORTED_MEDIA_TYPES` (`text/html`, `text/markdown`, `message/rfc822`), `DocumentInput` (`from_bytes`/`from_text`/`from_stream`/`from_path`), safe format detection/sniffing, and batch/CLI discovery (`.html`, `.htm`, `.md`, `.markdown`, `.eml`) while rejecting disguised binary payloads cleanly.
|
|
54
|
+
- Added hardened stdlib-only parsers: `html_parser.py` (strips `<script>`/`<style>`/`<noscript>`/`<template>`/comments, incremental entity-expansion `max_decompressed_bytes` guard, zero network I/O, heading/table provenance), `markdown_parser.py` (ATX/Setext `section` tracking ignoring fenced code blocks, 1-indexed line & paragraph locations), and `eml_parser.py` (normalized `Headers` + `text/plain`-preferred / HTML-fallback body, `attachments_skipped` count-only warning, 128-part / 16-depth MIME-bomb guards).
|
|
55
|
+
- Added offline runnable example `examples/multiformat_extraction_example.py`, 6-format cross-format consistency & adversarial security tests, and updated `README.md`, `docs/api.md`, `docs/architecture.md`, and `docs/configuration.md`.
|
|
56
|
+
- **Privacy-Safe Observability Hooks, Stage Telemetry & LLM Token Usage Accounting (`InMemoryTelemetryObserver`, `StructuredLoggingObserver`, `--telemetry-json`)**:
|
|
57
|
+
- Added provider-independent, immutable telemetry models (`ExtractionEventKind`, `TokenUsage`, `StageTiming`, `StageTimingSummary`, `StrategyTelemetry`, `BatchProgress`, `ExtractionEvent`, `TelemetrySummary`), runtime-checkable `ExtractionObserver` / `AsyncExtractionObserver` protocols, and built-in zero-dependency `InMemoryTelemetryObserver` (thread-safe & asyncio-safe collector with exact median `p50_ms` rollups) and `StructuredLoggingObserver`.
|
|
58
|
+
- Extended `StrategyOutput` with optional `telemetry: StrategyTelemetry | None = None`, populating cumulative observed token counts (`prompt_tokens`, `completion_tokens`, `total_tokens`, leaving unreported values as `None`), attempts, retries, structured-output mode/fallback status, and truncation flags across both `OpenAICompatibleLLMStrategy` and `AsyncOpenAICompatibleLLMStrategy`.
|
|
59
|
+
- Added optional `observers` across `ExtractionEngine`, `extract`, `aextract`, `extract_batch`, and `aextract_batch` with eager validation, deterministic engine+call observer composition, correlated `extraction_id`/`batch_id` lifecycle events, strict observer fault isolation (scrubbing credentials without affecting results or `fail_fast`), and leak-free `asyncio.CancelledError` propagation.
|
|
60
|
+
- Added optional `--telemetry-json <path>` flag on `structa-maestro extract` and `extract-batch` (writing `TelemetrySummary` JSON while keeping stdout Contract `v1.0` output unchanged), offline runnable example `examples/observability_telemetry_example.py`, and updated `README.md`, `docs/api.md`, `docs/architecture.md`, and `docs/configuration.md`.
|
|
61
|
+
- **Native Asyncio Extraction API & Async LLM Strategy (`aextract`, `aextract_batch`, `AsyncOpenAICompatibleLLMStrategy`)**:
|
|
62
|
+
- Added runtime-checkable `AsyncExtractionStrategy` protocol, hardened `AsyncOpenAICompatibleLLMStrategy` (backed by `httpx.AsyncClient` and non-blocking `asyncio.sleep` retries with 100% parity with `OpenAICompatibleLLMStrategy`, reference-counted `async with`, idempotent `aclose()`, caller-owned `http_client` preservation, and per-call scoped fallback client), and offline `AsyncDeterministicTestStrategy`.
|
|
63
|
+
- Extended `ExtractionEngine` (`aextract`, `aextract_batch`) and added top-level `aextract` / `aextract_batch` supporting mixed file + `DocumentInput` inputs, `asyncio.to_thread` offloading for blocking parsing and sync strategies, bounded sliding-window async concurrency (`BatchOptions.max_workers` in `1..32`), `fail_fast` parity, and leak-free `asyncio.CancelledError` propagation.
|
|
64
|
+
- Added offline runnable example `examples/async_extraction_example.py`, GitHub community health files (`CODE_OF_CONDUCT.md`, `CONTRIBUTING.md`, enhanced `SECURITY.md`), and updated `README.md`, `docs/api.md`, `docs/architecture.md`, and `docs/configuration.md`.
|
|
65
|
+
- **Pydantic v2 Schema Derivation, Declarative JSON Export & Strict Typed Binding (`from_pydantic`, `to_dict`/`to_json`, `bind_record`/`bind_records`)**:
|
|
66
|
+
- Added `ExtractionSchema.from_pydantic(...)` to deterministically derive immutable `ExtractionSchema` instances from Pydantic v2 `BaseModel` subclasses covering all 7 Contract `v1.0` `FieldType`s, `Enum`/`StrEnum`/`IntEnum`/`Literal`, `Optional`/`| None`, nested `BaseModel`, `list[T]`, `Field(...)`/`Annotated` constraints, exact integer `gt`/`lt` bounds, `ConfigDict(extra=...)`, and declarative cross-field `ValidationRule`s while eagerly rejecting unsupported types (`datetime`, `Any`, multi-type `Union`, custom classes, non-int `gt`/`lt`, `multiple_of`, differing aliases, and cyclic models) with `SchemaDefinitionError`.
|
|
67
|
+
- Added lossless `ExtractionSchema.to_dict()` and `ExtractionSchema.to_json(indent=...)` serialization (including `Decimal`/`date` `allowed_values` round-trip support in `load_schema_from_dict`) so Pydantic-derived schemas export cleanly to JSON files for `structa-maestro extract` and `extract-batch` CLI workflows.
|
|
68
|
+
- Added explicit, opt-in strict non-coercing binding helpers (`bind_record`, `bind_records(only_valid=...)`) and privacy-safe `RecordBindingError` (omitting raw extracted values from messages and `issues`), preserving Canonical Output Record Contract `v1.0` and zero new dependencies, plus offline runnable example `examples/pydantic_schema_example.py` and updated user documentation.
|
|
69
|
+
- **In-Memory Document Inputs & CLI `stdin` Support (`DocumentInput`, `extract -`)**:
|
|
70
|
+
- Added immutable `DocumentInput` and `DocumentInputKind` (`from_path`, `from_bytes`, `from_text`, `from_stream`) with mutable-buffer snapshotting, payload-redacting `__repr__`, POSIX/Windows basename-only filename sanitization, eager media-type validation, and bounded chunked stream reading (`max_file_bytes + 1` cap) with zero temporary files written to disk.
|
|
71
|
+
- Extended `extract`, `ExtractionEngine.extract`, `extract_batch`, and `ExtractionEngine.extract_batch` to accept `DocumentInput` seamlessly alongside `str | Path | BatchDocumentInput`, including safe concurrent batch stream pre-materialization and full fault isolation.
|
|
72
|
+
- Extended `structa-maestro extract` to accept `-` for binary `stdin` piping with stdin-only `--filename` and byte-exact `--max-bytes` override, plus offline runnable example `examples/in_memory_extraction_example.py`.
|
|
73
|
+
- **Stateless Batch Document Extraction (`extract_batch`, `extract-batch`)**:
|
|
74
|
+
- Added stateless in-process batch orchestration (`extract_batch`, `ExtractionEngine.extract_batch`) with immutable models (`BatchDocumentInput`, `BatchOptions`, `BatchSummary`, `BatchExtractionResult`), eager pre-flight validation, exact input-order preservation, and lossless `to_jsonl()`, `to_dict()`, and `to_json()` helpers preserving Canonical Output Record Contract `v1.0` per item.
|
|
75
|
+
- Added bounded in-process concurrency (`max_workers` in `1..32`, default `1`) using a bounded sliding-window worker pool with strict cross-document isolation, default continue-on-error fault isolation, and optional `fail_fast` stopping with honest `skipped_documents` / `aborted_early` accounting.
|
|
76
|
+
- Added thin `structa-maestro extract-batch` CLI subcommand with safe deterministic directory discovery (`--recursive`, hidden/broken-symlink filtering, `followlinks=False`), compact Contract `v1.0` JSONL streaming, optional `--summary-json`, exit codes `0`/`2`/`1`, and runnable example `examples/batch_extraction_example.py`.
|
|
77
|
+
- **Cross-Field & Conditional Validation (`ExtractionSchema.rules`, `DeterministicValidator`)**:
|
|
78
|
+
- Declarative, immutable intra-record validation rules (`ComparisonRule`, `ArithmeticRule`, `ArithmeticTerm`, `FieldCondition`, `ConditionalPresenceRule`, `GroupPresenceRule`) supporting field-to-field comparisons (`eq`, `ne`, `lt`, `lte`, `gt`, `gte`), exact `Decimal` arithmetic balances and nested array collection sums with optional tolerance and `treat_missing_as_zero`, conditional presence (`required_if`, `forbidden_if`), and group constraints (`mutually_exclusive`, `at_least_one_of`).
|
|
79
|
+
- Eager schema-load validation rejecting unknown field paths, incompatible types, duplicate rule IDs, negative tolerances, and unknown rule attributes with `SchemaDefinitionError` (zero arbitrary code execution / `eval`).
|
|
80
|
+
- Configurable `RuleSeverity` (`error` vs. `warning`) preserving Canonical Output Record Contract `v1.0` compliance, per-record multi-record isolation, and runnable example `examples/cross_field_validation_example.py`.
|
|
81
|
+
- **LLM Strategy Hardening & Reliability (`OpenAICompatibleLLMStrategy`)**:
|
|
82
|
+
- Deterministic closed JSON Schema compilation (`CompiledOutputSchema`, `compile_extraction_output_schema`) with configurable `StructuredOutputMode` (`strict_with_fallback` default, `strict`, `json_object`) and automatic single-step non-oscillating compatibility fallback (`structured_output_fallback` warning; `strict_schema_incompatible` fail-fast on open schemas in `strict` mode).
|
|
83
|
+
- Safe Markdown-fence and surrounding-prose JSON envelope recovery (`model_output_sanitized` warning) and recursive nested `Decimal`/`date` JSON-wire handling without mutating invalid values.
|
|
84
|
+
- Configurable bounded `RetryPolicy` (`max_retries=2` default) with exponential backoff, jitter, RFC 7231 `Retry-After` integer/HTTP-date parsing, optional `max_total_seconds` deadline capping, retryable vs. permanent error classification, and `provider_retry_succeeded` warning emission.
|
|
85
|
+
- Configurable character-based `InputBudgetPolicy` (`max_input_chars=120_000` default, or `None` to disable) and `InputBudgetOverflowPolicy` (`reject` default with pre-network `input_budget_exceeded` error, or clean-boundary `truncate` forcing `partial` status with `input_truncated` warning).
|
|
86
|
+
- Embedded `<untrusted_document`/`</untrusted_document` delimiter neutralization in prompt messages while keeping `PreparedDocument` untouched for exact downstream provenance verification, plus end-to-end credential scrubbing across retry and fallback error paths.
|
|
87
|
+
- Optional reliability CLI flags (`--structured-output-mode`, `--max-retries`, `--max-input-chars`, `--overflow-policy`) on both `structa-maestro extract` and `python -m evals run`, plus runnable example `examples/hardened_llm_strategy_example.py`.
|
|
88
|
+
- **Golden Extraction Evaluation Corpus & Regression Suite (`evals/`, repository-internal)**:
|
|
89
|
+
- 50-case curated synthetic golden corpus (`dataset_version: "2.0.0"`) spanning 8 business document categories, 3 formats (`TXT`, `PDF`, `DOCX`), and 10 challenge profiles with deterministic on-disk fixture materialization and committed offline baseline (`evals/baselines/deterministic_v2.0.0.json`).
|
|
90
|
+
- Multi-metric scoring with strict anti-hallucination accounting, provenance verification, repeated-trial (`mean`/`min`/`max`) distributions, zero-regression baseline gating, differential strategy comparison, and `python -m evals` CLI (`validate-dataset`, `run`, `compare`, `diff`), excluded from published wheel and sdist artifacts.
|
|
91
|
+
|
|
92
|
+
## [0.1.0] - 2026-11-22
|
|
93
|
+
|
|
94
|
+
### Added
|
|
95
|
+
- **Canonical Output Record Contract (`1.0`)**: Immutable, strategy-independent `ExtractionResult`, `ExtractedRecord`, `ExtractedField`, `ConfidenceAssessment`, `ProvenanceEvidence`, `SourceLocation`, `ValidationOutcome`, and `DiagnosticIssue` models with lossless JSON round-trip serialization.
|
|
96
|
+
- **Document Input & Parsing**: Safe magic-byte/archive format detection, configurable `DocumentLimits` (default 25 MB raw file, 50 MB decompressed text, 200 pages), and parsers for `TXT`, text-based `PDF`, and `DOCX`.
|
|
97
|
+
- **Schema & Deterministic Validation**: Declarative and programmatic `ExtractionSchema` supporting single- and multi-record extraction, scalar/nested/array types, constraints, nullability, and strict default rejection of unexpected extra fields.
|
|
98
|
+
- **Provenance & Confidence**: Verbatim/normalized source evidence verification (`ProvenanceAssociator`) and explicit uncalibrated confidence normalization (`ConfidenceNormalizer`, `calibrated=False`).
|
|
99
|
+
- **Strategies**: Replaceable `ExtractionStrategy` protocol, `OpenAICompatibleLLMStrategy` (via `httpx` with per-call nonce untrusted-document delimiters), and offline `DeterministicTestStrategy`.
|
|
100
|
+
- **Thin CLI**: Single-document `structa-maestro extract` CLI delegating directly to the library contract.
|
|
101
|
+
- **Verification & CI**: Comprehensive unit, contract, document-processing, integration, golden-dataset evaluation, security, resilience, property-based, and compatibility suites plus GitHub Actions workflows.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 structa-maestro contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|