anthromesh 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 (73) hide show
  1. anthromesh/__init__.py +3 -0
  2. anthromesh/adapters/__init__.py +18 -0
  3. anthromesh/adapters/base.py +218 -0
  4. anthromesh/adapters/cloud.py +151 -0
  5. anthromesh/adapters/factory.py +31 -0
  6. anthromesh/adapters/heuristic.py +113 -0
  7. anthromesh/adapters/local.py +91 -0
  8. anthromesh/benchmarks/__init__.py +3 -0
  9. anthromesh/benchmarks/datasets.py +207 -0
  10. anthromesh/benchmarks/empirical.py +176 -0
  11. anthromesh/benchmarks/panel_cohort.py +67 -0
  12. anthromesh/benchmarks/public_twin.py +414 -0
  13. anthromesh/benchmarks/public_validation.py +435 -0
  14. anthromesh/benchmarks/replay.py +174 -0
  15. anthromesh/benchmarks/runner.py +140 -0
  16. anthromesh/benchmarks/study.py +245 -0
  17. anthromesh/benchmarks/study_report.py +170 -0
  18. anthromesh/capture/__init__.py +1 -0
  19. anthromesh/capture/github_webhook.py +51 -0
  20. anthromesh/capture/graph.py +221 -0
  21. anthromesh/capture/workflows.py +70 -0
  22. anthromesh/cli.py +807 -0
  23. anthromesh/client.py +96 -0
  24. anthromesh/cohort/__init__.py +3 -0
  25. anthromesh/cohort/categorical_anchor.py +240 -0
  26. anthromesh/cohort/clustering.py +93 -0
  27. anthromesh/cohort/human_anchor.py +92 -0
  28. anthromesh/cohort/ingest.py +104 -0
  29. anthromesh/cohort/oracle.py +153 -0
  30. anthromesh/cohort/twin_priors.py +118 -0
  31. anthromesh/config.py +48 -0
  32. anthromesh/gate/__init__.py +15 -0
  33. anthromesh/gate/calibration.py +95 -0
  34. anthromesh/gate/conformal.py +73 -0
  35. anthromesh/gate/engine.py +293 -0
  36. anthromesh/gate/fast.py +62 -0
  37. anthromesh/gate/fit.py +56 -0
  38. anthromesh/judgment/__init__.py +1 -0
  39. anthromesh/judgment/elicitation.py +206 -0
  40. anthromesh/judgment/monitor.py +128 -0
  41. anthromesh/judgment/panel.py +389 -0
  42. anthromesh/judgment/settings.py +41 -0
  43. anthromesh/models/__init__.py +39 -0
  44. anthromesh/models/cohort.py +76 -0
  45. anthromesh/models/decision.py +81 -0
  46. anthromesh/models/escalation.py +70 -0
  47. anthromesh/models/policy.py +41 -0
  48. anthromesh/models/validity.py +17 -0
  49. anthromesh/protocols/__init__.py +4 -0
  50. anthromesh/protocols/a2a_server.py +414 -0
  51. anthromesh/protocols/capabilities.py +52 -0
  52. anthromesh/protocols/delegation.py +373 -0
  53. anthromesh/protocols/mcp_server.py +500 -0
  54. anthromesh/protocols/oauth.py +177 -0
  55. anthromesh/ros_gate.py +141 -0
  56. anthromesh/twin/__init__.py +3 -0
  57. anthromesh/twin/engine.py +116 -0
  58. anthromesh/twin/inbox.py +221 -0
  59. anthromesh/vault/__init__.py +5 -0
  60. anthromesh/vault/dense.py +171 -0
  61. anthromesh/vault/encryption.py +50 -0
  62. anthromesh/vault/policy_engine.py +123 -0
  63. anthromesh/vault/postgres.py +92 -0
  64. anthromesh/vault/privacy.py +264 -0
  65. anthromesh/vault/retrieval.py +135 -0
  66. anthromesh/vault/storage.py +937 -0
  67. anthromesh-0.2.0.dist-info/METADATA +493 -0
  68. anthromesh-0.2.0.dist-info/RECORD +73 -0
  69. anthromesh-0.2.0.dist-info/WHEEL +5 -0
  70. anthromesh-0.2.0.dist-info/entry_points.txt +2 -0
  71. anthromesh-0.2.0.dist-info/licenses/LICENSE +201 -0
  72. anthromesh-0.2.0.dist-info/licenses/NOTICE +2 -0
  73. anthromesh-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,140 @@
