forecast-anything 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 (162) hide show
  1. forecast_anything/LICENSE +177 -0
  2. forecast_anything/NOTICE +39 -0
  3. forecast_anything/__init__.py +1 -0
  4. forecast_anything/_contracts/__init__.py +1 -0
  5. forecast_anything/_contracts/common.py +65 -0
  6. forecast_anything/_contracts/discovery.py +311 -0
  7. forecast_anything/_contracts/forecasts.py +300 -0
  8. forecast_anything/_contracts/notifications.py +102 -0
  9. forecast_anything/_contracts/questions.py +191 -0
  10. forecast_anything/_contracts/sources.py +154 -0
  11. forecast_anything/_storage/__init__.py +1 -0
  12. forecast_anything/_storage/discovery.py +272 -0
  13. forecast_anything/_storage/encoding.py +16 -0
  14. forecast_anything/_storage/inbox.py +263 -0
  15. forecast_anything/_storage/operations.py +303 -0
  16. forecast_anything/_storage/runs.py +246 -0
  17. forecast_anything/_storage/watches.py +233 -0
  18. forecast_anything/_storage/webhooks.py +318 -0
  19. forecast_anything/_worker_discovery.py +274 -0
  20. forecast_anything/_worker_requalification.py +303 -0
  21. forecast_anything/_worker_sources.py +364 -0
  22. forecast_anything/_worker_watches.py +249 -0
  23. forecast_anything/api/__init__.py +1 -0
  24. forecast_anything/api/app.py +228 -0
  25. forecast_anything/api/errors.py +70 -0
  26. forecast_anything/api/routes.py +226 -0
  27. forecast_anything/api/routes_events.py +74 -0
  28. forecast_anything/api/routes_jobs.py +108 -0
  29. forecast_anything/api/routes_sources.py +73 -0
  30. forecast_anything/api/routes_subscriptions.py +64 -0
  31. forecast_anything/api/scenarios.py +101 -0
  32. forecast_anything/api/service.py +219 -0
  33. forecast_anything/api/service_discovery.py +150 -0
  34. forecast_anything/api/service_jobs.py +356 -0
  35. forecast_anything/api/service_questions.py +251 -0
  36. forecast_anything/api/service_updates.py +176 -0
  37. forecast_anything/backtesting/__init__.py +1 -0
  38. forecast_anything/backtesting/contracts.py +299 -0
  39. forecast_anything/backtesting/planning.py +265 -0
  40. forecast_anything/backtesting/runner.py +381 -0
  41. forecast_anything/backtesting/selection.py +130 -0
  42. forecast_anything/backtesting/service.py +426 -0
  43. forecast_anything/backtesting/store.py +420 -0
  44. forecast_anything/cli.py +394 -0
  45. forecast_anything/cli_arguments.py +130 -0
  46. forecast_anything/connectors/csv.py +90 -0
  47. forecast_anything/connectors/http_json.py +237 -0
  48. forecast_anything/continuity.py +97 -0
  49. forecast_anything/contracts/v1/openapi.json +10476 -0
  50. forecast_anything/contracts/v1/schemas.json +13076 -0
  51. forecast_anything/contracts.py +257 -0
  52. forecast_anything/diagnostics.py +236 -0
  53. forecast_anything/discovery/agent_gateway.py +135 -0
  54. forecast_anything/discovery/agent_storage.py +177 -0
  55. forecast_anything/discovery/candidates.py +383 -0
  56. forecast_anything/discovery/policy.py +271 -0
  57. forecast_anything/evaluation/_legacy_metrics.py +95 -0
  58. forecast_anything/evaluation/calendar_covariates.py +87 -0
  59. forecast_anything/evaluation/conformal.py +201 -0
  60. forecast_anything/evaluation/holidays.py +93 -0
  61. forecast_anything/evaluation/metrics.py +117 -0
  62. forecast_anything/evaluation/paired_bootstrap.py +174 -0
  63. forecast_anything/evaluation/records.py +259 -0
  64. forecast_anything/evaluation/residual_correction.py +345 -0
  65. forecast_anything/evaluation/residual_features.py +227 -0
  66. forecast_anything/evaluation/selection_stability.py +80 -0
  67. forecast_anything/evaluation/splits.py +144 -0
  68. forecast_anything/examples/minimal/graph.json +13 -0
  69. forecast_anything/examples/minimal/observations.csv +5 -0
  70. forecast_anything/forecast_policy.py +97 -0
  71. forecast_anything/graph.py +258 -0
  72. forecast_anything/jobs.py +287 -0
  73. forecast_anything/local_services.py +152 -0
  74. forecast_anything/mcp_adapter/__init__.py +1 -0
  75. forecast_anything/mcp_adapter/agent_descriptions.py +128 -0
  76. forecast_anything/mcp_adapter/arguments.py +318 -0
  77. forecast_anything/mcp_adapter/catalog.py +124 -0
  78. forecast_anything/mcp_adapter/client.py +261 -0
  79. forecast_anything/mcp_adapter/config.py +168 -0
  80. forecast_anything/mcp_adapter/context_views.py +212 -0
  81. forecast_anything/mcp_adapter/csv_folders.py +78 -0
  82. forecast_anything/mcp_adapter/dispatch.py +16 -0
  83. forecast_anything/mcp_adapter/forecast_tools.py +261 -0
  84. forecast_anything/mcp_adapter/instructions.md +7 -0
  85. forecast_anything/mcp_adapter/operation_tools.py +106 -0
  86. forecast_anything/mcp_adapter/protocol.py +144 -0
  87. forecast_anything/mcp_adapter/question_tools.py +241 -0
  88. forecast_anything/mcp_adapter/server.py +201 -0
  89. forecast_anything/mcp_adapter/source_tools.py +168 -0
  90. forecast_anything/mcp_adapter/summaries.py +15 -0
  91. forecast_anything/mcp_adapter/ui_dist/context.html +112 -0
  92. forecast_anything/mcp_adapter/watch_tools.py +133 -0
  93. forecast_anything/mcp_adapter/workspace_tools.py +77 -0
  94. forecast_anything/mcp_clients.py +231 -0
  95. forecast_anything/migrations/001_initial.sql +25 -0
  96. forecast_anything/migrations/002_evaluations.sql +10 -0
  97. forecast_anything/migrations/003_discovery.sql +50 -0
  98. forecast_anything/migrations/004_observatory.sql +26 -0
  99. forecast_anything/migrations/005_jobs.sql +32 -0
  100. forecast_anything/migrations/006_scenarios.sql +7 -0
  101. forecast_anything/migrations/007_agent_operations.sql +31 -0
  102. forecast_anything/migrations/008_backtests.sql +40 -0
  103. forecast_anything/migrations/009_worker_liveness.sql +8 -0
  104. forecast_anything/migrations/010_worker_runtime.sql +8 -0
  105. forecast_anything/migrations/011_persistent_questions.sql +69 -0
  106. forecast_anything/migrations/012_workspace_identity.sql +8 -0
  107. forecast_anything/migrations/013_continuity_and_inbox.sql +78 -0
  108. forecast_anything/migrations/014_workspace_forecast_checkpoint.sql +13 -0
  109. forecast_anything/operators/__init__.py +13 -0
  110. forecast_anything/operators/base.py +10 -0
  111. forecast_anything/operators/events.py +58 -0
  112. forecast_anything/operators/temporal.py +175 -0
  113. forecast_anything/presentations/__init__.py +40 -0
  114. forecast_anything/presentations/backtest.py +208 -0
  115. forecast_anything/presentations/forecast.py +218 -0
  116. forecast_anything/presentations/question.py +56 -0
  117. forecast_anything/presentations/snapshot.py +102 -0
  118. forecast_anything/providers/base.py +65 -0
  119. forecast_anything/providers/baseline.py +69 -0
  120. forecast_anything/providers/calendar_member.py +47 -0
  121. forecast_anything/providers/classical.py +138 -0
  122. forecast_anything/providers/classical_statsforecast.py +100 -0
  123. forecast_anything/providers/configuration.py +84 -0
  124. forecast_anything/providers/ensemble.py +339 -0
  125. forecast_anything/providers/ensemble_combine.py +262 -0
  126. forecast_anything/providers/ensemble_pair.py +141 -0
  127. forecast_anything/providers/ensemble_weights.py +423 -0
  128. forecast_anything/providers/pipeline.py +248 -0
  129. forecast_anything/providers/pipeline_auto.py +326 -0
  130. forecast_anything/providers/pipeline_backtest.py +360 -0
  131. forecast_anything/providers/pipeline_calibration.py +180 -0
  132. forecast_anything/providers/pipeline_candidates.py +220 -0
  133. forecast_anything/providers/pipeline_options.py +177 -0
  134. forecast_anything/providers/pipeline_selection.py +312 -0
  135. forecast_anything/providers/timestral.py +340 -0
  136. forecast_anything/question_storage.py +407 -0
  137. forecast_anything/runtime.py +417 -0
  138. forecast_anything/runtime_results.py +149 -0
  139. forecast_anything/service_systemd.py +252 -0
  140. forecast_anything/setup_local.py +413 -0
  141. forecast_anything/sources/calendar_days.py +96 -0
  142. forecast_anything/sources/catalog.py +142 -0
  143. forecast_anything/sources/profiling.py +449 -0
  144. forecast_anything/store.py +332 -0
  145. forecast_anything/temporal.py +92 -0
  146. forecast_anything/uncertainty/history_panels.py +134 -0
  147. forecast_anything/uncertainty/joint_dependence.py +98 -0
  148. forecast_anything/uncertainty/joint_marginals.py +44 -0
  149. forecast_anything/uncertainty/joint_provider.py +266 -0
  150. forecast_anything/uncertainty/joint_samples.py +89 -0
  151. forecast_anything/uncertainty/residual_panels.py +189 -0
  152. forecast_anything/uncertainty/seasonal_panels.py +48 -0
  153. forecast_anything/watch_updates.py +154 -0
  154. forecast_anything/watches.py +449 -0
  155. forecast_anything/worker.py +385 -0
  156. forecast_anything/workspace_config.py +219 -0
  157. forecast_anything-0.2.0.dist-info/METADATA +123 -0
  158. forecast_anything-0.2.0.dist-info/RECORD +162 -0
  159. forecast_anything-0.2.0.dist-info/WHEEL +4 -0
  160. forecast_anything-0.2.0.dist-info/entry_points.txt +2 -0
  161. forecast_anything-0.2.0.dist-info/licenses/LICENSE +177 -0
  162. forecast_anything-0.2.0.dist-info/licenses/NOTICE +39 -0
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,39 @@
1
+ Forecast Anything — release-candidate materials
2
+
3
+ The project name, public owner, package registry and domain are provisional.
4
+ Apache-2.0 is the roadmap's proposed license for project code; the accompanying
5
+ LICENSE is prepared for that release candidate. Public release is a separate
6
+ decision. This notice does not assign copyright ownership or grant trademark
7
+ rights in the working name.
8
+
9
+ Third-party software retains its own copyright and license terms. The Python
10
+ dependency inventory is in pyproject.toml and uv.lock. The console and public site inventories are in their
11
+ package.json and package-lock.json files.
12
+ Retain applicable third-party notices when redistributing their artifacts;
13
+ this file is not a complete third-party license inventory or SBOM.
14
+
15
+ The console and static site include IBM Plex Sans, distributed through Google
16
+ Fonts under the SIL Open Font License 1.1. The font copyright and complete license
17
+ are retained in apps/console/public/fonts/OFL.txt and site/src/fonts/OFL.txt.
18
+ Source: https://github.com/google/fonts/tree/main/ofl/ibmplexsans.
19
+
20
+ The optional Timestral integration has separate code and model-weight terms:
21
+ - Source: mistralai/timestral, Apache-2.0, pinned in integrations/models.lock.json.
22
+ - Weights: mistralai/Timestral-28M and mistralai/Timestral-123M, Modified MIT,
23
+ separately pinned in that lock.
24
+ An owner-authorized local CPU parity run and benchmark are recorded separately;
25
+ each user/deployment must assess its own weight-license applicability. Model
26
+ weights are not licensed by the project's Apache-2.0 LICENSE.
27
+ See docs/implementation/timestral.md for the recorded restrictions and gate.
28
+
29
+ External benchmark datasets are separately attributed in benchmarks/manifest.yaml:
30
+ - UCI Online Retail II, DOI 10.24432/C5CG6D, recorded as CC-BY-4.0.
31
+ - UCI Individual Household Electric Power Consumption, DOI 10.24432/C58K54,
32
+ recorded as CC-BY-4.0.
33
+ - Wikimedia pageview aggregates, recorded as CC0-1.0, with source and access
34
+ policy URLs in the manifest.
35
+ Dataset source files, prepared observations, and any redistribution of them
36
+ remain subject to their own terms. Transformations and availability/timezone
37
+ assumptions are recorded in the manifest. Synthetic scenarios are labeled and
38
+ excluded from observed benchmark scores. The bundled minimal observations are
39
+ synthetic example data, not a redistribution of those external datasets.
@@ -0,0 +1 @@
1
+ """Forecast Anything: validated predictive infrastructure."""
@@ -0,0 +1 @@
1
+ """Domain modules behind the public version-one contract imports."""
@@ -0,0 +1,65 @@
1
+ """Shared validation, resource identities, and domain errors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from math import isfinite
6
+ from typing import Annotated, Any, Literal
7
+
8
+ from pydantic import AfterValidator, BaseModel, ConfigDict, StringConstraints
9
+
10
+ Identifier = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]
11
+
12
+
13
+ def _require_finite_nested(value: Any) -> Any:
14
+ """Validate opaque JSON-like data without changing its structure."""
15
+ if isinstance(value, float) and not isfinite(value):
16
+ raise ValueError("opaque dictionary numbers must be finite")
17
+ if isinstance(value, dict):
18
+ for item in value.values():
19
+ _require_finite_nested(item)
20
+ elif isinstance(value, (list, tuple, set, frozenset)):
21
+ for item in value:
22
+ _require_finite_nested(item)
23
+ return value
24
+
25
+
26
+ OpaqueDictionary = Annotated[dict[str, Any], AfterValidator(_require_finite_nested)]
27
+
28
+
29
+ class Contract(BaseModel):
30
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
31
+
32
+
33
+ class ResourceIdentity(Contract):
34
+ kind: Literal["run", "question", "report"]
35
+ resource_id: Identifier
36
+
37
+
38
+ class WorkspaceIdentity(Contract):
39
+ workspace_id: Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{32}$")]
40
+
41
+
42
+ class _ErrorPayload(Contract):
43
+ code: Identifier
44
+ details: OpaqueDictionary
45
+
46
+
47
+ class DomainError(Exception):
48
+ """Structured domain failure; serializable through its validated payload."""
49
+
50
+ def __init__(self, code: str, details: dict[str, Any]) -> None:
51
+ self._payload = _ErrorPayload(code=code, details=details)
52
+ self.code = self._payload.code
53
+ self.details = self._payload.details
54
+ super().__init__(self.code)
55
+
56
+ def model_dump(self, **kwargs: Any) -> dict[str, Any]:
57
+ return self._payload.model_dump(**kwargs)
58
+
59
+ def model_dump_json(self, **kwargs: Any) -> str:
60
+ return self._payload.model_dump_json(**kwargs)
61
+
62
+
63
+ class ErrorResponse(Contract):
64
+ code: Identifier
65
+ details: OpaqueDictionary
@@ -0,0 +1,311 @@
1
+ """Discovery candidates, qualification, watches, and evaluations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated, Literal
6
+
7
+ from pydantic import (
8
+ AfterValidator,
9
+ AwareDatetime,
10
+ ConfigDict,
11
+ Field,
12
+ computed_field,
13
+ model_validator,
14
+ )
15
+
16
+ from .common import Contract, Identifier, OpaqueDictionary
17
+ from .forecasts import GraphSpec
18
+ from .sources import SourceProfile
19
+
20
+
21
+ class DiscoveryBudget(Contract):
22
+ max_candidates: Annotated[int, Field(ge=0, strict=True)] = 10
23
+ max_tool_calls: Annotated[int, Field(ge=0, strict=True)] = 20
24
+
25
+
26
+ class VerificationProtocol(Contract):
27
+ """Frozen before final evaluation; no post-selection correction is assumed."""
28
+
29
+ criterion: Literal["mae", "brier"] = "mae"
30
+ target_node_id: Identifier = "question"
31
+ reference_node_id: Identifier = "reference"
32
+ selection_method: Literal["prespecified_holdout", "exploratory", "corrected"] = (
33
+ "prespecified_holdout"
34
+ )
35
+
36
+
37
+ class CandidateCostEstimate(Contract):
38
+ """Static execution work, not a latency or monetary quote.
39
+
40
+ Unknown/unsupported execution has no numeric value; zero is never a stand-in
41
+ for an unavailable estimate. The compiler owns the estimate and its basis.
42
+ """
43
+
44
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False, frozen=True)
45
+
46
+ status: Literal["known", "unavailable"] = "unavailable"
47
+ value: Annotated[int, Field(ge=0, strict=True)] | None = None
48
+ unit: Literal["provider_calls_per_run"] = "provider_calls_per_run"
49
+ basis: Identifier = "not_estimated"
50
+
51
+ @model_validator(mode="after")
52
+ def validate_availability(self) -> CandidateCostEstimate:
53
+ if (self.status == "known") != (self.value is not None):
54
+ raise ValueError(
55
+ "known cost requires a value; unavailable cost requires null"
56
+ )
57
+ return self
58
+
59
+
60
+ class Candidate(Contract):
61
+ candidate_id: Identifier
62
+ template_id: Identifier
63
+ source_ids: tuple[Identifier, ...]
64
+ graph: GraphSpec
65
+ reason: Identifier
66
+ protocol_id: Identifier
67
+ epoch_id: Identifier
68
+ protocol: VerificationProtocol = Field(default_factory=VerificationProtocol)
69
+ estimated_cost: CandidateCostEstimate = Field(default_factory=CandidateCostEstimate)
70
+ source_profiles: tuple[SourceProfile, ...] = ()
71
+ executable: bool = False
72
+ unresolved: tuple[str, ...] = ()
73
+
74
+
75
+ class DiscoveryEpoch(Contract):
76
+ epoch_id: Identifier
77
+ source_snapshot_ids: tuple[Identifier, ...]
78
+ explored_candidate_ids: tuple[Identifier, ...]
79
+ final_origin_ids: tuple[Identifier, ...]
80
+ final_candidate_id: Identifier | None = None
81
+ tuning_origin_ids: tuple[Identifier, ...] = ()
82
+
83
+ @model_validator(mode="after")
84
+ def validate_partitions(self) -> DiscoveryEpoch:
85
+ for values in (
86
+ self.source_snapshot_ids,
87
+ self.explored_candidate_ids,
88
+ self.final_origin_ids,
89
+ self.tuning_origin_ids,
90
+ ):
91
+ if len(set(values)) != len(values):
92
+ raise ValueError("discovery identities must be unique")
93
+ if set(self.final_origin_ids) & set(self.tuning_origin_ids):
94
+ raise ValueError("final origins cannot be used for tuning")
95
+ if self.final_candidate_id is not None and (
96
+ self.final_candidate_id not in self.explored_candidate_ids
97
+ ):
98
+ raise ValueError("final block owner must be a declared candidate")
99
+ return self
100
+
101
+
102
+ class EligibilityDecision(Contract):
103
+ action: Literal["activate", "provisional", "reject"]
104
+ reason_codes: tuple[Identifier, ...]
105
+ candidate_id: Identifier | None = None
106
+ protocol_id: Identifier | None = None
107
+ epoch_id: Identifier | None = None
108
+ evaluation_ids: tuple[Identifier, ...] = ()
109
+ backtest_id: Identifier | None = None
110
+ policy_version: Identifier = "discovery-v1"
111
+
112
+
113
+ class Watch(Contract):
114
+ """Current relevance state; Candidate and decision retain their issued lineage.
115
+
116
+ Evidence applicability is current metadata, independent of immutable scores.
117
+ A minimal watch can be displayed without lineage, but cannot be qualified.
118
+ """
119
+
120
+ migration_reason: Identifier | None = Field(
121
+ default=None, exclude_if=lambda value: value is None
122
+ )
123
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False, frozen=True)
124
+
125
+ watch_id: Identifier
126
+ candidate_id: Identifier
127
+ lifecycle: Literal["candidate", "evaluating", "active", "paused", "unsupported"]
128
+ quality: Literal["provisional", "usable", "stale", "degraded"]
129
+ graph_id: Identifier
130
+ graph_version: int
131
+ policy_version: Identifier
132
+ next_due_at: AwareDatetime
133
+ requalification_due_at: AwareDatetime | None = Field(
134
+ default=None, exclude_if=lambda value: value is None
135
+ )
136
+ requalification_reason: Identifier | None = Field(
137
+ default=None, exclude_if=lambda value: value is None
138
+ )
139
+ requalification_new_origins: Annotated[int, Field(ge=0, strict=True)] = 0
140
+ qualification_snapshot_id: Identifier | None = Field(
141
+ default=None, exclude_if=lambda value: value is None
142
+ )
143
+ last_run_id: Identifier | None = Field(
144
+ default=None, exclude_if=lambda value: value is None
145
+ )
146
+ forecast_horizon_end: AwareDatetime | None = Field(
147
+ default=None, exclude_if=lambda value: value is None
148
+ )
149
+ quality_reason: Identifier | None = Field(
150
+ default=None, exclude_if=lambda value: value is None
151
+ )
152
+ muted: bool
153
+ priority: Annotated[int, Field(ge=0, le=5, strict=True)] = 3
154
+ candidate: Candidate | None = None
155
+ eligibility_decision: EligibilityDecision | None = None
156
+ source_snapshot_ids: tuple[Identifier, ...] = ()
157
+ evidence_applicable: bool = False
158
+ reevaluation_required: bool = True
159
+ invalidated_evaluation_ids: tuple[Identifier, ...] = ()
160
+ candidate_invalidated: bool = False
161
+ supersedes_watch_id: Identifier | None = None
162
+
163
+ @model_validator(mode="after")
164
+ def validate_lineage(self) -> Watch:
165
+ if self.supersedes_watch_id == self.watch_id:
166
+ raise ValueError("watch cannot supersede itself")
167
+ if self.candidate is not None and (
168
+ self.candidate_id != self.candidate.candidate_id
169
+ or (self.graph_id, self.graph_version)
170
+ != (self.candidate.graph.graph_id, self.candidate.graph.version)
171
+ ):
172
+ raise ValueError("watch candidate lineage mismatch")
173
+ if self.eligibility_decision is not None and (
174
+ self.eligibility_decision.candidate_id != self.candidate_id
175
+ or self.eligibility_decision.policy_version != self.policy_version
176
+ or self.candidate is None
177
+ or (
178
+ self.eligibility_decision.protocol_id,
179
+ self.eligibility_decision.epoch_id,
180
+ )
181
+ != (self.candidate.protocol_id, self.candidate.epoch_id)
182
+ ):
183
+ raise ValueError("watch decision lineage mismatch")
184
+ return self
185
+
186
+ @property
187
+ def operational(self) -> bool:
188
+ """Only current, qualified, unmuted watches may emit operational alerts."""
189
+ return (
190
+ self.lifecycle == "active"
191
+ and self.quality == "usable"
192
+ and not self.muted
193
+ and self.evidence_applicable
194
+ and not self.reevaluation_required
195
+ and not self.candidate_invalidated
196
+ and self.eligibility_decision is not None
197
+ and self.eligibility_decision.action == "activate"
198
+ )
199
+
200
+
201
+ class _ImmutableDict(dict):
202
+ def _deny(self, *args, **kwargs):
203
+ raise TypeError("evaluation metrics are immutable")
204
+
205
+ __setitem__ = __delitem__ = clear = pop = popitem = setdefault = update = (
206
+ __ior__
207
+ ) = _deny
208
+
209
+
210
+ def _immutable(value):
211
+ if isinstance(value, dict):
212
+ return _ImmutableDict({key: _immutable(item) for key, item in value.items()})
213
+ if isinstance(value, (list, tuple)):
214
+ return tuple(_immutable(item) for item in value)
215
+ return value
216
+
217
+
218
+ class EvaluationContext(Contract):
219
+ """Trusted evaluator attestation, never accepted as an agent proposal.
220
+
221
+ Origin IDs identify the frozen target window, independently of model/config.
222
+ The caller establishes temporal/semantic validity using Plan 02 evaluation.
223
+ Defaults fail closed when that verification has not been performed.
224
+ """
225
+
226
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False, frozen=True)
227
+
228
+ candidate_id: Identifier
229
+ protocol_id: Identifier
230
+ epoch_id: Identifier
231
+ origin_id: Identifier
232
+ partition: Literal["exploration", "selection", "final"]
233
+ source_snapshot_ids: tuple[Identifier, ...]
234
+ target_start: AwareDatetime
235
+ target_end: AwareDatetime
236
+ temporal_valid: bool = False
237
+ semantic_valid: bool = False
238
+
239
+ @model_validator(mode="after")
240
+ def validate_window(self) -> EvaluationContext:
241
+ if self.target_end < self.target_start:
242
+ raise ValueError("target window must be ordered")
243
+ return self
244
+
245
+
246
+ class EvaluationRecord(Contract):
247
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False, frozen=True)
248
+
249
+ evaluation_id: Identifier
250
+ run_id: Identifier
251
+ actuals_snapshot_id: Identifier
252
+ status: Literal["pending", "evaluated", "insufficient_evidence"]
253
+ metrics: Annotated[OpaqueDictionary, AfterValidator(_immutable)]
254
+ origin_count: Annotated[int, Field(ge=0, strict=True)]
255
+ assumptions: tuple[str, ...]
256
+ discovery: EvaluationContext | None = None
257
+
258
+
259
+ class CandidateRequest(Contract):
260
+ template_id: Identifier
261
+ source_ids: tuple[Identifier, ...]
262
+ reason: Identifier
263
+ selection_method: Literal["prespecified_holdout", "exploratory", "corrected"] = (
264
+ "prespecified_holdout"
265
+ )
266
+
267
+
268
+ class WatchRequest(Contract):
269
+ candidate_id: Identifier
270
+ next_due_at: AwareDatetime
271
+
272
+
273
+ class WatchPatch(Contract):
274
+ muted: Annotated[bool, Field(strict=True)] | None = None
275
+ priority: Annotated[int, Field(ge=0, le=5, strict=True)] | None = None
276
+
277
+ @model_validator(mode="after")
278
+ def require_control(self):
279
+ if not self.model_fields_set or any(
280
+ getattr(self, key) is None for key in self.model_fields_set
281
+ ):
282
+ raise ValueError("at least one non-null control is required")
283
+ return self
284
+
285
+
286
+ class WatchView(Watch):
287
+ @model_validator(mode="before")
288
+ @classmethod
289
+ def discard_derived_operational(cls, value):
290
+ if isinstance(value, dict) and "operational" in value:
291
+ value = dict(value)
292
+ value.pop("operational")
293
+ return value
294
+
295
+ @computed_field
296
+ @property
297
+ def operational(self) -> bool:
298
+ return super().operational
299
+
300
+
301
+ class WatchHistoryEntry(Contract):
302
+ sequence: Annotated[int, Field(ge=1, strict=True)]
303
+ event_id: Identifier
304
+ occurred_at: AwareDatetime
305
+ event: OpaqueDictionary
306
+ watch: WatchView
307
+
308
+
309
+ class WatchHistoryPage(Contract):
310
+ entries: tuple[WatchHistoryEntry, ...]
311
+ next_offset: Annotated[int, Field(ge=0, strict=True)] | None