flowharness-evaluation 0.1.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.
@@ -0,0 +1,202 @@
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
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,26 @@
1
+ Metadata-Version: 2.4
2
+ Name: flowharness-evaluation
3
+ Version: 0.1.0
4
+ Summary: Evaluation context (FLOWHARNESS_SPEC.md §6.6) — eval suites, golden-set corpus, signed eval runs, the gate service
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ Classifier: Programming Language :: Python :: 3.13
10
+ Requires-Dist: flowharness-core==0.1.0
11
+ Requires-Dist: sqlalchemy>=2.0
12
+ Requires-Dist: alembic>=1.13
13
+ Requires-Python: >=3.12
14
+ Project-URL: Homepage, https://github.com/flowharness-ai
15
+ Description-Content-Type: text/markdown
16
+
17
+ # flowharness-evaluation
18
+
19
+ Evaluation bounded context — owns eval suites, golden-set corpus, signed eval runs, gate policies, and the gate service (verdict + scoring logic). Provides the domain layer for evaluating AI surfaces against a committed test suite, applying gate policies, and producing signed evaluation reports.
20
+
21
+ This is an **internal library package** of the FlowHarness toolchain, published to PyPI as a transitive dependency of [`flowharness`](https://github.com/flowharness-ai) (the scan CLI) and [`flowharness-ci-runner`](https://github.com/flowharness-ai). Install those packages instead of depending on `flowharness-evaluation` directly.
22
+
23
+ > **Note:** this package currently installs a top-level module named `evaluation`. Prefer `uvx` (isolated environments) over `pip install` into a shared venv until the 0.2 module-namespace rename lands.
24
+
25
+ **License:** Apache-2.0
26
+ **Homepage:** https://github.com/flowharness-ai
@@ -0,0 +1,10 @@
1
+ # flowharness-evaluation
2
+
3
+ Evaluation bounded context — owns eval suites, golden-set corpus, signed eval runs, gate policies, and the gate service (verdict + scoring logic). Provides the domain layer for evaluating AI surfaces against a committed test suite, applying gate policies, and producing signed evaluation reports.
4
+
5
+ This is an **internal library package** of the FlowHarness toolchain, published to PyPI as a transitive dependency of [`flowharness`](https://github.com/flowharness-ai) (the scan CLI) and [`flowharness-ci-runner`](https://github.com/flowharness-ai). Install those packages instead of depending on `flowharness-evaluation` directly.
6
+
7
+ > **Note:** this package currently installs a top-level module named `evaluation`. Prefer `uvx` (isolated environments) over `pip install` into a shared venv until the 0.2 module-namespace rename lands.
8
+
9
+ **License:** Apache-2.0
10
+ **Homepage:** https://github.com/flowharness-ai
@@ -0,0 +1,41 @@
1
+ [project]
2
+ name = "flowharness-evaluation"
3
+ version = "0.1.0"
4
+ readme = "README.md"
5
+ description = "Evaluation context (FLOWHARNESS_SPEC.md §6.6) — eval suites, golden-set corpus, signed eval runs, the gate service"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Programming Language :: Python :: 3.12",
12
+ "Programming Language :: Python :: 3.13",
13
+ ]
14
+ dependencies = [
15
+ "flowharness-core==0.1.0",
16
+ "sqlalchemy>=2.0",
17
+ "alembic>=1.13",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/flowharness-ai"
22
+
23
+ [build-system]
24
+ requires = ["uv_build>=0.9.0,<0.10.0"]
25
+ build-backend = "uv_build"
26
+
27
+ [tool.uv.build-backend]
28
+ module-name = "evaluation"
29
+ source-exclude = [
30
+ "src/evaluation/api",
31
+ "src/evaluation/application",
32
+ "src/evaluation/infrastructure",
33
+ ]
34
+ wheel-exclude = [
35
+ "evaluation/api",
36
+ "evaluation/application",
37
+ "evaluation/infrastructure",
38
+ ]
39
+
40
+ [tool.uv.sources.flowharness-core]
41
+ workspace = true
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "flowharness-evaluation"
3
+ version = "0.1.0"
4
+ readme = "README.md"
5
+ description = "Evaluation context (FLOWHARNESS_SPEC.md §6.6) — eval suites, golden-set corpus, signed eval runs, the gate service"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Programming Language :: Python :: 3.12",
12
+ "Programming Language :: Python :: 3.13",
13
+ ]
14
+ # Internal deps pin ==0.1.0: the six OSS packages version in lockstep (release.yml builds
15
+ # them from one tag), and [tool.uv.sources] workspace=true overrides these locally.
16
+ dependencies = ["flowharness-core==0.1.0", "sqlalchemy>=2.0", "alembic>=1.13"]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/flowharness-ai"
20
+
21
+ [build-system]
22
+ requires = ["uv_build>=0.9.0,<0.10.0"]
23
+ build-backend = "uv_build"
24
+
25
+ [tool.uv.build-backend]
26
+ module-name = "evaluation"
27
+ # --- Pruned public surface (decision 2026-07-30: funnel-open / platform-closed) -------
28
+ # `flowharness-evaluation` is published only because `flowharness-ci` reads the public gate
29
+ # formats from it (domain.gate_policy / domain.report / domain.errors — verified as the whole
30
+ # of its closure). So the dists ship `evaluation/__init__.py` + `evaluation/domain/` + py.typed
31
+ # and nothing else: `application/` (service layer, UoW, staging), `infrastructure/`
32
+ # (SQLAlchemy tables, repositories, migrations) and `api/` are the platform's, not the OSS
33
+ # surface. `evaluation/migrations/` (the alembic revisions = the platform DB schema) already
34
+ # sits outside `src/` and uv_build never ships it — verified against the baseline build.
35
+ # Zero code change needed: `evaluation/__init__.py` imports nothing and
36
+ # `evaluation/domain/__init__.py` imports only from `evaluation.domain`.
37
+ # BOTH lists are required — see the note in platform/core/pyproject.toml.
38
+ # Enforced by tests/packaging/test_public_surface_manifest.py.
39
+ source-exclude = [
40
+ "src/evaluation/api",
41
+ "src/evaluation/application",
42
+ "src/evaluation/infrastructure",
43
+ ]
44
+ wheel-exclude = [
45
+ "evaluation/api",
46
+ "evaluation/application",
47
+ "evaluation/infrastructure",
48
+ ]
49
+
50
+ [tool.uv.sources]
51
+ flowharness-core = { workspace = true }
@@ -0,0 +1,7 @@
1
+ """Evaluation bounded context (FLOWHARNESS_SPEC.md §6.6).
2
+
3
+ Owns eval suites, golden-set corpus, signed eval runs, the gate service.
4
+
5
+ Near-empty four-layer package (domain / application / infrastructure / api) so
6
+ the import-linter dependency graph is real from day one (§8).
7
+ """
@@ -0,0 +1,9 @@
1
+ """Evaluation domain layer (FLOWHARNESS_SPEC.md §6.6).
2
+
3
+ Dataclass value objects, entities, and domain services. Imports stdlib + core
4
+ only — enforced by import-linter (dependency rule 4, §8).
5
+ """
6
+
7
+ from evaluation.domain.errors import EvaluationError
8
+
9
+ __all__ = ["EvaluationError"]
@@ -0,0 +1,25 @@
1
+ """Corpus implementations for Evaluation (FLOWHARNESS_SPEC §6.6, D9a-9).
2
+
3
+ `GoldenSet` is the p1 `core.Corpus`: a curated set of eval-case assets, plus a CONTENT-ADDRESSED
4
+ `corpus_ref` so "same corpus" comparisons are structural — two runs over the same case set share a
5
+ `corpus_ref`, which is what makes "a run binds an exact (candidate, cell, corpus)" enforceable. The
6
+ platform derives the ref from the suite at ingest, so a runner cannot forge which corpus it ran
7
+ against. `ReplayWindow` (the second `Corpus`, over real `GenerationTrace`s) lands in p3.
8
+ """
9
+
10
+ import hashlib
11
+ from dataclasses import dataclass
12
+
13
+ from core import canonical_json
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class GoldenSet:
18
+ case_asset_ids: tuple[str, ...]
19
+
20
+ def cases(self) -> tuple[str, ...]: # the core.Corpus port: the case specs to run against
21
+ return tuple(sorted(self.case_asset_ids))
22
+
23
+ def corpus_ref(self) -> str:
24
+ body = canonical_json(list(self.cases())).encode("utf-8")
25
+ return "goldenset:" + hashlib.sha256(body).hexdigest()
@@ -0,0 +1,11 @@
1
+ """Evaluation domain errors (FLOWHARNESS_SPEC.md §8.1, P&G ch.1).
2
+
3
+ The context owns a DomainError subclass so invariant failures carry a stable,
4
+ machine-readable code instead of leaking as bare ValueErrors across the boundary.
5
+ """
6
+
7
+ from core import DomainError
8
+
9
+
10
+ class EvaluationError(DomainError):
11
+ """Base of the evaluation context's domain-error hierarchy."""
@@ -0,0 +1,120 @@
1
+ """EvalRun aggregate root (FLOWHARNESS_SPEC §6.6).
2
+
3
+ A federated run an external CI runner uploads: it lands `RECEIVED`, then the ingestion UoW resolves
4
+ it to `VERIFIED` or `REJECTED` (HMAC + scope + idempotency) — synchronously, in one transaction. The
5
+ run binds an exact `(candidate, cell, corpus_ref)` so comparisons stay honest; `corpus_ref` is
6
+ platform-derived from the suite (a runner cannot forge it). A terminal run cannot transition again.
7
+ Subclasses `core.EventRecorder`; invariants raise `EvaluationError`. Insert-only (no `row_version`):
8
+ the row is written once in its final state.
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from enum import Enum
13
+
14
+ from core import CandidateRef, Cell, Event, EventRecorder
15
+ from evaluation.domain.errors import EvaluationError
16
+ from evaluation.domain.events import EvalRunRejected, EvalRunVerified
17
+ from evaluation.domain.report import EvalReport
18
+
19
+
20
+ class RunStatus(Enum):
21
+ RECEIVED = "received"
22
+ VERIFIED = "verified"
23
+ REJECTED = "rejected"
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class RunnerIdentity:
28
+ runner_ref: str # the AGENT token actor_id (e.g. "apitoken:…")
29
+ nonce: str # the runner-supplied nonce — the idempotency/replay axis
30
+
31
+ def __post_init__(self) -> None:
32
+ if not self.runner_ref or not self.nonce:
33
+ raise EvaluationError("runner_identity_incomplete")
34
+
35
+
36
+ @dataclass(slots=True)
37
+ class EvalRun(EventRecorder):
38
+ run_id: str
39
+ org_id: str
40
+ suite_id: str
41
+ candidate: CandidateRef
42
+ cell: Cell
43
+ corpus_ref: str
44
+ runner: RunnerIdentity
45
+ report: EvalReport
46
+ status: RunStatus = RunStatus.RECEIVED
47
+ rejection_reason: str | None = None
48
+ sequence_no: int = 0
49
+ # PR-P1.5 (§4.8.2): context-diff fields. Pure passthrough to the row/event (no domain rule),
50
+ # mirroring how corpus_ref/runner transit the aggregate. cch is journaled; changed_paths is
51
+ # row-only (K6). Both additive-defaulted so every existing constructor stays valid.
52
+ context_change_hash: str | None = None
53
+ changed_paths: tuple[str, ...] | None = None
54
+ _events: list[Event] = field(default_factory=list, init=False)
55
+
56
+ @classmethod
57
+ def receive(
58
+ cls,
59
+ *,
60
+ run_id: str,
61
+ org_id: str,
62
+ suite_id: str,
63
+ candidate: CandidateRef,
64
+ cell: Cell,
65
+ corpus_ref: str,
66
+ runner: RunnerIdentity,
67
+ report: EvalReport,
68
+ context_change_hash: str | None = None,
69
+ changed_paths: tuple[str, ...] | None = None,
70
+ ) -> "EvalRun":
71
+ return cls(
72
+ run_id=run_id,
73
+ org_id=org_id,
74
+ suite_id=suite_id,
75
+ candidate=candidate,
76
+ cell=cell,
77
+ corpus_ref=corpus_ref,
78
+ runner=runner,
79
+ report=report,
80
+ context_change_hash=context_change_hash,
81
+ changed_paths=changed_paths,
82
+ )
83
+
84
+ def _guard_received(self) -> None:
85
+ if self.status is not RunStatus.RECEIVED:
86
+ raise EvaluationError("eval_run_terminal")
87
+
88
+ def mark_verified(self) -> None:
89
+ self._guard_received()
90
+ self.status = RunStatus.VERIFIED
91
+ self._record(
92
+ EvalRunVerified(
93
+ org_id=self.org_id,
94
+ run_id=self.run_id,
95
+ suite_id=self.suite_id,
96
+ candidate_kind=self.candidate.kind.value,
97
+ candidate_ref=self.candidate.ref,
98
+ cell_harness=self.cell.harness,
99
+ cell_model=self.cell.model,
100
+ corpus_ref=self.corpus_ref,
101
+ report_hash=self.report.content_hash(),
102
+ pass_rate_bp=self.report.pass_rate_bp.value,
103
+ regressions_count=self.report.regressions_count,
104
+ new_passing_count=self.report.new_passing_count,
105
+ context_change_hash=self.context_change_hash, # None ⇒ omitted from payload (D5)
106
+ )
107
+ )
108
+
109
+ def mark_rejected(self, reason: str) -> None:
110
+ self._guard_received()
111
+ self.status = RunStatus.REJECTED
112
+ self.rejection_reason = reason
113
+ self._record(
114
+ EvalRunRejected(
115
+ org_id=self.org_id,
116
+ run_id=self.run_id,
117
+ suite_id=self.suite_id,
118
+ rejection_reason=reason,
119
+ )
120
+ )
@@ -0,0 +1,89 @@
1
+ """Evaluation domain events (FLOWHARNESS_SPEC §4.2, §6.6): past-tense facts the aggregates raise.
2
+
3
+ Lean, float-free payloads (ids + ints + bp-as-int + bool). `EvalSuiteCreated` carries the suite's
4
+ shape (counts + thresholds, not the case bodies). `EvalRunVerified`/`EvalRunRejected` (S4) carry the
5
+ run's identity + the report's `content_hash` + bp/counts — the gate's evidence, never raw secrets.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+
10
+ from core import Event
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class EvalSuiteCreated(Event):
15
+ org_id: str
16
+ suite_id: str
17
+ playbook_id: str
18
+ case_count: int
19
+ min_pass_rate_bp: int
20
+ max_regressions: int
21
+ vs_baseline: bool
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class EvalRunVerified(Event):
26
+ org_id: str
27
+ run_id: str
28
+ suite_id: str
29
+ candidate_kind: str
30
+ candidate_ref: str
31
+ cell_harness: str
32
+ cell_model: str
33
+ corpus_ref: str
34
+ report_hash: str # the EvalReport content_hash — re-verifiable evidence (never a raw body)
35
+ pass_rate_bp: int
36
+ regressions_count: int
37
+ new_passing_count: int
38
+ # PR-P1.5 (§4.8.2): additive optional cch. OMITTED from the journal payload when None (skip-None
39
+ # in journal_mapping._payload) → byte-identical entry_hash for runs that don't carry it (§9.3).
40
+ context_change_hash: str | None = None
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class EvalRunRejected(Event):
45
+ org_id: str
46
+ run_id: str
47
+ suite_id: str
48
+ rejection_reason: str
49
+
50
+
51
+ # Gate-decision facts (§6.6, D9b-6): one per outcome so consumers (Catalog/Rollout/Signals) can
52
+ # subscribe per-verdict. Evidence-only payload — `run_count` (how many verified runs the decision
53
+ # weighed), never any report body or secret. `gate_eval_id` is the minted aggregate the event hangs
54
+ # off (sequence_no 0, a fresh id → no collision with the per-aggregate/per-org journal chain).
55
+ @dataclass(frozen=True, slots=True)
56
+ class _GateEvent(Event):
57
+ org_id: str
58
+ gate_eval_id: str
59
+ candidate_kind: str
60
+ candidate_ref: str
61
+ verdict: str # the core.Verdict value, redundant-but-explicit per the distinct event type
62
+ run_count: int
63
+ policy_version: str
64
+
65
+
66
+ @dataclass(frozen=True, slots=True)
67
+ class GatePolicySet(Event):
68
+ org_id: str
69
+ scope: str
70
+ required_cells: tuple[tuple[str, str], ...] # (harness, model) pairs — full point-in-time audit
71
+ min_pass_rate_bp: int
72
+ max_regressions: int
73
+ human_judged: bool
74
+ version: str
75
+
76
+
77
+ @dataclass(frozen=True, slots=True)
78
+ class GatePassed(_GateEvent):
79
+ pass
80
+
81
+
82
+ @dataclass(frozen=True, slots=True)
83
+ class GateFailed(_GateEvent):
84
+ pass
85
+
86
+
87
+ @dataclass(frozen=True, slots=True)
88
+ class GateNeedsHuman(_GateEvent):
89
+ pass
@@ -0,0 +1,135 @@
1
+ """GatePolicy aggregate + the pure gate decision (FLOWHARNESS_SPEC §6.6, §4.2.7; PR9b D9b-1..D9b-4).
2
+
3
+ A per-org policy document interpreted by a generic engine (§4.2.7): it carries the gate's `scope`
4
+ (AGGREGATE vs PER_CELL) + thresholds, and `decide` turns verified-run evidence into a `Verdict` with
5
+ no I/O — so the whole gate logic is unit-testable here. The safe default (`human_judged=True`)
6
+ forces NEEDS_HUMAN until an org opts into automation (D9b-4); no evidence also defers to a human,
7
+ never a silent PASS/FAIL.
8
+
9
+ The decision only weighs a run's `pass_rate_bp` + `regressions_count`, declared here as the
10
+ structural `RunEvidence` contract so the domain needn't import the application read model
11
+ (`VerifiedRunRow` satisfies it) — the layering rule (domain imports stdlib + core only) holds.
12
+ """
13
+
14
+ from dataclasses import dataclass, field
15
+ from enum import Enum
16
+ from typing import Protocol
17
+
18
+ from core import BasisPoints, Cell, Event, EventRecorder, Verdict
19
+ from evaluation.domain.errors import EvaluationError
20
+ from evaluation.domain.events import GatePolicySet
21
+
22
+
23
+ class RunEvidence(Protocol):
24
+ """The minimal verified-run shape `decide` weighs — owned by the domain (the PR9a application
25
+ `VerifiedRunRow` satisfies it structurally, so the domain stays application-free)."""
26
+
27
+ # Read-only @property members (not variable annotations): the conforming
28
+ # VerifiedRunRow is a frozen, slotted dataclass, so its attributes are read-only
29
+ # — a settable Protocol variable member never matches them (mypy's
30
+ # settable-vs-read-only rule). Declaring these read-only makes VerifiedRunRow
31
+ # conform without any runtime change (a Protocol body is never executed).
32
+ @property
33
+ def pass_rate_bp(self) -> BasisPoints: ...
34
+ @property
35
+ def regressions_count(self) -> int: ...
36
+
37
+
38
+ class GateScope(Enum):
39
+ AGGREGATE = "aggregate" # judge ALL the candidate's verified runs (any cell)
40
+ PER_CELL = "per_cell" # every cell in required_cells must pass
41
+
42
+
43
+ def _runs_pass(runs: tuple[RunEvidence, ...], min_bp: BasisPoints, max_reg: int) -> bool:
44
+ # conservative: every verified run in the slot must individually clear BOTH thresholds
45
+ return all(
46
+ r.pass_rate_bp.value >= min_bp.value and r.regressions_count <= max_reg for r in runs
47
+ )
48
+
49
+
50
+ @dataclass(slots=True)
51
+ class GatePolicy(EventRecorder):
52
+ org_id: str
53
+ scope: GateScope = GateScope.AGGREGATE
54
+ required_cells: tuple[Cell, ...] = ()
55
+ min_pass_rate_bp: BasisPoints = field(default_factory=lambda: BasisPoints(10_000))
56
+ max_regressions: int = 0
57
+ human_judged: bool = True # the default policy forces NEEDS_HUMAN (safe until configured)
58
+ version: str = "evaluation.gate.v1"
59
+ row_version: int = 0
60
+ sequence_no: int = 0
61
+ _events: list[Event] = field(default_factory=list, init=False)
62
+
63
+ def __post_init__(self) -> None:
64
+ self._validate(self.scope, self.required_cells, self.max_regressions)
65
+
66
+ @staticmethod
67
+ def _validate(scope: GateScope, required_cells: tuple[Cell, ...], max_regressions: int) -> None:
68
+ if max_regressions < 0:
69
+ raise EvaluationError("gate_policy_max_regressions_negative")
70
+ if scope is GateScope.PER_CELL and not required_cells:
71
+ raise EvaluationError("gate_policy_per_cell_no_cells")
72
+
73
+ def configure(
74
+ self,
75
+ *,
76
+ scope: GateScope,
77
+ required_cells: tuple[Cell, ...],
78
+ min_pass_rate_bp: BasisPoints,
79
+ max_regressions: int,
80
+ human_judged: bool,
81
+ ) -> None:
82
+ """Reconfigure the org's policy and record `GatePolicySet`. Validates the new config BEFORE
83
+ mutating, so a rejected reconfigure leaves the AR unchanged (fail-atomic). Mutation goes
84
+ through this method (which records the event, bumping `sequence_no`) so a reconfigure is
85
+ never silently lost — the persistence layer dirty-tracks on the recorded write."""
86
+ self._validate(scope, required_cells, max_regressions) # before mutating → fail-atomic
87
+ self.scope = scope
88
+ self.required_cells = required_cells
89
+ self.min_pass_rate_bp = min_pass_rate_bp
90
+ self.max_regressions = max_regressions
91
+ self.human_judged = human_judged
92
+ self._record(
93
+ GatePolicySet(
94
+ org_id=self.org_id,
95
+ scope=scope.value,
96
+ # full cell identities (not a count): the policy is a REPEATED mutation, so the
97
+ # journal records which cells each reconfigure required (point-in-time audit)
98
+ required_cells=tuple((c.harness, c.model) for c in required_cells),
99
+ min_pass_rate_bp=min_pass_rate_bp.value,
100
+ max_regressions=max_regressions,
101
+ human_judged=human_judged,
102
+ version=self.version,
103
+ )
104
+ )
105
+
106
+ def decide(self, runs_by_cell: dict[Cell | None, tuple[RunEvidence, ...]]) -> Verdict:
107
+ """runs_by_cell: for AGGREGATE, one entry keyed None = all the candidate's runs; for
108
+ PER_CELL, one entry per required Cell (missing/empty = no evidence for that cell)."""
109
+ if self.human_judged:
110
+ return Verdict.NEEDS_HUMAN
111
+ if self.scope is GateScope.AGGREGATE:
112
+ runs = runs_by_cell.get(None, ())
113
+ if not runs:
114
+ return Verdict.NEEDS_HUMAN # no evidence → defer to a human
115
+ return (
116
+ Verdict.PASS
117
+ if _runs_pass(runs, self.min_pass_rate_bp, self.max_regressions)
118
+ else Verdict.FAIL
119
+ )
120
+ # PER_CELL — only the required cells matter (evidence keyed under any other cell is
121
+ # ignored, so an unrelated cell can never sink the gate). Precedence is by `required_cells`
122
+ # order: the first required cell that is missing → NEEDS_HUMAN, else the first that fails →
123
+ # FAIL. Both branches are conservative (no silent auto-PASS) and deterministic (ordered).
124
+ for cell in self.required_cells:
125
+ runs = runs_by_cell.get(cell, ())
126
+ if not runs:
127
+ return Verdict.NEEDS_HUMAN # a required cell has no evidence → defer
128
+ if not _runs_pass(runs, self.min_pass_rate_bp, self.max_regressions):
129
+ return Verdict.FAIL
130
+ return Verdict.PASS
131
+
132
+
133
+ def DEFAULT_GATE_POLICY(org_id: str) -> GatePolicy:
134
+ """The safe baseline used until an org configures one: `human_judged=True` → NEEDS_HUMAN."""
135
+ return GatePolicy(org_id=org_id)
@@ -0,0 +1,52 @@
1
+ """EvalReport — the immutable, content-addressed result a runner uploads (FLOWHARNESS_SPEC §6.6).
2
+
3
+ Float-free by construction: the pass rate is integer `BasisPoints`, the counts are ints — so the
4
+ report's `content_hash` is deterministic + byte-portable (the canonical guard rejects any float),
5
+ which makes the stored evidence re-verifiable. `CaseResult.outcome` is golden-mode `passed|failed`;
6
+ replay's `improved|unchanged|regressed` arrives in p3.
7
+ """
8
+
9
+ from dataclasses import dataclass
10
+ from enum import Enum
11
+
12
+ from core import BasisPoints, ContentHashable
13
+ from evaluation.domain.errors import EvaluationError
14
+
15
+
16
+ class Outcome(Enum):
17
+ PASSED = "passed"
18
+ FAILED = "failed"
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class CaseResult:
23
+ case_ref: str
24
+ outcome: Outcome
25
+ diff_ref: str | None
26
+
27
+ def __post_init__(self) -> None:
28
+ if not self.case_ref:
29
+ raise EvaluationError("eval_case_ref_blank")
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class EvalReport(ContentHashable):
34
+ per_case: tuple[CaseResult, ...]
35
+ pass_rate_bp: BasisPoints
36
+ regressions_count: int
37
+ new_passing_count: int
38
+
39
+ def __post_init__(self) -> None:
40
+ if self.regressions_count < 0 or self.new_passing_count < 0:
41
+ raise EvaluationError("eval_report_count_negative")
42
+
43
+ def _hash_payload(self) -> object:
44
+ return {
45
+ "pass_rate_bp": self.pass_rate_bp.value,
46
+ "regressions_count": self.regressions_count,
47
+ "new_passing_count": self.new_passing_count,
48
+ "per_case": [
49
+ {"case_ref": c.case_ref, "outcome": c.outcome.value, "diff_ref": c.diff_ref}
50
+ for c in self.per_case
51
+ ],
52
+ }
@@ -0,0 +1,20 @@
1
+ """HMAC-SHA256 over the canonical report bytes, keyed by the runner's raw bearer token (D9a-2).
2
+
3
+ Pure + stdlib only. The platform recomputes the tag with the raw token it already receives to
4
+ authenticate the request, so there is no separate signing-key store; the raw key never leaves the
5
+ edge boundary. Comparison is constant-time. A malformed/empty signature simply fails to verify.
6
+ """
7
+
8
+ from core import canonical_json
9
+
10
+ # sign_report/verify_signature were lifted to core.signing (D3); re-exported here with zero behavior
11
+ # change so every existing evaluation.domain.signing importer keeps working.
12
+ from core.signing import sign_report, verify_signature
13
+ from evaluation.domain.report import EvalReport
14
+
15
+ __all__ = ["canonical_report_bytes", "sign_report", "verify_signature"]
16
+
17
+
18
+ def canonical_report_bytes(report: EvalReport) -> bytes:
19
+ # the exact bytes the runner signs: the canonical JSON of the report's hash projection
20
+ return canonical_json(report._hash_payload()).encode("utf-8")
@@ -0,0 +1,83 @@
1
+ """EvalSuite aggregate root (FLOWHARNESS_SPEC §6.6).
2
+
3
+ A suite binds a playbook's curated eval-case assets to its publish thresholds. `Thresholds` is
4
+ float-free (integer `BasisPoints` + ints + a bool). Subclasses `core.EventRecorder`; invariants
5
+ raise `EvaluationError`. Authoring suites may start with no cases; suite mutation (add/retire cases,
6
+ rebaseline) lands when composition screens do.
7
+ """
8
+
9
+ from dataclasses import dataclass, field
10
+
11
+ from core import BasisPoints, Event, EventRecorder
12
+ from evaluation.domain.errors import EvaluationError
13
+ from evaluation.domain.events import EvalSuiteCreated
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class Thresholds:
18
+ min_pass_rate_bp: BasisPoints
19
+ max_regressions: int
20
+ vs_baseline: bool
21
+
22
+ def __post_init__(self) -> None:
23
+ if self.min_pass_rate_bp.value > 10_000:
24
+ raise EvaluationError("basis_points_out_of_range")
25
+ if self.max_regressions < 0:
26
+ raise EvaluationError("eval_threshold_negative")
27
+
28
+
29
+ @dataclass(slots=True)
30
+ class EvalSuite(EventRecorder):
31
+ suite_id: str
32
+ org_id: str
33
+ playbook_id: str
34
+ case_asset_ids: tuple[str, ...]
35
+ thresholds: Thresholds
36
+ baseline_run: str | None = None
37
+ name: str | None = None
38
+ slug: str | None = None
39
+ description: str | None = None
40
+ tags: tuple[str, ...] = ()
41
+ row_version: int = 0
42
+ sequence_no: int = 0
43
+ _events: list[Event] = field(default_factory=list, init=False)
44
+
45
+ @classmethod
46
+ def create(
47
+ cls,
48
+ *,
49
+ suite_id: str,
50
+ org_id: str,
51
+ playbook_id: str,
52
+ case_asset_ids: tuple[str, ...],
53
+ thresholds: Thresholds,
54
+ baseline_run: str | None = None,
55
+ name: str | None = None,
56
+ slug: str | None = None,
57
+ description: str | None = None,
58
+ tags: tuple[str, ...] = (),
59
+ ) -> "EvalSuite":
60
+ suite = cls(
61
+ suite_id=suite_id,
62
+ org_id=org_id,
63
+ playbook_id=playbook_id,
64
+ case_asset_ids=case_asset_ids,
65
+ thresholds=thresholds,
66
+ baseline_run=baseline_run,
67
+ name=name,
68
+ slug=slug,
69
+ description=description,
70
+ tags=tags,
71
+ )
72
+ suite._record(
73
+ EvalSuiteCreated(
74
+ org_id=org_id,
75
+ suite_id=suite_id,
76
+ playbook_id=playbook_id,
77
+ case_count=len(case_asset_ids),
78
+ min_pass_rate_bp=thresholds.min_pass_rate_bp.value,
79
+ max_regressions=thresholds.max_regressions,
80
+ vs_baseline=thresholds.vs_baseline,
81
+ )
82
+ )
83
+ return suite
File without changes