1
+ from __future__ import annotations
2
+
3
+ import tempfile
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from pydantic import BaseModel
8
+
9
+ from anthromesh.adapters.base import BaseModelAdapter
10
+ from anthromesh.adapters.heuristic import HeuristicAdapter
11
+ from anthromesh.cohort.oracle import ResearchCohortOracle
12
+ from anthromesh.gate.calibration import compute_ece, jensen_shannon_divergence
13
+ from anthromesh.models import CohortQuery, GateAction
14
+ from anthromesh.twin.engine import PersonalDecisionTwin
15
+ from anthromesh.vault.policy_engine import PolicyEngine
16
+ from anthromesh.vault.storage import BehavioralVault
17
+ from .datasets import build_cohort_benchmark_suite, build_twin_benchmark_suite
18
+
19
+
20
+ class BenchmarkReport(BaseModel):
21
+ twin_anthromesh: dict[str, Any]
22
+ twin_zero_shot_baseline: dict[str, Any]
23
+ cohort_anthromesh: dict[str, Any]
24
+ cohort_mode_collapsed_baseline: dict[str, Any]
25
+
26
+
27
+ class BenchmarkRunner:
28
+ """Reproducible evaluation harness comparing AnthroMesh against standard zero-shot persona baselines."""
29
+
30
+ def __init__(self, adapter: BaseModelAdapter | None = None) -> None:
31
+ self.adapter = adapter or HeuristicAdapter()
32
+
33
+ def run_all(self) -> BenchmarkReport:
34
+ with tempfile.TemporaryDirectory() as tmpdir:
35
+ db_path = str(Path(tmpdir) / "bench.db")
36
+ vault = BehavioralVault(db_path=db_path)
37
+ twin = PersonalDecisionTwin(
38
+ vault=vault,
39
+ policy_engine=PolicyEngine(),
40
+ adapter=self.adapter,
41
+ confidence_threshold=0.68,
42
+ min_evidence_count=2,
43
+ )
44
+ oracle = ResearchCohortOracle(vault=vault, adapter=self.adapter)
45
+
46
+ history, eval_cases = build_twin_benchmark_suite()
47
+ for dec in history:
48
+ twin.record_decision(dec)
49
+
50
+ am_confs: list[float] = []
51
+ am_correct: list[int] = []
52
+ am_escalate_tp = am_escalate_fp = am_escalate_fn = 0
53
+ am_in_dist_correct = am_in_dist_total = 0
54
+
55
+ base_confs: list[float] = []
56
+ base_correct: list[int] = []
57
+
58
+ for query, gt_action, should_escalate in eval_cases:
59
+ res = twin.query_decision(query)
60
+ escalated = res.action == GateAction.ESCALATE
61
+
62
+ if should_escalate and escalated:
63
+ am_escalate_tp += 1
64
+ elif not should_escalate and escalated:
65
+ am_escalate_fp += 1
66
+ elif should_escalate and not escalated:
67
+ am_escalate_fn += 1
68
+
69
+ if not should_escalate:
70
+ am_in_dist_total += 1
71
+ if res.chosen_action == gt_action:
72
+ am_in_dist_correct += 1
73
+
74
+ am_confs.append(res.confidence)
75
+ am_correct.append(1 if (res.chosen_action == gt_action and not escalated) else 0)
76
+
77
+ base_pred = query.candidate_options[0].option_id
78
+ base_confs.append(0.88)
79
+ base_correct.append(1 if base_pred == gt_action else 0)
80
+
81
+ esc_prec = am_escalate_tp / max(am_escalate_tp + am_escalate_fp, 1)
82
+ esc_rec = am_escalate_tp / max(am_escalate_tp + am_escalate_fn, 1)
83
+ esc_f1 = (2 * esc_prec * esc_rec) / max(esc_prec + esc_rec, 1e-9)
84
+
85
+ twin_am_metrics = {
86
+ "in_distribution_accuracy": round(am_in_dist_correct / max(am_in_dist_total, 1), 4),
87
+ "ood_escalation_precision": round(esc_prec, 4),
88
+ "ood_escalation_recall": round(esc_rec, 4),
89
+ "ood_escalation_f1": round(esc_f1, 4),
90
+ "expected_calibration_error": compute_ece(am_confs, am_correct),
91
+ }
92
+ twin_base_metrics = {
93
+ "in_distribution_accuracy": round(sum(base_correct[:2]) / 2.0, 4),
94
+ "ood_escalation_recall": 0.0,
95
+ "expected_calibration_error": compute_ece(base_confs, base_correct),
96
+ }
97
+
98
+ profile, options, stimulus, gt_dist = build_cohort_benchmark_suite()
99
+ oracle.register_cohort(profile)
100
+ sim = oracle.simulate(
101
+ CohortQuery(
102
+ cohort_id=profile.cohort_id,
103
+ stimulus=stimulus,
104
+ options=options,
105
+ sample_size=200,
106
+ preserve_long_tail=True,
107
+ random_seed=42,
108
+ )
109
+ )
110
+ am_jsd = jensen_shannon_divergence(sim.metrics.option_distribution, gt_dist)
111
+
112
+ collapsed_dist = {
113
+ "pilot_guarded": 0.92,
114
+ "adopt_now": 0.06,
115
+ "local_only": 0.02,
116
+ "reject_ai": 0.0,
117
+ }
118
+ base_jsd = jensen_shannon_divergence(collapsed_dist, gt_dist)
119
+
120
+ cohort_am_metrics = {
121
+ "jensen_shannon_divergence": am_jsd,
122
+ "normalized_entropy": sim.metrics.normalized_entropy,
123
+ "long_tail_representation_rate": sim.metrics.long_tail_representation_rate,
124
+ "distinct_options_selected": sim.metrics.distinct_options_selected,
125
+ "distribution": sim.metrics.option_distribution,
126
+ }
127
+ cohort_base_metrics = {
128
+ "jensen_shannon_divergence": base_jsd,
129
+ "normalized_entropy": 0.2286,
130
+ "long_tail_representation_rate": 0.02,
131
+ "distinct_options_selected": 3,
132
+ "distribution": collapsed_dist,
133
+ }
134
+
135
+ return BenchmarkReport(
136
+ twin_anthromesh=twin_am_metrics,
137
+ twin_zero_shot_baseline=twin_base_metrics,
138
+ cohort_anthromesh=cohort_am_metrics,
139
+ cohort_mode_collapsed_baseline=cohort_base_metrics,
140
+ )
@@ -0,0 +1,245 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import math
6
+ from collections import Counter, defaultdict
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from typing import Literal
10
+
11
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
12
+
13
+ from anthromesh.models import CandidateOption, DecisionLog, QueryContext, RiskTier
14
+
15
+
16
+ def canonical_hash(value: object) -> str:
17
+ return hashlib.sha256(json.dumps(
18
+ value, sort_keys=True, separators=(",", ":"), allow_nan=False,
19
+ ).encode("utf-8")).hexdigest()
20
+
21
+
22
+ class StudyPlan(BaseModel):
23
+ model_config = ConfigDict(extra="forbid", frozen=True)
24
+
25
+ study_id: str = Field(min_length=1)
26
+ purpose: Literal["pilot", "confirmatory"] = "pilot"
27
+ domains: tuple[str, ...] = Field(min_length=1)
28
+ backends: tuple[str, ...] = Field(min_length=1)
29
+ minimum_participants: int = Field(default=30, ge=1)
30
+ minimum_training_cases: int = Field(default=20, ge=2)
31
+ minimum_calibration_cases: int = Field(default=10, ge=1)
32
+ minimum_test_cases: int = Field(default=10, ge=1)
33
+ minimum_retests_per_domain: int = Field(default=5, ge=1)
34
+ calibration_fraction: float = Field(default=0.20, gt=0, lt=0.5)
35
+ test_fraction: float = Field(default=0.20, gt=0, lt=0.5)
36
+ alpha: float = Field(default=0.10, gt=0, lt=0.5)
37
+ accuracy_margin: float = Field(default=0.05, gt=0, lt=1)
38
+ self_consistency_gap: float = Field(default=0.10, ge=0, lt=1)
39
+ minimum_coverage: float = Field(default=0.60, gt=0, le=1)
40
+ minimum_retest_delay_hours: int = Field(default=24, ge=1)
41
+ bootstrap_draws: int = Field(default=2000, ge=500, le=10000)
42
+ seed: int = 42
43
+
44
+ @field_validator("domains", "backends")
45
+ @classmethod
46
+ def unique_values(cls, values: tuple[str, ...]) -> tuple[str, ...]:
47
+ if len(set(values)) != len(values) or any(not value.strip() for value in values):
48
+ raise ValueError("Study domains and backends must be distinct and nonempty.")
49
+ return values
50
+
51
+ def validate_design(self) -> None:
52
+ if self.purpose == "confirmatory" and (
53
+ self.minimum_participants < 30 or len(self.domains) < 2 or len(self.backends) < 3
54
+ ):
55
+ raise ValueError("A confirmatory run needs at least 30 participants, two domains, and three backends.")
56
+ if self.minimum_calibration_cases < math.ceil((1 - self.alpha) / self.alpha):
57
+ raise ValueError("The calibration minimum is too small for a finite conformal cutoff.")
58
+
59
+
60
+ class Registration(BaseModel):
61
+ model_config = ConfigDict(extra="forbid", frozen=True)
62
+ version: Literal[1] = 1
63
+ registered_at: datetime
64
+ plan: StudyPlan
65
+ plan_hash: str
66
+
67
+
68
+ def register_study(plan_path: Path, destination: Path) -> Registration:
69
+ plan = StudyPlan.model_validate_json(plan_path.read_text(encoding="utf-8"))
70
+ plan.validate_design()
71
+ registration = Registration(
72
+ registered_at=datetime.now(timezone.utc), plan=plan,
73
+ plan_hash=canonical_hash(plan.model_dump(mode="json")),
74
+ )
75
+ with destination.open("x", encoding="utf-8") as output:
76
+ output.write(registration.model_dump_json(indent=2) + "\n")
77
+ return registration
78
+
79
+
80
+ def load_registration(path: Path) -> Registration:
81
+ registration = Registration.model_validate_json(path.read_text(encoding="utf-8"))
82
+ registration.plan.validate_design()
83
+ if canonical_hash(registration.plan.model_dump(mode="json")) != registration.plan_hash:
84
+ raise ValueError("The registered plan has changed.")
85
+ if registration.registered_at.tzinfo is None:
86
+ raise ValueError("The registration timestamp must include a timezone.")
87
+ return registration
88
+
89
+
90
+ class ParticipantConsent(BaseModel):
91
+ model_config = ConfigDict(extra="forbid")
92
+ participant_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
93
+ study_id: str
94
+ consented_at: datetime
95
+ revoked_at: datetime | None = None
96
+ approved_backends: list[str]
97
+ persona: str = Field(default="", max_length=2000)
98
+
99
+ @field_validator("consented_at", "revoked_at")
100
+ @classmethod
101
+ def aware_time(cls, value: datetime | None) -> datetime | None:
102
+ if value is not None and value.tzinfo is None:
103
+ raise ValueError("Consent timestamps must include a timezone.")
104
+ return value
105
+
106
+
107
+ class StudyCase(BaseModel):
108
+ model_config = ConfigDict(extra="forbid")
109
+ case_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
110
+ participant_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
111
+ scenario_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
112
+ domain: str = Field(min_length=1)
113
+ context: str = Field(min_length=1, max_length=12000)
114
+ options: list[CandidateOption] = Field(min_length=2, max_length=20)
115
+ chosen_action: str
116
+ recorded_at: datetime
117
+ rationale: str = Field(default="", max_length=4000)
118
+ out_of_distribution: bool = False
119
+ risk_tier: RiskTier = RiskTier.LOW
120
+ retest_of: str | None = None
121
+
122
+ @field_validator("recorded_at")
123
+ @classmethod
124
+ def aware_time(cls, value: datetime) -> datetime:
125
+ if value.tzinfo is None:
126
+ raise ValueError("Case timestamps must include a timezone.")
127
+ return value
128
+
129
+ def option_ids(self) -> set[str]:
130
+ return {option.option_id for option in self.options}
131
+
132
+ def query(self) -> QueryContext:
133
+ return QueryContext(
134
+ query_id=f"{self.participant_id}:{self.case_id}", subject_id=self.participant_id,
135
+ caller_agent="study", domain=self.domain, context=self.context,
136
+ candidate_options=self.options, risk_tier=self.risk_tier,
137
+ )
138
+
139
+ def as_decision(self) -> DecisionLog:
140
+ return DecisionLog(
141
+ decision_id=f"{self.participant_id}:{self.case_id}", subject_id=self.participant_id,
142
+ domain=self.domain, context=self.context, created_at=self.recorded_at.isoformat(),
143
+ options_considered=self.options, chosen_action=self.chosen_action,
144
+ rationale=self.rationale, risk_tier=self.risk_tier,
145
+ )
146
+
147
+
148
+ class StudyDataset(BaseModel):
149
+ model_config = ConfigDict(extra="forbid")
150
+ source: Literal["synthetic", "consented"]
151
+ participants: list[ParticipantConsent] = Field(min_length=1)
152
+ cases: list[StudyCase] = Field(min_length=1)
153
+
154
+
155
+ class PreparedStudy(BaseModel):
156
+ train: list[StudyCase]
157
+ calibration: list[StudyCase]
158
+ test: list[StudyCase]
159
+ retests: list[tuple[StudyCase, StudyCase]]
160
+ participants: dict[str, ParticipantConsent]
161
+
162
+
163
+ def prepare_study(registration: Registration, dataset: StudyDataset) -> PreparedStudy:
164
+ plan = registration.plan
165
+ if dataset.source == "synthetic" and plan.purpose != "pilot":
166
+ raise ValueError("Synthetic data cannot satisfy a confirmatory study.")
167
+ participants = {item.participant_id: item for item in dataset.participants}
168
+ if len(participants) != len(dataset.participants) or len(participants) < plan.minimum_participants:
169
+ raise ValueError("Duplicate participants or insufficient consented participants.")
170
+ for record in participants.values():
171
+ if (record.study_id != plan.study_id or record.revoked_at is not None
172
+ or record.consented_at > datetime.now(timezone.utc)):
173
+ raise ValueError("Every participant must have current consent for this study.")
174
+ if not set(plan.backends).issubset(record.approved_backends):
175
+ raise ValueError("Participant consent must cover every registered backend.")
176
+
177
+ by_id = {}
178
+ primary: dict[tuple[str, str], list[StudyCase]] = defaultdict(list)
179
+ repeated: list[StudyCase] = []
180
+ for case in dataset.cases:
181
+ identifier = (case.participant_id, case.case_id)
182
+ consent = participants.get(case.participant_id)
183
+ if consent is None or case.domain not in plan.domains:
184
+ raise ValueError("A case is outside the registered participant or domain scope.")
185
+ if identifier in by_id or len(case.option_ids()) != len(case.options):
186
+ raise ValueError("Case and option identifiers must be unique.")
187
+ if case.chosen_action not in case.option_ids():
188
+ raise ValueError("A recorded choice does not match any candidate option.")
189
+ by_id[identifier] = case
190
+ if case.retest_of is None:
191
+ primary[(case.participant_id, case.domain)].append(case)
192
+ else:
193
+ repeated.append(case)
194
+
195
+ train, calibration, test = [], [], []
196
+ expected_groups = {(person, domain) for person in participants for domain in plan.domains}
197
+ if set(primary) != expected_groups:
198
+ raise ValueError("Every included participant must have primary cases in every registered domain.")
199
+ for group in sorted(primary):
200
+ cases = sorted(primary[group], key=lambda case: (case.recorded_at, case.case_id))
201
+ if len({case.scenario_id for case in cases}) != len(cases):
202
+ raise ValueError("Repeated scenarios must be explicitly marked as retests.")
203
+ ordinary = [case for case in cases if not case.out_of_distribution]
204
+ n_test = max(plan.minimum_test_cases, math.ceil(len(ordinary) * plan.test_fraction))
205
+ n_calibration = max(plan.minimum_calibration_cases, math.ceil(len(ordinary) * plan.calibration_fraction))
206
+ if len(ordinary) - n_test - n_calibration < plan.minimum_training_cases:
207
+ raise ValueError("Insufficient cases for the registered temporal split.")
208
+ split_train = ordinary[:-(n_test + n_calibration)]
209
+ split_calibration = ordinary[-(n_test + n_calibration):-n_test]
210
+ split_test = ordinary[-n_test:]
211
+ if (split_train[-1].recorded_at >= split_calibration[0].recorded_at
212
+ or split_calibration[-1].recorded_at >= split_test[0].recorded_at):
213
+ raise ValueError("Training, calibration, and evaluation must have disjoint timestamps.")
214
+ if any(case.recorded_at < split_test[0].recorded_at for case in cases if case.out_of_distribution):
215
+ raise ValueError("OOD cases must be collected in the held-out period.")
216
+ train.extend(split_train)
217
+ calibration.extend(split_calibration)
218
+ test.extend([*split_test, *(case for case in cases if case.out_of_distribution)])
219
+
220
+ if plan.purpose == "confirmatory" and any(
221
+ case.recorded_at <= max(registration.registered_at, participants[case.participant_id].consented_at)
222
+ for case in test
223
+ ):
224
+ raise ValueError("Confirmatory test responses must be collected after registration and consent.")
225
+ test_ids = {(case.participant_id, case.case_id) for case in test}
226
+ retests = []
227
+ seen_pairs = set()
228
+ for second in repeated:
229
+ source_key = (second.participant_id, second.retest_of)
230
+ first = by_id.get(source_key)
231
+ if (source_key not in test_ids or first is None or source_key in seen_pairs
232
+ or first.domain != second.domain or first.scenario_id != second.scenario_id
233
+ or first.context != second.context or first.option_ids() != second.option_ids()
234
+ or first.risk_tier != second.risk_tier
235
+ or {option.option_id: (option.label, option.description) for option in first.options}
236
+ != {option.option_id: (option.label, option.description) for option in second.options}
237
+ or (second.recorded_at - first.recorded_at).total_seconds() < plan.minimum_retest_delay_hours * 3600):
238
+ raise ValueError("Each retest must independently repeat one held-out case after the registered delay.")
239
+ seen_pairs.add(source_key)
240
+ retests.append((first, second))
241
+ counts = Counter((first.participant_id, first.domain) for first, _ in retests)
242
+ if any(counts[group] < plan.minimum_retests_per_domain for group in expected_groups):
243
+ raise ValueError("The dataset lacks the preregistered retest count.")
244
+ return PreparedStudy(train=train, calibration=calibration, test=test,
245
+ retests=retests, participants=participants)
@@ -0,0 +1,170 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import random
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ from statistics import fmean
8
+
9
+ from anthromesh.gate.calibration import compute_ece
10
+
11
+ from .replay import SYSTEMS, Forecast, ForecastRun, load_dataset
12
+ from .study import Registration, StudyCase, canonical_hash, prepare_study
13
+
14
+
15
+ def _interval(values: list[float], *, draws: int, seed: int, tail: float) -> list[float] | None:
16
+ if len(values) < 2:
17
+ return None
18
+ sampler = random.Random(seed)
19
+ statistics = sorted(fmean(sampler.choices(values, k=len(values))) for _ in range(draws))
20
+ lower = int(tail * (draws - 1))
21
+ upper = int((1 - tail) * (draws - 1))
22
+ return [statistics[lower], statistics[upper]]
23
+
24
+
25
+ def _ratio(count: int, total: int) -> float | None:
26
+ return count / total if total else None
27
+
28
+
29
+ def _check_forecasts(run: ForecastRun, cases: dict[tuple[str, str], StudyCase]):
30
+ seen = {}
31
+ for row in run.forecasts:
32
+ key = (row.participant_id, row.case_id)
33
+ case = cases.get(key)
34
+ if (case is None or row.system not in SYSTEMS or (key, row.system) in seen
35
+ or row.predicted_action not in case.option_ids() | {None}):
36
+ raise ValueError("Forecast records must be unique and use registered cases, systems and options.")
37
+ if row.system == "twin" and row.predicted_action is None and not row.escalated:
38
+ raise ValueError("The twin cannot approve an invalid prediction.")
39
+ if row.system != "twin" and row.escalated:
40
+ raise ValueError("Baseline forecasts are forced choices, independent of their matched selector.")
41
+ seen[key, row.system] = row
42
+ if len(seen) != len(cases) * len(SYSTEMS):
43
+ raise ValueError("Every backend must forecast every case using every registered system.")
44
+ return seen
45
+
46
+
47
+ def _score_backend(run: ForecastRun, prepared, plan, adjusted_tail: float) -> dict:
48
+ cases = {(case.participant_id, case.case_id): case for case in prepared.test}
49
+ rows = _check_forecasts(run, cases)
50
+ groups = defaultdict(list)
51
+ for key, case in cases.items():
52
+ groups[(case.participant_id, case.domain)].append(key)
53
+ correct = {(key, system): rows[key, system].predicted_action == case.chosen_action
54
+ for key, case in cases.items() for system in SYSTEMS}
55
+ invalid = {system: 0 for system in SYSTEMS}
56
+ forced = {system: [] for system in SYSTEMS}
57
+ for key in cases:
58
+ for system in SYSTEMS:
59
+ forced[system].append(correct[key, system])
60
+ invalid[system] += rows[key, system].predicted_action is None
61
+
62
+ acceptance = {}
63
+ comparisons = defaultdict(list)
64
+ selected_outcomes = {system: [] for system in SYSTEMS}
65
+ for (person, domain), keys in sorted(groups.items()):
66
+ accepted = [key for key in keys if not rows[key, "twin"].escalated]
67
+ acceptance[person, domain] = len(accepted) / len(keys)
68
+ k = len(accepted)
69
+ if not k:
70
+ continue
71
+ accuracy = fmean(correct[key, "twin"] for key in accepted)
72
+ selected_outcomes["twin"].extend(correct[key, "twin"] for key in accepted)
73
+ for system in SYSTEMS[1:]:
74
+ ranked = sorted(keys, key=lambda key: (
75
+ rows[key, system].predicted_action is None,
76
+ -rows[key, system].confidence,
77
+ canonical_hash([plan.seed, *key]),
78
+ ))
79
+ selected_outcomes[system].extend(correct[key, system] for key in ranked[:k])
80
+ comparisons[system, person].append(
81
+ accuracy - fmean(correct[key, system] for key in ranked[:k])
82
+ )
83
+
84
+ paired = {}
85
+ for system in SYSTEMS[1:]:
86
+ person_deltas = [fmean(values) for (name, _), values in sorted(comparisons.items())
87
+ if name == system]
88
+ limits = _interval(person_deltas, draws=plan.bootstrap_draws, seed=plan.seed, tail=adjusted_tail)
89
+ paired[system] = {
90
+ "participant_mean_accuracy_gain": fmean(person_deltas) if person_deltas else None,
91
+ "adjusted_interval": limits,
92
+ "participants": len(person_deltas),
93
+ "clears_registered_margin": (limits is not None and limits[0] >= plan.accuracy_margin
94
+ and len(person_deltas) == len(prepared.participants)),
95
+ }
96
+
97
+ retest_by_person = defaultdict(list)
98
+ human_agreements, twin_agreements = [], []
99
+ for first, repeated in prepared.retests:
100
+ human = first.chosen_action == repeated.chosen_action
101
+ twin = correct[(first.participant_id, first.case_id), "twin"]
102
+ human_agreements.append(human)
103
+ twin_agreements.append(twin)
104
+ retest_by_person[first.participant_id].append(int(human) - int(twin))
105
+ gap = [fmean(values) for _, values in sorted(retest_by_person.items())]
106
+ gap_interval = _interval(gap, draws=plan.bootstrap_draws, seed=plan.seed, tail=adjusted_tail)
107
+ consistent = bool(gap_interval and gap_interval[1] <= plan.self_consistency_gap)
108
+ coverage_by_domain = {domain: fmean(value for (_, group), value in acceptance.items() if group == domain)
109
+ for domain in plan.domains}
110
+ coverage_ok = all(value >= plan.minimum_coverage for value in coverage_by_domain.values())
111
+
112
+ holds = {key: rows[key, "twin"].escalated for key in cases}
113
+ tp = sum(holds[key] and case.out_of_distribution for key, case in cases.items())
114
+ fp = sum(holds[key] and not case.out_of_distribution for key, case in cases.items())
115
+ fn = sum(not holds[key] and case.out_of_distribution for key, case in cases.items())
116
+ return {
117
+ "backend": run.backend,
118
+ "forced_choice_accuracy": {system: fmean(values) for system, values in forced.items()},
119
+ "invalid_or_unavailable_predictions": invalid,
120
+ "selective_accuracy_at_matched_case_counts": {
121
+ system: fmean(values) if values else None for system, values in selected_outcomes.items()
122
+ },
123
+ "coverage_by_domain": coverage_by_domain,
124
+ "escalation_rate": fmean(holds.values()),
125
+ "ood_escalation_f1": _ratio(2 * tp, 2 * tp + fp + fn),
126
+ "ece_by_system": {
127
+ system: compute_ece([rows[key, system].confidence for key in cases], forced[system])
128
+ for system in SYSTEMS
129
+ },
130
+ "accuracy_gain_by_baseline": paired,
131
+ "self_consistency": {
132
+ "pairs": len(human_agreements), "human_retest_agreement": fmean(human_agreements),
133
+ "twin_agreement_on_same_first_cases": fmean(twin_agreements),
134
+ "human_minus_twin_adjusted_interval": gap_interval,
135
+ "clears_registered_gap": consistent,
136
+ },
137
+ "clears_numeric_gates": coverage_ok and consistent and all(
138
+ row["clears_registered_margin"] for row in paired.values()
139
+ ),
140
+ }
141
+
142
+
143
+ def evaluate_study(registration: Registration, dataset_path: Path, forecast_paths: list[Path]) -> dict:
144
+ plan = registration.plan
145
+ dataset, digest = load_dataset(dataset_path)
146
+ prepared = prepare_study(registration, dataset)
147
+ runs = {}
148
+ for path in forecast_paths:
149
+ run = ForecastRun.model_validate_json(path.read_text(encoding="utf-8"))
150
+ if run.plan_hash != registration.plan_hash or run.dataset_hash != digest or run.backend in runs:
151
+ raise ValueError("Forecast files must match the registered plan and exact data, once per backend.")
152
+ runs[run.backend] = run
153
+ if set(runs) != set(plan.backends):
154
+ raise ValueError("Reports require exactly the preregistered backends.")
155
+ tail = 0.05 / (2 * len(plan.backends) * len(SYSTEMS))
156
+ reports = [_score_backend(runs[name], prepared, plan, tail) for name in plan.backends]
157
+ return {
158
+ "study_id": plan.study_id,
159
+ "purpose": plan.purpose,
160
+ "dataset_source": dataset.source,
161
+ "plan_hash": registration.plan_hash,
162
+ "dataset_hash": digest,
163
+ "participants": len(prepared.participants),
164
+ "training_cases": len(prepared.train),
165
+ "calibration_cases": len(prepared.calibration),
166
+ "test_cases": len(prepared.test),
167
+ "backends": reports,
168
+ "fidelity_gate": ("pass" if all(row["clears_numeric_gates"] for row in reports) else "fail")
169
+ if plan.purpose == "confirmatory" and dataset.source == "consented" else "pilot_only",
170
+ }
@@ -0,0 +1 @@
1
+ """Opt-in importers for locally supplied workflow exports."""
@@ -0,0 +1,51 @@
1
+ import hmac
2
+ import json
3
+
4
+ from anthromesh.vault.storage import BehavioralVault
5
+
6
+ from .workflows import github_reviews
7
+
8
+
9
+ def create_github_capture_app(
10
+ vault: BehavioralVault, *, secret: str, subject: str, account: str, repositories: set[str],
11
+ ):
12
+ from fastapi import FastAPI, HTTPException
13
+ from starlette.concurrency import run_in_threadpool
14
+ from starlette.requests import Request
15
+ from starlette.responses import Response
16
+
17
+ if not secret or not subject or not account or not repositories:
18
+ raise ValueError("Configure a secret, subject, GitHub account, and repository allowlist.")
19
+ app = FastAPI(title="AnthroMesh GitHub capture", docs_url=None, redoc_url=None, openapi_url=None)
20
+ key = secret.encode("utf-8")
21
+ allowed = {item.casefold() for item in repositories}
22
+
23
+ async def capture(request: Request):
24
+ signatures = request.headers.getlist("x-hub-signature-256")
25
+ if len(signatures) != 1 or not signatures[0].isascii():
26
+ raise HTTPException(401, detail="Invalid delivery signature.")
27
+ chunks = bytearray()
28
+ async for chunk in request.stream():
29
+ if len(chunks) + len(chunk) > 2 * 1024 * 1024:
30
+ raise HTTPException(413, detail="Payload too large.")
31
+ chunks.extend(chunk)
32
+ expected = "sha256=" + hmac.digest(key, chunks, "sha256").hex()
33
+ if not hmac.compare_digest(expected, signatures[0]):
34
+ raise HTTPException(401, detail="Invalid delivery signature.")
35
+ if request.headers.get("x-github-event") != "pull_request_review":
36
+ return Response(status_code=204)
37
+
38
+ try:
39
+ payload = json.loads(chunks)
40
+ repository = payload["repository"]["full_name"]
41
+ if repository.casefold() not in allowed or payload["action"] != "submitted":
42
+ return Response(status_code=204)
43
+ decisions = github_reviews([payload], subject, account)
44
+ except (KeyError, TypeError, AttributeError, ValueError) as exc:
45
+ raise HTTPException(400, detail="Invalid review payload.") from exc
46
+
47
+ count = await run_in_threadpool(vault.import_captured_decisions, decisions)
48
+ return {"imported": count}
49
+
50
+ app.add_api_route("/webhooks/github", capture, methods=["POST"])
51
+ return app