benchside 0.4.1__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.
- benchside/__init__.py +1 -0
- benchside/_content/app/SKILL.md +155 -0
- benchside/_content/app/references/app-api.md +261 -0
- benchside/_content/app/references/generic-agents.md +69 -0
- benchside/_content/app/references/metascience.md +346 -0
- benchside/_content/app/references/native-memory.md +429 -0
- benchside/_content/app/references/onboarding.md +313 -0
- benchside/_content/app/references/sharing.md +159 -0
- benchside/_content/app/scripts/benchside_app.py +311 -0
- benchside/_content/app-requirements.txt +197 -0
- benchside/_content/claude/bench-init/SKILL.md +37 -0
- benchside/_content/claude/bench-share/SKILL.md +44 -0
- benchside/_content/fixtures/.gitkeep +0 -0
- benchside/_content/legacy-skill-digests.json +26 -0
- benchside/_content/personas/journal-club.yaml +45 -0
- benchside/_content/personas/methods-clinic.yaml +49 -0
- benchside/_content/personas/peer-review.yaml +45 -0
- benchside/_content/personas/pi-hypothesis.yaml +121 -0
- benchside/_content/personas/pi.yaml +87 -0
- benchside/_content/personas/repro-check.yaml +45 -0
- benchside/_content/personas/results-meeting.yaml +46 -0
- benchside/_content/personas/study-design.yaml +50 -0
- benchside/_content/templates/app-role.md.tmpl +31 -0
- benchside/_content/templates/blocks/capture-contract.md +40 -0
- benchside/_content/templates/blocks/sovereignty.md +36 -0
- benchside/_content/templates/skill.md.tmpl +54 -0
- benchside/application/__init__.py +0 -0
- benchside/application/app.py +458 -0
- benchside/application/bridge.py +55 -0
- benchside/application/contributions.py +39 -0
- benchside/application/di.py +35 -0
- benchside/application/metascience.py +671 -0
- benchside/application/native.py +1088 -0
- benchside/application/packaging.py +19 -0
- benchside/application/sharing.py +439 -0
- benchside/application/submission_failures.py +28 -0
- benchside/cli/__init__.py +0 -0
- benchside/cli/hooks.py +159 -0
- benchside/cli/install.py +276 -0
- benchside/cli/journal.py +232 -0
- benchside/cli/main.py +761 -0
- benchside/cli/runtime.py +245 -0
- benchside/cli/sharing.py +66 -0
- benchside/cli/ui/__init__.py +5 -0
- benchside/cli/ui/_glyphs.py +21 -0
- benchside/cli/ui/_model.py +66 -0
- benchside/cli/ui/_renderer.py +110 -0
- benchside/cli/ui/_rich.py +75 -0
- benchside/config.py +122 -0
- benchside/domain/__init__.py +0 -0
- benchside/domain/authoring/__init__.py +0 -0
- benchside/domain/authoring/command/__init__.py +0 -0
- benchside/domain/authoring/command/compile.py +28 -0
- benchside/domain/authoring/model/__init__.py +0 -0
- benchside/domain/authoring/model/flow.py +27 -0
- benchside/domain/authoring/model/persona.py +56 -0
- benchside/domain/authoring/model/skill.py +32 -0
- benchside/domain/authoring/model/value.py +42 -0
- benchside/domain/authoring/port/__init__.py +5 -0
- benchside/domain/authoring/port/renderer.py +17 -0
- benchside/domain/authoring/port/repository.py +28 -0
- benchside/domain/authoring/port/skill_writer.py +19 -0
- benchside/domain/authoring/query/__init__.py +0 -0
- benchside/domain/authoring/query/get_persona.py +30 -0
- benchside/domain/authoring/query/list_personas.py +21 -0
- benchside/domain/authoring/service/__init__.py +0 -0
- benchside/domain/authoring/service/authoring.py +99 -0
- benchside/domain/authoring/util/__init__.py +0 -0
- benchside/domain/authoring/util/di/__init__.py +3 -0
- benchside/domain/authoring/util/di/provider.py +15 -0
- benchside/domain/consultation/__init__.py +0 -0
- benchside/domain/consultation/command/__init__.py +0 -0
- benchside/domain/consultation/command/capture_gap.py +28 -0
- benchside/domain/consultation/command/close.py +29 -0
- benchside/domain/consultation/command/open.py +36 -0
- benchside/domain/consultation/command/raise_critique.py +30 -0
- benchside/domain/consultation/command/record_decision.py +30 -0
- benchside/domain/consultation/command/resolve_critique.py +32 -0
- benchside/domain/consultation/command/state_hypothesis.py +28 -0
- benchside/domain/consultation/event/__init__.py +22 -0
- benchside/domain/consultation/event/closed.py +13 -0
- benchside/domain/consultation/event/critique_raised.py +12 -0
- benchside/domain/consultation/event/critique_resolved.py +12 -0
- benchside/domain/consultation/event/decision_recorded.py +13 -0
- benchside/domain/consultation/event/gap_observed.py +16 -0
- benchside/domain/consultation/event/hypothesis_stated.py +12 -0
- benchside/domain/consultation/event/opened.py +23 -0
- benchside/domain/consultation/event/question.py +16 -0
- benchside/domain/consultation/event/research_recorded.py +9 -0
- benchside/domain/consultation/model/__init__.py +0 -0
- benchside/domain/consultation/model/consultation.py +60 -0
- benchside/domain/consultation/model/project.py +78 -0
- benchside/domain/consultation/model/value.py +150 -0
- benchside/domain/consultation/port/__init__.py +6 -0
- benchside/domain/consultation/port/repository.py +32 -0
- benchside/domain/consultation/query/__init__.py +0 -0
- benchside/domain/consultation/query/get_consultation.py +28 -0
- benchside/domain/consultation/query/recall_project.py +97 -0
- benchside/domain/consultation/service/__init__.py +0 -0
- benchside/domain/consultation/service/consultation.py +373 -0
- benchside/domain/consultation/util/__init__.py +0 -0
- benchside/domain/consultation/util/di/__init__.py +3 -0
- benchside/domain/consultation/util/di/provider.py +33 -0
- benchside/domain/export/__init__.py +0 -0
- benchside/domain/export/command/__init__.py +0 -0
- benchside/domain/export/command/export_observations.py +31 -0
- benchside/domain/export/command/grant_consent.py +26 -0
- benchside/domain/export/command/revoke_consent.py +20 -0
- benchside/domain/export/event/__init__.py +19 -0
- benchside/domain/export/event/consent_granted.py +9 -0
- benchside/domain/export/event/consent_revoked.py +8 -0
- benchside/domain/export/event/observations_exported.py +12 -0
- benchside/domain/export/event/reporting.py +24 -0
- benchside/domain/export/model/__init__.py +0 -0
- benchside/domain/export/model/ledger.py +40 -0
- benchside/domain/export/model/metascience.py +418 -0
- benchside/domain/export/model/reporting.py +193 -0
- benchside/domain/export/model/value.py +79 -0
- benchside/domain/export/model/wire.py +104 -0
- benchside/domain/export/port/__init__.py +5 -0
- benchside/domain/export/port/redactor.py +27 -0
- benchside/domain/export/port/repository.py +25 -0
- benchside/domain/export/port/sink.py +19 -0
- benchside/domain/export/query/__init__.py +0 -0
- benchside/domain/export/query/consent_status.py +30 -0
- benchside/domain/export/query/preview_export.py +37 -0
- benchside/domain/export/service/__init__.py +0 -0
- benchside/domain/export/service/consent.py +53 -0
- benchside/domain/export/service/export.py +171 -0
- benchside/domain/export/service/reporting.py +281 -0
- benchside/domain/export/util/__init__.py +0 -0
- benchside/domain/export/util/di/__init__.py +3 -0
- benchside/domain/export/util/di/provider.py +22 -0
- benchside/domain/shared/__init__.py +0 -0
- benchside/domain/shared/command.py +44 -0
- benchside/domain/shared/error.py +51 -0
- benchside/domain/shared/event.py +46 -0
- benchside/domain/shared/model/__init__.py +31 -0
- benchside/domain/shared/model/aggregate.py +9 -0
- benchside/domain/shared/model/capture.py +33 -0
- benchside/domain/shared/model/entity.py +5 -0
- benchside/domain/shared/model/gap.py +89 -0
- benchside/domain/shared/model/ids.py +64 -0
- benchside/domain/shared/model/provenance.py +16 -0
- benchside/domain/shared/model/value.py +17 -0
- benchside/domain/shared/port/__init__.py +4 -0
- benchside/domain/shared/port/base.py +9 -0
- benchside/domain/shared/port/journal.py +36 -0
- benchside/domain/shared/query.py +42 -0
- benchside/domain/shared/service.py +31 -0
- benchside/infrastructure/__init__.py +9 -0
- benchside/infrastructure/content/__init__.py +0 -0
- benchside/infrastructure/content/loader.py +108 -0
- benchside/infrastructure/content/renderer.py +129 -0
- benchside/infrastructure/content/writer.py +26 -0
- benchside/infrastructure/files.py +43 -0
- benchside/infrastructure/http_sink.py +128 -0
- benchside/infrastructure/journal/__init__.py +0 -0
- benchside/infrastructure/journal/di.py +85 -0
- benchside/infrastructure/journal/projection.py +244 -0
- benchside/infrastructure/journal/registry.py +24 -0
- benchside/infrastructure/journal/store.py +134 -0
- benchside/infrastructure/placeholders.py +28 -0
- benchside/infrastructure/readable_records.py +211 -0
- benchside/infrastructure/readable_refresh.py +58 -0
- benchside/infrastructure/redaction.py +44 -0
- benchside/infrastructure/session_context.py +225 -0
- benchside/infrastructure/storage_layout.py +104 -0
- benchside/reporting.py +333 -0
- benchside/util/__init__.py +0 -0
- benchside/util/di/__init__.py +4 -0
- benchside/util/di/base.py +16 -0
- benchside/util/di/scope.py +18 -0
- benchside-0.4.1.dist-info/METADATA +97 -0
- benchside-0.4.1.dist-info/RECORD +178 -0
- benchside-0.4.1.dist-info/WHEEL +4 -0
- benchside-0.4.1.dist-info/entry_points.txt +2 -0
- benchside-0.4.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
"""Opt-in studies and selected-session observation; no ambient chat access.
|
|
2
|
+
|
|
3
|
+
Call under App's transaction lock. Host tools discover only explicitly selected
|
|
4
|
+
scopes, then analyse sampled sessions in the host. This module never reads logs.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import uuid
|
|
11
|
+
from datetime import UTC, date, datetime, timedelta
|
|
12
|
+
from http.client import HTTPException
|
|
13
|
+
from urllib.error import URLError
|
|
14
|
+
from urllib.request import Request
|
|
15
|
+
|
|
16
|
+
from benchside import __version__
|
|
17
|
+
from benchside.application.contributions import POLICY, contributor_id
|
|
18
|
+
from benchside.application.submission_failures import record_submission_failure
|
|
19
|
+
from benchside.domain.export.model.metascience import (
|
|
20
|
+
MANUAL_SAMPLING,
|
|
21
|
+
RANDOM_SAMPLING,
|
|
22
|
+
ActivityObservation,
|
|
23
|
+
Candidate,
|
|
24
|
+
Classification,
|
|
25
|
+
LinkedActivityPayload,
|
|
26
|
+
LinkedSurveyPayload,
|
|
27
|
+
MetaDraft,
|
|
28
|
+
MetaState,
|
|
29
|
+
Sample,
|
|
30
|
+
Scope,
|
|
31
|
+
SelectedProblem,
|
|
32
|
+
StudyCatalog,
|
|
33
|
+
StudyParticipation,
|
|
34
|
+
SurveyPayload,
|
|
35
|
+
TextAnswer,
|
|
36
|
+
canonical,
|
|
37
|
+
digest,
|
|
38
|
+
parse_activity,
|
|
39
|
+
parse_survey,
|
|
40
|
+
)
|
|
41
|
+
from benchside.domain.shared.error import ConsentRequiredError, InfrastructureError, ValidationError
|
|
42
|
+
from benchside.infrastructure.files import atomic_json
|
|
43
|
+
from benchside.infrastructure.http_sink import COLLECTOR, USER_AGENT, HttpExportSink
|
|
44
|
+
from benchside.infrastructure.redaction import TextRedactor
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _check_survey_text(payload):
|
|
48
|
+
"""Keep exact researcher wording; refuse flagged answers instead of rewriting."""
|
|
49
|
+
findings = {
|
|
50
|
+
f"{key}: {finding.category}"
|
|
51
|
+
for key, answer in payload.answers.items()
|
|
52
|
+
if isinstance(answer, TextAnswer)
|
|
53
|
+
for finding in TextRedactor().scan(answer.text)
|
|
54
|
+
if finding.tier == "HIGH"
|
|
55
|
+
}
|
|
56
|
+
if findings:
|
|
57
|
+
raise ValidationError(
|
|
58
|
+
"Edit the flagged survey answers before sending ("
|
|
59
|
+
+ "; ".join(sorted(findings))
|
|
60
|
+
+ "). Nothing was sent. Remove sensitive details; Benchside will not rewrite "
|
|
61
|
+
"your answers or send them unchanged.",
|
|
62
|
+
code="survey_answer_sensitive",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class StudyClient:
|
|
67
|
+
"""Fixed trusted endpoint, bounded JSON, no redirects or participant parameters."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, endpoint=None, *, allow_local=False, opener=None):
|
|
70
|
+
# Reuse the HTTPS and no-redirect boundary, never use a URL from a study.
|
|
71
|
+
self.transport = HttpExportSink(
|
|
72
|
+
endpoint or os.environ.get("BENCHSIDE_STUDIES_ENDPOINT", f"{COLLECTOR}/v1/studies"),
|
|
73
|
+
allow_local=allow_local,
|
|
74
|
+
opener=opener,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
def fetch(self):
|
|
78
|
+
try:
|
|
79
|
+
request = Request(
|
|
80
|
+
self.transport.destination,
|
|
81
|
+
headers={"Accept": "application/json", "User-Agent": USER_AGENT},
|
|
82
|
+
)
|
|
83
|
+
with self.transport._opener.open(request, timeout=10) as response:
|
|
84
|
+
raw = response.read(131073)
|
|
85
|
+
if response.status != 200 or len(raw) > 131072:
|
|
86
|
+
raise ValueError("Invalid catalog response")
|
|
87
|
+
return StudyCatalog.model_validate_json(raw)
|
|
88
|
+
except (URLError, OSError, ValueError, HTTPException) as err:
|
|
89
|
+
if hasattr(err, "close"):
|
|
90
|
+
err.close()
|
|
91
|
+
raise InfrastructureError(
|
|
92
|
+
"Study invitations are unavailable; continue research normally"
|
|
93
|
+
) from err
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class Metascience:
|
|
97
|
+
def __init__(self, paths, *, catalog=None, sinks=None, today=None):
|
|
98
|
+
self.paths = paths
|
|
99
|
+
self.path = paths.home / "metascience" / "state.json"
|
|
100
|
+
self.state = (
|
|
101
|
+
MetaState.model_validate_json(self.path.read_text())
|
|
102
|
+
if self.path.exists()
|
|
103
|
+
else MetaState(seed=uuid.uuid4().hex)
|
|
104
|
+
)
|
|
105
|
+
self.catalog = catalog
|
|
106
|
+
self.sinks = sinks
|
|
107
|
+
self.today = today or datetime.now(UTC).date()
|
|
108
|
+
|
|
109
|
+
def _save(self, **updates):
|
|
110
|
+
data = {**self.state.model_dump(), **updates}
|
|
111
|
+
state = MetaState.model_validate(data)
|
|
112
|
+
atomic_json(self.path, state.model_dump(mode="json"))
|
|
113
|
+
self.state = state
|
|
114
|
+
|
|
115
|
+
def _require(self, *choices):
|
|
116
|
+
if any(choice not in self.state.grants for choice in choices):
|
|
117
|
+
raise ConsentRequiredError(
|
|
118
|
+
"This optional metascience choice is off; nothing was shared"
|
|
119
|
+
)
|
|
120
|
+
if "analysis" in choices and self.state.analysis_policy != "selected-research-max20-1":
|
|
121
|
+
raise ConsentRequiredError(
|
|
122
|
+
"Explain and accept the updated analysis policy: up to 20 research conversations per completed week, selected randomly or by the researcher"
|
|
123
|
+
)
|
|
124
|
+
if "sharing" in choices and self.state.sharing_policy != POLICY:
|
|
125
|
+
raise ConsentRequiredError(
|
|
126
|
+
"Explain and accept pseudonymous sharing before linking activity contributions"
|
|
127
|
+
)
|
|
128
|
+
return {choice: self.state.grants[choice] for choice in choices}
|
|
129
|
+
|
|
130
|
+
def _sink(self, channel):
|
|
131
|
+
if self.sinks is not None:
|
|
132
|
+
return self.sinks[channel]
|
|
133
|
+
return HttpExportSink(
|
|
134
|
+
os.environ.get(f"BENCHSIDE_{channel.upper()}_ENDPOINT", f"{COLLECTOR}/v1/{channel}")
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
@staticmethod
|
|
138
|
+
def _retired(week, sample):
|
|
139
|
+
return sample.inventory_sha256 == digest(["benchside.retired-sample", week])
|
|
140
|
+
|
|
141
|
+
@staticmethod
|
|
142
|
+
def _retirement_message(week):
|
|
143
|
+
next_week = date.fromisoformat(week) + timedelta(days=7)
|
|
144
|
+
available = next_week + timedelta(days=7)
|
|
145
|
+
return (
|
|
146
|
+
f"The sample for {week} was retired after an analysis or source change. "
|
|
147
|
+
"It cannot be resumed or re-sampled. Select approved sources and sample "
|
|
148
|
+
f"a later completed UTC week, starting {next_week} (available from {available})."
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
def _sampling_week(self):
|
|
152
|
+
# Wait until Sunday has ended; an early-week run must not freeze a partial frame.
|
|
153
|
+
return self.today - timedelta(days=self.today.weekday() + 7)
|
|
154
|
+
|
|
155
|
+
def _sampling_window(self):
|
|
156
|
+
week = self._sampling_week()
|
|
157
|
+
return {
|
|
158
|
+
"week": week.isoformat(),
|
|
159
|
+
"starts_at": f"{week}T00:00:00Z",
|
|
160
|
+
"ends_before": f"{week + timedelta(days=7)}T00:00:00Z",
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
def _retire_samples(self, weeks):
|
|
164
|
+
"""Erase private selections; retain a marker so consent changes cannot redraw a week."""
|
|
165
|
+
keys = {f"activity:{week}" for week in weeks}
|
|
166
|
+
samples = dict(self.state.samples)
|
|
167
|
+
for week in weeks:
|
|
168
|
+
previous = samples[week]
|
|
169
|
+
samples[week] = Sample(
|
|
170
|
+
id=previous.id,
|
|
171
|
+
inventory_sha256=digest(["benchside.retired-sample", week]),
|
|
172
|
+
eligible=0,
|
|
173
|
+
sampling=previous.sampling,
|
|
174
|
+
selected={},
|
|
175
|
+
revision=previous.revision,
|
|
176
|
+
)
|
|
177
|
+
return {
|
|
178
|
+
"samples": samples,
|
|
179
|
+
"latest": {k: v for k, v in self.state.latest.items() if k not in keys},
|
|
180
|
+
"drafts": {
|
|
181
|
+
key: draft
|
|
182
|
+
for key, draft in self.state.drafts.items()
|
|
183
|
+
if draft.key not in keys or key in self.state.receipts
|
|
184
|
+
},
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
def _retained_drafts(self, drafts, latest):
|
|
188
|
+
keep = set(latest.values()) | set(self.state.receipts)
|
|
189
|
+
return {key: draft for key, draft in drafts.items() if key in keep}
|
|
190
|
+
|
|
191
|
+
def status(self):
|
|
192
|
+
return {
|
|
193
|
+
"choices": {
|
|
194
|
+
name: name in self.state.grants for name in ("invitations", "analysis", "sharing")
|
|
195
|
+
},
|
|
196
|
+
"scopes": [s.model_dump() for s in self.state.scopes],
|
|
197
|
+
"last_invitation": self.state.last_invitation,
|
|
198
|
+
"open_invitations": [
|
|
199
|
+
s.model_dump()
|
|
200
|
+
for key, s in self.state.studies.items()
|
|
201
|
+
if "invitations" in self.state.grants
|
|
202
|
+
and key not in self.state.completed
|
|
203
|
+
and s.active(self.today.isoformat())
|
|
204
|
+
],
|
|
205
|
+
"weeks": [
|
|
206
|
+
week
|
|
207
|
+
for week, sample in self.state.samples.items()
|
|
208
|
+
if not self._retired(week, sample)
|
|
209
|
+
],
|
|
210
|
+
"retired_weeks": [
|
|
211
|
+
week for week, sample in self.state.samples.items() if self._retired(week, sample)
|
|
212
|
+
],
|
|
213
|
+
"pending_drafts": [
|
|
214
|
+
d for d in self.state.latest.values() if d not in self.state.receipts
|
|
215
|
+
],
|
|
216
|
+
"limits": {"invitation_days": 7, "sessions_per_week": 20},
|
|
217
|
+
"sampling_window": self._sampling_window(),
|
|
218
|
+
"analysis_policy": self.state.analysis_policy,
|
|
219
|
+
"sharing_policy": self.state.sharing_policy,
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
def consent(self, choice, enabled):
|
|
223
|
+
if choice not in {"invitations", "analysis", "sharing"} or type(enabled) is not bool:
|
|
224
|
+
raise ValidationError("Choose invitations, analysis or sharing and true or false")
|
|
225
|
+
grants = dict(self.state.grants)
|
|
226
|
+
policy_changed = (
|
|
227
|
+
choice == "analysis" and self.state.analysis_policy != "selected-research-max20-1"
|
|
228
|
+
) or (choice == "sharing" and self.state.sharing_policy != POLICY)
|
|
229
|
+
if enabled:
|
|
230
|
+
if policy_changed or choice not in grants:
|
|
231
|
+
grants[choice] = uuid.uuid4().hex
|
|
232
|
+
else:
|
|
233
|
+
grants.pop(choice, None)
|
|
234
|
+
reset_scopes = choice == "analysis" and (not enabled or "analysis" not in self.state.grants)
|
|
235
|
+
retired = self._retire_samples(self.state.samples) if reset_scopes else {}
|
|
236
|
+
if reset_scopes:
|
|
237
|
+
# Survey participation is independent. Keep submitted activity payloads
|
|
238
|
+
# only as receipt evidence; they contain no source or session references.
|
|
239
|
+
retired["latest"] = {
|
|
240
|
+
k: v for k, v in retired["latest"].items() if not k.startswith("activity:")
|
|
241
|
+
}
|
|
242
|
+
retired["drafts"] = {
|
|
243
|
+
k: d
|
|
244
|
+
for k, d in retired["drafts"].items()
|
|
245
|
+
if d.channel != "activity" or k in self.state.receipts
|
|
246
|
+
}
|
|
247
|
+
self._save(
|
|
248
|
+
grants=grants,
|
|
249
|
+
scopes=[] if reset_scopes else self.state.scopes,
|
|
250
|
+
analysis_policy="selected-research-max20-1"
|
|
251
|
+
if choice == "analysis" and enabled
|
|
252
|
+
else self.state.analysis_policy,
|
|
253
|
+
sharing_policy=POLICY if choice == "sharing" and enabled else self.state.sharing_policy,
|
|
254
|
+
**retired,
|
|
255
|
+
)
|
|
256
|
+
return self.status()
|
|
257
|
+
|
|
258
|
+
def scopes(self, scopes):
|
|
259
|
+
self._require("analysis")
|
|
260
|
+
selected = [Scope.model_validate(s) for s in scopes]
|
|
261
|
+
if len({canonical(s.model_dump()) for s in selected}) != len(selected):
|
|
262
|
+
raise ValidationError("Select each source only once")
|
|
263
|
+
if selected != self.state.scopes:
|
|
264
|
+
# Changing scope invalidates every pending observation approval.
|
|
265
|
+
grants = {**self.state.grants, "analysis": uuid.uuid4().hex}
|
|
266
|
+
# Also retire a legacy current-week sample when upgrading mid-week.
|
|
267
|
+
recent_weeks = {
|
|
268
|
+
self._sampling_week().isoformat(),
|
|
269
|
+
(self._sampling_week() + timedelta(days=7)).isoformat(),
|
|
270
|
+
}
|
|
271
|
+
narrowed = any(scope not in selected for scope in self.state.scopes)
|
|
272
|
+
affected = [
|
|
273
|
+
week
|
|
274
|
+
for week, sample in self.state.samples.items()
|
|
275
|
+
if (narrowed and week in recent_weeks)
|
|
276
|
+
or any(c.scope not in selected for c in sample.selected.values())
|
|
277
|
+
]
|
|
278
|
+
self._save(scopes=selected, grants=grants, **self._retire_samples(affected))
|
|
279
|
+
return self.status()
|
|
280
|
+
|
|
281
|
+
def invitations(self):
|
|
282
|
+
self._require("invitations")
|
|
283
|
+
today = self.today.isoformat()
|
|
284
|
+
if (
|
|
285
|
+
self.state.last_invitation
|
|
286
|
+
and (self.today - date.fromisoformat(self.state.last_invitation)).days < 7
|
|
287
|
+
):
|
|
288
|
+
retry = date.fromisoformat(self.state.last_invitation) + timedelta(days=7)
|
|
289
|
+
return {"invitation": None, "reason": "weekly_limit", "retry_at": f"{retry}T00:00:00Z"}
|
|
290
|
+
if self.state.last_check == today:
|
|
291
|
+
retry = self.today + timedelta(days=1)
|
|
292
|
+
return {
|
|
293
|
+
"invitation": None,
|
|
294
|
+
"reason": "already_checked_today",
|
|
295
|
+
"retry_at": f"{retry}T00:00:00Z",
|
|
296
|
+
}
|
|
297
|
+
# Persist the cooldown even if the endpoint is unavailable.
|
|
298
|
+
self._save(last_check=today)
|
|
299
|
+
catalog = (self.catalog or StudyClient()).fetch()
|
|
300
|
+
for study in catalog.studies:
|
|
301
|
+
if study.key in self.state.studies and study != self.state.studies[study.key]:
|
|
302
|
+
raise ValidationError(
|
|
303
|
+
"Study changed without a version bump; do not invite or submit"
|
|
304
|
+
)
|
|
305
|
+
if (
|
|
306
|
+
study.active(today)
|
|
307
|
+
and study.id not in self.state.dismissed
|
|
308
|
+
and study.key not in self.state.completed
|
|
309
|
+
and study.key not in self.state.studies
|
|
310
|
+
):
|
|
311
|
+
self._save(studies={**self.state.studies, study.key: study}, last_invitation=today)
|
|
312
|
+
return {
|
|
313
|
+
"invitation": study.model_dump(),
|
|
314
|
+
"study_sha256": digest(study.model_dump()),
|
|
315
|
+
}
|
|
316
|
+
return {"invitation": None, "reason": "no_new_studies"}
|
|
317
|
+
|
|
318
|
+
def dismiss(self, study_key, *, permanently=False):
|
|
319
|
+
if type(permanently) is not bool or study_key not in self.state.studies:
|
|
320
|
+
raise ValidationError("Choose an existing invitation")
|
|
321
|
+
study = self.state.studies[study_key]
|
|
322
|
+
self._save(
|
|
323
|
+
completed=list(dict.fromkeys([*self.state.completed, study_key])),
|
|
324
|
+
dismissed=list(dict.fromkeys([*self.state.dismissed, study.id]))
|
|
325
|
+
if permanently
|
|
326
|
+
else self.state.dismissed,
|
|
327
|
+
)
|
|
328
|
+
return {"dismissed": study_key, "permanently": permanently}
|
|
329
|
+
|
|
330
|
+
def _preview(self, channel, key, payload, grants):
|
|
331
|
+
sink = self._sink(channel)
|
|
332
|
+
text = canonical(payload.model_dump(mode="json", by_alias=True))
|
|
333
|
+
current = self.state.drafts.get(self.state.latest.get(key))
|
|
334
|
+
if (
|
|
335
|
+
current
|
|
336
|
+
and current.payload == text
|
|
337
|
+
and current.grants == grants
|
|
338
|
+
and current.destination == sink.destination
|
|
339
|
+
):
|
|
340
|
+
retained = self._retained_drafts(self.state.drafts, self.state.latest)
|
|
341
|
+
if len(retained) != len(self.state.drafts):
|
|
342
|
+
self._save(drafts=retained)
|
|
343
|
+
return current.model_dump()
|
|
344
|
+
draft = MetaDraft(
|
|
345
|
+
id=uuid.uuid4().hex,
|
|
346
|
+
channel=channel,
|
|
347
|
+
key=key,
|
|
348
|
+
grants=grants,
|
|
349
|
+
payload=text,
|
|
350
|
+
sha256=hashlib.sha256(text.encode()).hexdigest(),
|
|
351
|
+
destination=sink.destination,
|
|
352
|
+
)
|
|
353
|
+
latest = {**self.state.latest, key: draft.id}
|
|
354
|
+
retained = self._retained_drafts({**self.state.drafts, draft.id: draft}, latest)
|
|
355
|
+
if len(retained) > 1000:
|
|
356
|
+
raise ValidationError(
|
|
357
|
+
"Metascience approval and receipt history is full; preserve the notebook "
|
|
358
|
+
"and arrange archival before creating another draft. Consent can still be withdrawn."
|
|
359
|
+
)
|
|
360
|
+
self._save(drafts=retained, latest=latest)
|
|
361
|
+
return draft.model_dump()
|
|
362
|
+
|
|
363
|
+
def survey(self, study_key, answers):
|
|
364
|
+
grants = self._require("invitations")
|
|
365
|
+
study = self.state.studies.get(study_key)
|
|
366
|
+
if (
|
|
367
|
+
not study
|
|
368
|
+
or not study.active(self.today.isoformat())
|
|
369
|
+
or study_key in self.state.completed
|
|
370
|
+
):
|
|
371
|
+
raise ValidationError("This survey is unavailable, dismissed or already answered")
|
|
372
|
+
key = f"survey:{study_key}"
|
|
373
|
+
previous = self.state.drafts.get(self.state.latest.get(key))
|
|
374
|
+
response_id = json.loads(previous.payload)["response_id"] if previous else uuid.uuid4().hex
|
|
375
|
+
accepted = self.state.participation.get(study_key)
|
|
376
|
+
payload_type = LinkedSurveyPayload if accepted else SurveyPayload
|
|
377
|
+
if accepted and (
|
|
378
|
+
accepted.invitation_grant != grants["invitations"]
|
|
379
|
+
or accepted.study_sha256 != digest(study.model_dump())
|
|
380
|
+
or accepted.destination != self._sink("surveys").destination
|
|
381
|
+
):
|
|
382
|
+
raise ConsentRequiredError(
|
|
383
|
+
"Survey participation changed; explain and accept the study again"
|
|
384
|
+
)
|
|
385
|
+
payload = payload_type(
|
|
386
|
+
benchside_version=__version__,
|
|
387
|
+
response_id=response_id,
|
|
388
|
+
study_id=study.id,
|
|
389
|
+
study_version=study.version,
|
|
390
|
+
study_sha256=digest(study.model_dump()),
|
|
391
|
+
answers=answers,
|
|
392
|
+
**({"contributor_id": accepted.contributor_id} if accepted else {}),
|
|
393
|
+
)
|
|
394
|
+
payload.check_study(study)
|
|
395
|
+
_check_survey_text(payload)
|
|
396
|
+
return self._preview("surveys", key, payload, grants)
|
|
397
|
+
|
|
398
|
+
def join_study(self, study_key, study_sha256):
|
|
399
|
+
"""Record agreement before answers; answering then authorises their submission."""
|
|
400
|
+
grants = self._require("invitations")
|
|
401
|
+
study = self.state.studies.get(study_key)
|
|
402
|
+
if (
|
|
403
|
+
not study
|
|
404
|
+
or not study.active(self.today.isoformat())
|
|
405
|
+
or study_key in self.state.completed
|
|
406
|
+
or study_sha256 != digest(study.model_dump())
|
|
407
|
+
):
|
|
408
|
+
raise ConsentRequiredError("Accept an available study and its exact current definition")
|
|
409
|
+
accepted = StudyParticipation(
|
|
410
|
+
study_sha256=study_sha256,
|
|
411
|
+
invitation_grant=grants["invitations"],
|
|
412
|
+
destination=self._sink("surveys").destination,
|
|
413
|
+
contributor_id=contributor_id(self.paths),
|
|
414
|
+
)
|
|
415
|
+
self._save(participation={**self.state.participation, study_key: accepted})
|
|
416
|
+
return {
|
|
417
|
+
"study_key": study_key,
|
|
418
|
+
"participating": True,
|
|
419
|
+
"answer_submission": "Answers supplied for this study may be sent without a second approval",
|
|
420
|
+
**accepted.model_dump(),
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
def sample(self, candidates, *, week=None, selection=None):
|
|
424
|
+
self._require("analysis")
|
|
425
|
+
completed_week = self._sampling_week().isoformat()
|
|
426
|
+
if week is not None and week != completed_week:
|
|
427
|
+
raise ValidationError(
|
|
428
|
+
f"Supply the inventory for completed UTC week {completed_week}; "
|
|
429
|
+
"refresh metascience.status before sampling. Current, future and stale "
|
|
430
|
+
"inventory windows cannot create a new sample."
|
|
431
|
+
)
|
|
432
|
+
week = completed_week
|
|
433
|
+
methods = {"random": RANDOM_SAMPLING, "user_selected": MANUAL_SAMPLING}
|
|
434
|
+
if selection is not None and (not isinstance(selection, str) or selection not in methods):
|
|
435
|
+
raise ValidationError("Choose random or user_selected for activity selection")
|
|
436
|
+
if not self.state.scopes:
|
|
437
|
+
raise ValidationError("Select accessible research projects or conversations first")
|
|
438
|
+
if not isinstance(candidates, list) or len(candidates) > 500:
|
|
439
|
+
raise ValidationError("Supply metadata for at most 500 eligible sessions")
|
|
440
|
+
items = [Candidate.model_validate(c) for c in candidates]
|
|
441
|
+
if any(c.scope not in self.state.scopes for c in items):
|
|
442
|
+
raise ValidationError("A candidate is outside the researcher's selected sources")
|
|
443
|
+
# The same conversation may be listed under more than one selected project.
|
|
444
|
+
keyed = {digest([c.scope.host, c.session_ref]): c for c in items}
|
|
445
|
+
if len(keyed) != len(items):
|
|
446
|
+
raise ValidationError("A session was listed more than once")
|
|
447
|
+
inventory = digest(sorted(keyed))
|
|
448
|
+
previous = self.state.samples.get(week)
|
|
449
|
+
if previous:
|
|
450
|
+
if self._retired(week, previous):
|
|
451
|
+
raise ValidationError(self._retirement_message(week))
|
|
452
|
+
if any(c.scope not in self.state.scopes for c in previous.selected.values()):
|
|
453
|
+
self._save(**self._retire_samples([week]))
|
|
454
|
+
raise ValidationError(self._retirement_message(week))
|
|
455
|
+
if selection is not None and methods[selection] != previous.sampling:
|
|
456
|
+
raise ValidationError(
|
|
457
|
+
f"The {week} selection method is fixed; use metascience.batch to resume it. "
|
|
458
|
+
"Both methods share one weekly cap; do not create a second batch."
|
|
459
|
+
)
|
|
460
|
+
if inventory != previous.inventory_sha256:
|
|
461
|
+
raise ValidationError(
|
|
462
|
+
f"The {week} sample is fixed; use metascience.batch to resume it"
|
|
463
|
+
)
|
|
464
|
+
return self.batch(week)
|
|
465
|
+
sampling = methods[selection or "random"]
|
|
466
|
+
if sampling == MANUAL_SAMPLING:
|
|
467
|
+
if not 1 <= len(keyed) <= 20:
|
|
468
|
+
raise ValidationError("Choose between 1 and 20 completed research conversations")
|
|
469
|
+
if any(key in self.state.seen for key in keyed):
|
|
470
|
+
raise ValidationError(
|
|
471
|
+
"A conversation was already selected in a previous week; "
|
|
472
|
+
"choose only previously unanalysed conversations"
|
|
473
|
+
)
|
|
474
|
+
eligible = {k: c for k, c in keyed.items() if k not in self.state.seen}
|
|
475
|
+
# A fresh random seed is private; sorting hashes makes retries/order independent.
|
|
476
|
+
ranked = sorted(eligible, key=lambda k: digest([self.state.seed, week, k]))
|
|
477
|
+
chosen = ranked[:20]
|
|
478
|
+
sample = Sample(
|
|
479
|
+
id=uuid.uuid4().hex,
|
|
480
|
+
inventory_sha256=inventory,
|
|
481
|
+
eligible=len(eligible),
|
|
482
|
+
sampling=sampling,
|
|
483
|
+
selected={uuid.uuid4().hex: eligible[k] for k in chosen},
|
|
484
|
+
)
|
|
485
|
+
self._save(samples={**self.state.samples, week: sample}, seen=[*self.state.seen, *chosen])
|
|
486
|
+
return self.batch(week)
|
|
487
|
+
|
|
488
|
+
def _sample(self, week):
|
|
489
|
+
self._require("analysis")
|
|
490
|
+
sample = self.state.samples.get(week)
|
|
491
|
+
if not sample:
|
|
492
|
+
raise ValidationError("No sample is available within the current selected sources")
|
|
493
|
+
if self._retired(week, sample):
|
|
494
|
+
raise ValidationError(self._retirement_message(week))
|
|
495
|
+
if any(c.scope not in self.state.scopes for c in sample.selected.values()):
|
|
496
|
+
self._save(**self._retire_samples([week]))
|
|
497
|
+
raise ValidationError(self._retirement_message(week))
|
|
498
|
+
return sample
|
|
499
|
+
|
|
500
|
+
def batch(self, week):
|
|
501
|
+
return {"week": week, **self._sample(week).model_dump()}
|
|
502
|
+
|
|
503
|
+
def record(self, week, token, classification):
|
|
504
|
+
sample = self._sample(week)
|
|
505
|
+
if token not in sample.selected:
|
|
506
|
+
raise ValidationError("Only selected sessions can be classified")
|
|
507
|
+
record = Classification.model_validate(classification)
|
|
508
|
+
data = sample.model_dump()
|
|
509
|
+
data["records"][token] = record
|
|
510
|
+
# An earlier preview no longer represents the reviewed local findings.
|
|
511
|
+
self._save(
|
|
512
|
+
samples={**self.state.samples, week: Sample.model_validate(data)},
|
|
513
|
+
latest={k: v for k, v in self.state.latest.items() if k != f"activity:{week}"},
|
|
514
|
+
)
|
|
515
|
+
return {"recorded": token, "week": week}
|
|
516
|
+
|
|
517
|
+
def record_gap(self, week, token, gap, basis):
|
|
518
|
+
sample = self._sample(week)
|
|
519
|
+
if token not in sample.selected:
|
|
520
|
+
raise ValidationError("Only selected conversations can contribute candidate problems")
|
|
521
|
+
problem = SelectedProblem(id=uuid.uuid4().hex, gap=gap, basis=basis)
|
|
522
|
+
existing = sample.problems.get(token, [])
|
|
523
|
+
for previous in existing:
|
|
524
|
+
if previous.gap == problem.gap and previous.basis == problem.basis:
|
|
525
|
+
return {"recorded": previous.id, "week": week}
|
|
526
|
+
data = sample.model_dump()
|
|
527
|
+
data["problems"][token] = [*existing, problem]
|
|
528
|
+
self._save(samples={**self.state.samples, week: Sample.model_validate(data)})
|
|
529
|
+
return {
|
|
530
|
+
"recorded": problem.id,
|
|
531
|
+
"week": week,
|
|
532
|
+
"next": "Review this candidate through sharing.preview for channel gaps",
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
def preview_activity(self, week, tokens=None):
|
|
536
|
+
grants = self._require("analysis", "sharing")
|
|
537
|
+
sample = self._sample(week)
|
|
538
|
+
selected = sorted(sample.records if tokens is None else tokens)
|
|
539
|
+
if (
|
|
540
|
+
not selected
|
|
541
|
+
or len(set(selected)) != len(selected)
|
|
542
|
+
or any(t not in sample.records for t in selected)
|
|
543
|
+
):
|
|
544
|
+
raise ValidationError("Choose one or more classified sessions, without duplicates")
|
|
545
|
+
observations = [
|
|
546
|
+
ActivityObservation(
|
|
547
|
+
**sample.records[t].model_dump(),
|
|
548
|
+
host=sample.selected[t].scope.host,
|
|
549
|
+
)
|
|
550
|
+
for t in selected
|
|
551
|
+
]
|
|
552
|
+
payload = LinkedActivityPayload(
|
|
553
|
+
contributor_id=contributor_id(self.paths),
|
|
554
|
+
benchside_version=__version__,
|
|
555
|
+
batch_id=sample.id,
|
|
556
|
+
revision=sample.revision + 1,
|
|
557
|
+
week=week,
|
|
558
|
+
eligible=sample.eligible,
|
|
559
|
+
selected=len(sample.selected),
|
|
560
|
+
sampling=sample.sampling,
|
|
561
|
+
observations=observations,
|
|
562
|
+
)
|
|
563
|
+
# An identical repeat preview uses the existing bytes and approval token.
|
|
564
|
+
key = f"activity:{week}"
|
|
565
|
+
previous = self.state.drafts.get(self.state.latest.get(key))
|
|
566
|
+
if previous:
|
|
567
|
+
prior = parse_activity(previous.payload)
|
|
568
|
+
if payload.model_copy(update={"revision": prior.revision}) == prior:
|
|
569
|
+
payload = prior
|
|
570
|
+
data = sample.model_dump()
|
|
571
|
+
data["revision"] = payload.revision
|
|
572
|
+
self._save(samples={**self.state.samples, week: Sample.model_validate(data)})
|
|
573
|
+
return self._preview("activity", key, payload, grants)
|
|
574
|
+
|
|
575
|
+
def send(self, draft_id, approved_sha256):
|
|
576
|
+
try:
|
|
577
|
+
return self._send(draft_id, approved_sha256)
|
|
578
|
+
except Exception as err:
|
|
579
|
+
record_submission_failure(self.paths, err)
|
|
580
|
+
raise
|
|
581
|
+
|
|
582
|
+
def _send(self, draft_id, approved_sha256):
|
|
583
|
+
draft = self.state.drafts.get(draft_id)
|
|
584
|
+
if not draft or self.state.latest.get(draft.key) != draft_id:
|
|
585
|
+
raise ConsentRequiredError("Review the current metascience draft first")
|
|
586
|
+
if self._require(*draft.grants) != draft.grants:
|
|
587
|
+
raise ConsentRequiredError("Consent changed; prepare and review a new draft")
|
|
588
|
+
sink = self._sink(draft.channel)
|
|
589
|
+
if approved_sha256 != draft.sha256 or sink.destination != draft.destination:
|
|
590
|
+
raise ValidationError(
|
|
591
|
+
"Approve the exact payload and destination in the current preview"
|
|
592
|
+
)
|
|
593
|
+
if draft.id in self.state.receipts:
|
|
594
|
+
return self.state.receipts[draft.id].model_dump()
|
|
595
|
+
if draft.channel == "surveys":
|
|
596
|
+
key = draft.key.removeprefix("survey:")
|
|
597
|
+
study = self.state.studies[key]
|
|
598
|
+
if not study.active(self.today.isoformat()) or key in self.state.completed:
|
|
599
|
+
raise ConsentRequiredError("The survey has closed or was dismissed")
|
|
600
|
+
payload = parse_survey(draft.payload)
|
|
601
|
+
payload.check_study(study)
|
|
602
|
+
_check_survey_text(payload) # Also guard pending drafts from earlier releases.
|
|
603
|
+
if isinstance(payload, LinkedSurveyPayload):
|
|
604
|
+
accepted = self.state.participation.get(key)
|
|
605
|
+
if (
|
|
606
|
+
not accepted
|
|
607
|
+
or accepted.study_sha256 != payload.study_sha256
|
|
608
|
+
or accepted.invitation_grant != draft.grants["invitations"]
|
|
609
|
+
or accepted.destination != sink.destination
|
|
610
|
+
or accepted.contributor_id != payload.contributor_id
|
|
611
|
+
):
|
|
612
|
+
raise ConsentRequiredError(
|
|
613
|
+
"Study participation no longer matches these answers"
|
|
614
|
+
)
|
|
615
|
+
receipt = sink.send(draft.payload)
|
|
616
|
+
if receipt is None:
|
|
617
|
+
raise InfrastructureError(
|
|
618
|
+
"The collector did not acknowledge the submission",
|
|
619
|
+
code="submission_receipt_invalid",
|
|
620
|
+
)
|
|
621
|
+
result = {
|
|
622
|
+
"channel": draft.channel,
|
|
623
|
+
"destination": draft.destination,
|
|
624
|
+
**receipt.model_dump(mode="json"),
|
|
625
|
+
}
|
|
626
|
+
completed = self.state.completed
|
|
627
|
+
if draft.channel == "surveys":
|
|
628
|
+
completed = [*completed, draft.key.removeprefix("survey:")]
|
|
629
|
+
self._save(receipts={**self.state.receipts, draft.id: result}, completed=completed)
|
|
630
|
+
return result
|
|
631
|
+
|
|
632
|
+
def dispatch(self, request):
|
|
633
|
+
match request["action"]:
|
|
634
|
+
case "metascience.status":
|
|
635
|
+
return self.status()
|
|
636
|
+
case "metascience.consent":
|
|
637
|
+
return self.consent(request["choice"], request["enabled"])
|
|
638
|
+
case "metascience.scopes":
|
|
639
|
+
return self.scopes(request["scopes"])
|
|
640
|
+
case "metascience.invitations":
|
|
641
|
+
return self.invitations()
|
|
642
|
+
case "metascience.dismiss":
|
|
643
|
+
return self.dismiss(
|
|
644
|
+
request["study_key"], permanently=request.get("permanently", False)
|
|
645
|
+
)
|
|
646
|
+
case "metascience.survey":
|
|
647
|
+
return self.survey(request["study_key"], request["answers"])
|
|
648
|
+
case "metascience.join_study":
|
|
649
|
+
return self.join_study(request["study_key"], request["study_sha256"])
|
|
650
|
+
case "metascience.sample":
|
|
651
|
+
return self.sample(
|
|
652
|
+
request["candidates"],
|
|
653
|
+
week=request.get("week"),
|
|
654
|
+
selection=request.get("selection"),
|
|
655
|
+
)
|
|
656
|
+
case "metascience.batch":
|
|
657
|
+
return self.batch(request["week"])
|
|
658
|
+
case "metascience.record":
|
|
659
|
+
return self.record(request["week"], request["token"], request["classification"])
|
|
660
|
+
case "metascience.gap":
|
|
661
|
+
return self.record_gap(
|
|
662
|
+
request["week"], request["token"], request["gap"], request["basis"]
|
|
663
|
+
)
|
|
664
|
+
case "metascience.preview":
|
|
665
|
+
return self.preview_activity(request["week"], request.get("tokens"))
|
|
666
|
+
case "metascience.send":
|
|
667
|
+
return self.send(request["draft_id"], request["approved_sha256"])
|
|
668
|
+
case "metascience.history":
|
|
669
|
+
return [r.model_dump() for r in self.state.receipts.values()]
|
|
670
|
+
case _:
|
|
671
|
+
raise ValidationError("Unknown metascience action")
|