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.
Files changed (178) hide show
  1. benchside/__init__.py +1 -0
  2. benchside/_content/app/SKILL.md +155 -0
  3. benchside/_content/app/references/app-api.md +261 -0
  4. benchside/_content/app/references/generic-agents.md +69 -0
  5. benchside/_content/app/references/metascience.md +346 -0
  6. benchside/_content/app/references/native-memory.md +429 -0
  7. benchside/_content/app/references/onboarding.md +313 -0
  8. benchside/_content/app/references/sharing.md +159 -0
  9. benchside/_content/app/scripts/benchside_app.py +311 -0
  10. benchside/_content/app-requirements.txt +197 -0
  11. benchside/_content/claude/bench-init/SKILL.md +37 -0
  12. benchside/_content/claude/bench-share/SKILL.md +44 -0
  13. benchside/_content/fixtures/.gitkeep +0 -0
  14. benchside/_content/legacy-skill-digests.json +26 -0
  15. benchside/_content/personas/journal-club.yaml +45 -0
  16. benchside/_content/personas/methods-clinic.yaml +49 -0
  17. benchside/_content/personas/peer-review.yaml +45 -0
  18. benchside/_content/personas/pi-hypothesis.yaml +121 -0
  19. benchside/_content/personas/pi.yaml +87 -0
  20. benchside/_content/personas/repro-check.yaml +45 -0
  21. benchside/_content/personas/results-meeting.yaml +46 -0
  22. benchside/_content/personas/study-design.yaml +50 -0
  23. benchside/_content/templates/app-role.md.tmpl +31 -0
  24. benchside/_content/templates/blocks/capture-contract.md +40 -0
  25. benchside/_content/templates/blocks/sovereignty.md +36 -0
  26. benchside/_content/templates/skill.md.tmpl +54 -0
  27. benchside/application/__init__.py +0 -0
  28. benchside/application/app.py +458 -0
  29. benchside/application/bridge.py +55 -0
  30. benchside/application/contributions.py +39 -0
  31. benchside/application/di.py +35 -0
  32. benchside/application/metascience.py +671 -0
  33. benchside/application/native.py +1088 -0
  34. benchside/application/packaging.py +19 -0
  35. benchside/application/sharing.py +439 -0
  36. benchside/application/submission_failures.py +28 -0
  37. benchside/cli/__init__.py +0 -0
  38. benchside/cli/hooks.py +159 -0
  39. benchside/cli/install.py +276 -0
  40. benchside/cli/journal.py +232 -0
  41. benchside/cli/main.py +761 -0
  42. benchside/cli/runtime.py +245 -0
  43. benchside/cli/sharing.py +66 -0
  44. benchside/cli/ui/__init__.py +5 -0
  45. benchside/cli/ui/_glyphs.py +21 -0
  46. benchside/cli/ui/_model.py +66 -0
  47. benchside/cli/ui/_renderer.py +110 -0
  48. benchside/cli/ui/_rich.py +75 -0
  49. benchside/config.py +122 -0
  50. benchside/domain/__init__.py +0 -0
  51. benchside/domain/authoring/__init__.py +0 -0
  52. benchside/domain/authoring/command/__init__.py +0 -0
  53. benchside/domain/authoring/command/compile.py +28 -0
  54. benchside/domain/authoring/model/__init__.py +0 -0
  55. benchside/domain/authoring/model/flow.py +27 -0
  56. benchside/domain/authoring/model/persona.py +56 -0
  57. benchside/domain/authoring/model/skill.py +32 -0
  58. benchside/domain/authoring/model/value.py +42 -0
  59. benchside/domain/authoring/port/__init__.py +5 -0
  60. benchside/domain/authoring/port/renderer.py +17 -0
  61. benchside/domain/authoring/port/repository.py +28 -0
  62. benchside/domain/authoring/port/skill_writer.py +19 -0
  63. benchside/domain/authoring/query/__init__.py +0 -0
  64. benchside/domain/authoring/query/get_persona.py +30 -0
  65. benchside/domain/authoring/query/list_personas.py +21 -0
  66. benchside/domain/authoring/service/__init__.py +0 -0
  67. benchside/domain/authoring/service/authoring.py +99 -0
  68. benchside/domain/authoring/util/__init__.py +0 -0
  69. benchside/domain/authoring/util/di/__init__.py +3 -0
  70. benchside/domain/authoring/util/di/provider.py +15 -0
  71. benchside/domain/consultation/__init__.py +0 -0
  72. benchside/domain/consultation/command/__init__.py +0 -0
  73. benchside/domain/consultation/command/capture_gap.py +28 -0
  74. benchside/domain/consultation/command/close.py +29 -0
  75. benchside/domain/consultation/command/open.py +36 -0
  76. benchside/domain/consultation/command/raise_critique.py +30 -0
  77. benchside/domain/consultation/command/record_decision.py +30 -0
  78. benchside/domain/consultation/command/resolve_critique.py +32 -0
  79. benchside/domain/consultation/command/state_hypothesis.py +28 -0
  80. benchside/domain/consultation/event/__init__.py +22 -0
  81. benchside/domain/consultation/event/closed.py +13 -0
  82. benchside/domain/consultation/event/critique_raised.py +12 -0
  83. benchside/domain/consultation/event/critique_resolved.py +12 -0
  84. benchside/domain/consultation/event/decision_recorded.py +13 -0
  85. benchside/domain/consultation/event/gap_observed.py +16 -0
  86. benchside/domain/consultation/event/hypothesis_stated.py +12 -0
  87. benchside/domain/consultation/event/opened.py +23 -0
  88. benchside/domain/consultation/event/question.py +16 -0
  89. benchside/domain/consultation/event/research_recorded.py +9 -0
  90. benchside/domain/consultation/model/__init__.py +0 -0
  91. benchside/domain/consultation/model/consultation.py +60 -0
  92. benchside/domain/consultation/model/project.py +78 -0
  93. benchside/domain/consultation/model/value.py +150 -0
  94. benchside/domain/consultation/port/__init__.py +6 -0
  95. benchside/domain/consultation/port/repository.py +32 -0
  96. benchside/domain/consultation/query/__init__.py +0 -0
  97. benchside/domain/consultation/query/get_consultation.py +28 -0
  98. benchside/domain/consultation/query/recall_project.py +97 -0
  99. benchside/domain/consultation/service/__init__.py +0 -0
  100. benchside/domain/consultation/service/consultation.py +373 -0
  101. benchside/domain/consultation/util/__init__.py +0 -0
  102. benchside/domain/consultation/util/di/__init__.py +3 -0
  103. benchside/domain/consultation/util/di/provider.py +33 -0
  104. benchside/domain/export/__init__.py +0 -0
  105. benchside/domain/export/command/__init__.py +0 -0
  106. benchside/domain/export/command/export_observations.py +31 -0
  107. benchside/domain/export/command/grant_consent.py +26 -0
  108. benchside/domain/export/command/revoke_consent.py +20 -0
  109. benchside/domain/export/event/__init__.py +19 -0
  110. benchside/domain/export/event/consent_granted.py +9 -0
  111. benchside/domain/export/event/consent_revoked.py +8 -0
  112. benchside/domain/export/event/observations_exported.py +12 -0
  113. benchside/domain/export/event/reporting.py +24 -0
  114. benchside/domain/export/model/__init__.py +0 -0
  115. benchside/domain/export/model/ledger.py +40 -0
  116. benchside/domain/export/model/metascience.py +418 -0
  117. benchside/domain/export/model/reporting.py +193 -0
  118. benchside/domain/export/model/value.py +79 -0
  119. benchside/domain/export/model/wire.py +104 -0
  120. benchside/domain/export/port/__init__.py +5 -0
  121. benchside/domain/export/port/redactor.py +27 -0
  122. benchside/domain/export/port/repository.py +25 -0
  123. benchside/domain/export/port/sink.py +19 -0
  124. benchside/domain/export/query/__init__.py +0 -0
  125. benchside/domain/export/query/consent_status.py +30 -0
  126. benchside/domain/export/query/preview_export.py +37 -0
  127. benchside/domain/export/service/__init__.py +0 -0
  128. benchside/domain/export/service/consent.py +53 -0
  129. benchside/domain/export/service/export.py +171 -0
  130. benchside/domain/export/service/reporting.py +281 -0
  131. benchside/domain/export/util/__init__.py +0 -0
  132. benchside/domain/export/util/di/__init__.py +3 -0
  133. benchside/domain/export/util/di/provider.py +22 -0
  134. benchside/domain/shared/__init__.py +0 -0
  135. benchside/domain/shared/command.py +44 -0
  136. benchside/domain/shared/error.py +51 -0
  137. benchside/domain/shared/event.py +46 -0
  138. benchside/domain/shared/model/__init__.py +31 -0
  139. benchside/domain/shared/model/aggregate.py +9 -0
  140. benchside/domain/shared/model/capture.py +33 -0
  141. benchside/domain/shared/model/entity.py +5 -0
  142. benchside/domain/shared/model/gap.py +89 -0
  143. benchside/domain/shared/model/ids.py +64 -0
  144. benchside/domain/shared/model/provenance.py +16 -0
  145. benchside/domain/shared/model/value.py +17 -0
  146. benchside/domain/shared/port/__init__.py +4 -0
  147. benchside/domain/shared/port/base.py +9 -0
  148. benchside/domain/shared/port/journal.py +36 -0
  149. benchside/domain/shared/query.py +42 -0
  150. benchside/domain/shared/service.py +31 -0
  151. benchside/infrastructure/__init__.py +9 -0
  152. benchside/infrastructure/content/__init__.py +0 -0
  153. benchside/infrastructure/content/loader.py +108 -0
  154. benchside/infrastructure/content/renderer.py +129 -0
  155. benchside/infrastructure/content/writer.py +26 -0
  156. benchside/infrastructure/files.py +43 -0
  157. benchside/infrastructure/http_sink.py +128 -0
  158. benchside/infrastructure/journal/__init__.py +0 -0
  159. benchside/infrastructure/journal/di.py +85 -0
  160. benchside/infrastructure/journal/projection.py +244 -0
  161. benchside/infrastructure/journal/registry.py +24 -0
  162. benchside/infrastructure/journal/store.py +134 -0
  163. benchside/infrastructure/placeholders.py +28 -0
  164. benchside/infrastructure/readable_records.py +211 -0
  165. benchside/infrastructure/readable_refresh.py +58 -0
  166. benchside/infrastructure/redaction.py +44 -0
  167. benchside/infrastructure/session_context.py +225 -0
  168. benchside/infrastructure/storage_layout.py +104 -0
  169. benchside/reporting.py +333 -0
  170. benchside/util/__init__.py +0 -0
  171. benchside/util/di/__init__.py +4 -0
  172. benchside/util/di/base.py +16 -0
  173. benchside/util/di/scope.py +18 -0
  174. benchside-0.4.1.dist-info/METADATA +97 -0
  175. benchside-0.4.1.dist-info/RECORD +178 -0
  176. benchside-0.4.1.dist-info/WHEEL +4 -0
  177. benchside-0.4.1.dist-info/entry_points.txt +2 -0
  178. benchside-0.4.1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,281 @@
1
+ """Optional reporting, with no shared identifiers in workflow observations."""
2
+
3
+ from collections import defaultdict
4
+ from datetime import UTC, date, datetime, timedelta
5
+
6
+ from pydantic import TypeAdapter
7
+ from pydantic import ValidationError as SchemaError
8
+
9
+ from benchside.domain.consultation.event import (
10
+ ConsultationClosed,
11
+ ConsultationOpened,
12
+ CritiqueRaised,
13
+ CritiqueResolved,
14
+ DecisionRecorded,
15
+ GapObserved,
16
+ HypothesisStated,
17
+ ResearchRecorded,
18
+ )
19
+ from benchside.domain.consultation.event.question import QuestionAnswered, QuestionRecorded
20
+ from benchside.domain.export.event.reporting import (
21
+ FeedbackRecorded,
22
+ ReportingConsentChanged,
23
+ ReportSubmitted,
24
+ UsageFailureRecorded,
25
+ )
26
+ from benchside.domain.export.model.reporting import (
27
+ FAILURE_CODES,
28
+ AppVersion,
29
+ Channel,
30
+ Feedback,
31
+ FeedbackPayload,
32
+ RecordCounts,
33
+ Role,
34
+ UsagePayload,
35
+ UsageRow,
36
+ Version,
37
+ parse_feedback,
38
+ )
39
+ from benchside.domain.export.model.value import ExportPreview
40
+ from benchside.domain.export.port.redactor import Redactor
41
+ from benchside.domain.export.port.sink import ExportSink
42
+ from benchside.domain.shared.error import ConsentRequiredError, NotFoundError, ValidationError
43
+ from benchside.domain.shared.event import new_event_id
44
+ from benchside.domain.shared.model.ids import CONSENT_LEDGER_PROJECT, ProjectId
45
+ from benchside.domain.shared.port.journal import Journal
46
+ from benchside.domain.shared.service import Service
47
+
48
+ REPORTING_PROJECT = ProjectId("reporting-ledger")
49
+ RECORD_EVENTS = {
50
+ QuestionRecorded: "record",
51
+ QuestionAnswered: "record",
52
+ HypothesisStated: "hypothesis",
53
+ CritiqueRaised: "critique",
54
+ CritiqueResolved: "resolution",
55
+ DecisionRecorded: "decision",
56
+ GapObserved: "gap",
57
+ ResearchRecorded: "record",
58
+ }
59
+ _ROLE = TypeAdapter(Role)
60
+ _VERSION = TypeAdapter(Version)
61
+ _APP_VERSION = TypeAdapter(AppVersion)
62
+
63
+
64
+ def week_start(now: datetime | None = None) -> str:
65
+ day = (now or datetime.now(UTC)).astimezone(UTC).date()
66
+ return (day - timedelta(days=day.weekday())).isoformat()
67
+
68
+
69
+ class ReportingService(Service):
70
+ journal: Journal
71
+
72
+ def active_grant(self, channel: Channel) -> str | None:
73
+ found = None
74
+ for event in self.journal.read(CONSENT_LEDGER_PROJECT):
75
+ if isinstance(event, ReportingConsentChanged) and event.channel == channel:
76
+ found = event.id if event.enabled else None
77
+ return found
78
+
79
+ def set_consent(self, channel: Channel, enabled: bool) -> str | None:
80
+ current = self.active_grant(channel)
81
+ if bool(current) == enabled:
82
+ return current
83
+ event = ReportingConsentChanged(id=new_event_id(), channel=channel, enabled=enabled)
84
+ self.journal.append(CONSENT_LEDGER_PROJECT, event)
85
+ return event.id if enabled else None
86
+
87
+ def record_feedback(self, feedback: Feedback) -> Feedback:
88
+ self.journal.append(
89
+ REPORTING_PROJECT, FeedbackRecorded(id=new_event_id(), feedback=feedback)
90
+ )
91
+ return feedback
92
+
93
+ def feedback_payload(self, identifier: str, version: str) -> str:
94
+ for event in self.journal.read(REPORTING_PROJECT):
95
+ if isinstance(event, FeedbackRecorded) and event.feedback.id == identifier:
96
+ return FeedbackPayload(
97
+ benchside_version=version,
98
+ feedback=event.feedback,
99
+ ).model_dump_json(by_alias=True, indent=2)
100
+ raise NotFoundError("Feedback was not found")
101
+
102
+ def failure(self, code: str) -> None:
103
+ if code in FAILURE_CODES and self.active_grant("usage"):
104
+ self.journal.append(
105
+ REPORTING_PROJECT,
106
+ UsageFailureRecorded(id=new_event_id(), code=code),
107
+ )
108
+
109
+ def usage_payload(self, *, installation_id, report_id, week, revision, version) -> UsagePayload:
110
+ start = date.fromisoformat(week)
111
+ end = start + timedelta(days=7)
112
+ groups = {}
113
+ # IDs are used locally to join events, then discarded from the report.
114
+ for project_id in self.journal.projects():
115
+ if project_id in {REPORTING_PROJECT, CONSENT_LEDGER_PROJECT}:
116
+ continue
117
+ events = list(self.journal.read(project_id))
118
+ sittings = {}
119
+ reportable = {}
120
+ for event in events:
121
+ if isinstance(event, ConsultationOpened):
122
+ sittings.setdefault(event.consultation_id, event)
123
+ for identifier, sitting in sittings.items():
124
+ try:
125
+ reportable[identifier] = (
126
+ _ROLE.validate_python(sitting.persona_id.root),
127
+ _VERSION.validate_python(sitting.persona_version),
128
+ )
129
+ except SchemaError:
130
+ # Custom/legacy roles remain valid private science records,
131
+ # but cannot be represented by the collector's strict schema.
132
+ continue
133
+ seen = set()
134
+ seen_opens = set()
135
+ seen_closes = set()
136
+ for event in events:
137
+ if event.id in seen:
138
+ continue
139
+ seen.add(event.id)
140
+ if not start <= event.recorded_at.astimezone(UTC).date() < end:
141
+ continue
142
+ sitting = sittings.get(getattr(event, "consultation_id", None))
143
+ if sitting is None or sitting.consultation_id not in reportable:
144
+ continue
145
+ # A scientific sitting can continue across apps and upgrades.
146
+ # Legacy events have no per-event context and retain their
147
+ # original opening attribution rather than inventing metadata.
148
+ context = event.provenance or sitting
149
+ host = context.host if context.host in {"chatgpt", "claude"} else "unknown"
150
+ surface = (
151
+ context.surface if context.surface in {"web", "desktop", "cli"} else "unknown"
152
+ )
153
+ try:
154
+ app_version = _APP_VERSION.validate_python(context.app_version)
155
+ except SchemaError:
156
+ app_version = "unknown"
157
+ role, role_version = reportable[sitting.consultation_id]
158
+ key = (
159
+ role,
160
+ role_version,
161
+ host,
162
+ surface,
163
+ app_version,
164
+ )
165
+ row = groups.setdefault(
166
+ key,
167
+ {
168
+ "started": 0,
169
+ "concluded": 0,
170
+ "abandoned": 0,
171
+ "records": defaultdict(int),
172
+ },
173
+ )
174
+ if (
175
+ isinstance(event, ConsultationOpened)
176
+ and event.consultation_id not in seen_opens
177
+ and event.id == sitting.id
178
+ ):
179
+ row["started"] += 1
180
+ seen_opens.add(event.consultation_id)
181
+ elif (
182
+ isinstance(event, ConsultationClosed)
183
+ and event.consultation_id not in seen_closes
184
+ ):
185
+ row["concluded" if event.state == "converged" else "abandoned"] += 1
186
+ seen_closes.add(event.consultation_id)
187
+ elif type(event) in RECORD_EVENTS:
188
+ row["records"][RECORD_EVENTS[type(event)]] += 1
189
+ errors = dict.fromkeys(FAILURE_CODES, 0)
190
+ seen_errors = set()
191
+ for event in self.journal.read(REPORTING_PROJECT):
192
+ if (
193
+ isinstance(event, UsageFailureRecorded)
194
+ and event.id not in seen_errors
195
+ and start <= event.recorded_at.astimezone(UTC).date() < end
196
+ ):
197
+ seen_errors.add(event.id)
198
+ errors[event.code] += 1
199
+ return UsagePayload(
200
+ installation_id=installation_id,
201
+ report_id=report_id,
202
+ week=week,
203
+ revision=revision,
204
+ benchside_version=version,
205
+ errors=errors,
206
+ sessions=[
207
+ UsageRow(
208
+ role=key[0],
209
+ role_version=key[1],
210
+ host=key[2],
211
+ surface=key[3],
212
+ app_version=key[4],
213
+ started=value["started"],
214
+ concluded=value["concluded"],
215
+ abandoned=value["abandoned"],
216
+ records=RecordCounts(**value["records"]),
217
+ )
218
+ for key, value in sorted(groups.items())
219
+ if any(value[field] for field in ("started", "concluded", "abandoned"))
220
+ or any(value["records"].values())
221
+ ],
222
+ )
223
+
224
+ def send(
225
+ self,
226
+ *,
227
+ channel: Channel,
228
+ preview: ExportPreview,
229
+ approved_sha256: str,
230
+ sink: ExportSink,
231
+ redactor: Redactor,
232
+ ):
233
+ from benchside.domain.export.service.export import ExportService
234
+
235
+ grant = self.active_grant(channel)
236
+ if not grant or grant != preview.grant_id:
237
+ raise ConsentRequiredError("Reporting consent changed; review the submission again")
238
+ digest = ExportService._digest(preview.payload)
239
+ if digest != preview.payload_sha256 or digest != approved_sha256:
240
+ raise ConsentRequiredError("The reviewed payload changed or has not been approved")
241
+ if preview.destination != sink.destination:
242
+ raise ConsentRequiredError("The destination changed; review the submission again")
243
+ parsed = (
244
+ parse_feedback(preview.payload)
245
+ if channel == "feedback"
246
+ else UsagePayload.model_validate_json(preview.payload)
247
+ )
248
+ if any(f.tier == "HIGH" for f in redactor.scan(preview.payload)):
249
+ raise ValidationError("Sensitive content remains; edit and review before sending")
250
+ identifier = parsed.feedback.id if channel == "feedback" else parsed.report_id
251
+ for event in self.journal.read(CONSENT_LEDGER_PROJECT):
252
+ if (
253
+ isinstance(event, ReportSubmitted)
254
+ and event.channel == channel
255
+ and event.payload_sha256 == digest
256
+ and event.destination == sink.destination
257
+ ):
258
+ return event
259
+ if (
260
+ isinstance(event, ReportSubmitted)
261
+ and channel == "feedback"
262
+ and event.channel == channel
263
+ and event.submission_id == identifier
264
+ ):
265
+ raise ValidationError(
266
+ "That feedback has already been shared; record new feedback for a new submission"
267
+ )
268
+ receipt = sink.send(preview.payload)
269
+ if receipt is None:
270
+ raise ValidationError("Reporting requires a verified collector receipt")
271
+ event = ReportSubmitted(
272
+ id=new_event_id(),
273
+ channel=channel,
274
+ grant_id=grant,
275
+ submission_id=identifier,
276
+ payload_sha256=digest,
277
+ destination=sink.destination,
278
+ received_at=receipt.received_at,
279
+ )
280
+ self.journal.append(CONSENT_LEDGER_PROJECT, event)
281
+ return event
File without changes
@@ -0,0 +1,3 @@
1
+ from benchside.domain.export.util.di.provider import ExportProvider
2
+
3
+ __all__ = ["ExportProvider"]
@@ -0,0 +1,22 @@
1
+ from dishka import provide
2
+
3
+ from benchside.domain.export.command.export_observations import ExportObservationsHandler
4
+ from benchside.domain.export.command.grant_consent import GrantConsentHandler
5
+ from benchside.domain.export.command.revoke_consent import RevokeConsentHandler
6
+ from benchside.domain.export.query.consent_status import GetConsentStatusHandler
7
+ from benchside.domain.export.query.preview_export import PreviewExportHandler
8
+ from benchside.domain.export.service.consent import ConsentService
9
+ from benchside.domain.export.service.export import ExportService
10
+ from benchside.util.di import Provider, Scope
11
+
12
+
13
+ class ExportProvider(Provider):
14
+ consent_service = provide(ConsentService, scope=Scope.UOW)
15
+ export_service = provide(ExportService, scope=Scope.UOW)
16
+
17
+ grant_handler = provide(GrantConsentHandler, scope=Scope.UOW)
18
+ revoke_handler = provide(RevokeConsentHandler, scope=Scope.UOW)
19
+ export_handler = provide(ExportObservationsHandler, scope=Scope.UOW)
20
+
21
+ preview_handler = provide(PreviewExportHandler, scope=Scope.UOW)
22
+ consent_status_handler = provide(GetConsentStatusHandler, scope=Scope.UOW)
File without changes
@@ -0,0 +1,44 @@
1
+ """Command side: the write half of CQRS.
2
+
3
+ One file per use case holds three classes: the Command DTO, the Result DTO,
4
+ and the Handler. Handlers are thin -- unpack, call one service, build a result.
5
+ """
6
+
7
+ from abc import ABCMeta, abstractmethod
8
+ from dataclasses import dataclass
9
+ from typing import Any, Generic, TypeVar, dataclass_transform
10
+
11
+ from pydantic import BaseModel
12
+
13
+
14
+ class Command(BaseModel):
15
+ """An intent to change state. Also the CLI argument shape."""
16
+
17
+
18
+ class Result(BaseModel):
19
+ """What a handler returns. Also the CLI output shape."""
20
+
21
+
22
+ @dataclass_transform()
23
+ class _CommandHandlerMeta(ABCMeta):
24
+ def __new__(
25
+ mcs,
26
+ name: str,
27
+ bases: tuple[type, ...],
28
+ namespace: dict[str, Any],
29
+ ) -> type:
30
+ cls = super().__new__(mcs, name, bases, namespace)
31
+ if any(isinstance(b, mcs) for b in bases):
32
+ return dataclass(cls)
33
+ return cls
34
+
35
+
36
+ C = TypeVar("C", bound=Command)
37
+ R = TypeVar("R", bound=Result)
38
+
39
+
40
+ class CommandHandler(Generic[C, R], metaclass=_CommandHandlerMeta):
41
+ """Entry point for a write. Delegates to a service; never touches a port."""
42
+
43
+ @abstractmethod
44
+ def run(self, cmd: C) -> R: ...
@@ -0,0 +1,51 @@
1
+ """Domain error hierarchy.
2
+
3
+ Raise typed errors; never return None to signal failure. None means "not
4
+ found" at a repository boundary and nothing else.
5
+ """
6
+
7
+
8
+ class BenchsideError(Exception):
9
+ """Root of every error benchside raises deliberately."""
10
+
11
+ def __init__(self, message: str, *, code: str | None = None, hint: str | None = None) -> None:
12
+ super().__init__(message)
13
+ self.message = message
14
+ self.code = code or type(self).__name__
15
+ self.hint = hint
16
+
17
+
18
+ class DomainError(BenchsideError):
19
+ """A business-rule violation. The caller asked for something invalid."""
20
+
21
+
22
+ class NotFoundError(DomainError):
23
+ """The referenced aggregate does not exist."""
24
+
25
+
26
+ class ValidationError(DomainError):
27
+ """Input failed validation."""
28
+
29
+ def __init__(self, message: str, *, field: str | None = None, code: str | None = None) -> None:
30
+ super().__init__(message, code=code)
31
+ self.field = field
32
+
33
+
34
+ class InvalidStateError(DomainError):
35
+ """The aggregate cannot make this transition from its current state."""
36
+
37
+
38
+ class ConsentRequiredError(DomainError):
39
+ """An export was attempted without an active consent grant covering it."""
40
+
41
+
42
+ class InfrastructureError(BenchsideError):
43
+ """A system failure: disk, network, external process."""
44
+
45
+
46
+ class StorageUnavailableError(InfrastructureError):
47
+ """The journal or content store could not be read or written."""
48
+
49
+
50
+ class ConfigurationError(InfrastructureError):
51
+ """The installation is misconfigured; fail fast at startup."""
@@ -0,0 +1,46 @@
1
+ """The journal event base.
2
+
3
+ Every durable fact benchside records is an Event appended to a research line's
4
+ journal. The journal is append-only and is the source of truth: consultation
5
+ state, the lab notebook, and the eval assertions are all derived from it.
6
+ """
7
+
8
+ from datetime import UTC, datetime
9
+ from typing import ClassVar, NewType, Self
10
+ from uuid import uuid4
11
+
12
+ from pydantic import BaseModel, Field
13
+
14
+ from benchside.domain.shared.model.provenance import AppProvenance
15
+
16
+ EventId = NewType("EventId", str)
17
+
18
+
19
+ def new_event_id() -> EventId:
20
+ """Opaque unique event id. Always generated here, never by the model."""
21
+ return EventId(str(uuid4()))
22
+
23
+
24
+ class Event(BaseModel):
25
+ """A recorded fact. Immutable once appended.
26
+
27
+ Subclasses register themselves by class name so a journal line can be
28
+ parsed back into its concrete type.
29
+ """
30
+
31
+ _registry: ClassVar[dict[str, type["Event"]]] = {}
32
+
33
+ id: EventId
34
+ recorded_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
35
+ # Old journals omit this. New scientific events keep the originating app
36
+ # even when another app later resumes the same scientific sitting.
37
+ provenance: AppProvenance | None = None
38
+
39
+ def __init_subclass__(cls, **kwargs: object) -> None:
40
+ super().__init_subclass__(**kwargs)
41
+ Event._registry[cls.__name__] = cls
42
+
43
+ @classmethod
44
+ def resolve(cls, name: str) -> type[Self]:
45
+ """Look up a concrete Event subclass by its class name."""
46
+ return Event._registry[name] # type: ignore[return-value]
@@ -0,0 +1,31 @@
1
+ from benchside.domain.shared.model.aggregate import Aggregate
2
+ from benchside.domain.shared.model.entity import Entity
3
+ from benchside.domain.shared.model.gap import GAP_KINDS, Gap
4
+ from benchside.domain.shared.model.ids import (
5
+ ConsultationId,
6
+ CritiqueId,
7
+ DecisionId,
8
+ GrantId,
9
+ HypothesisId,
10
+ ObservationId,
11
+ PersonaId,
12
+ ProjectId,
13
+ )
14
+ from benchside.domain.shared.model.value import RootValueObject, ValueObject
15
+
16
+ __all__ = [
17
+ "GAP_KINDS",
18
+ "Aggregate",
19
+ "ConsultationId",
20
+ "CritiqueId",
21
+ "DecisionId",
22
+ "Entity",
23
+ "Gap",
24
+ "GrantId",
25
+ "HypothesisId",
26
+ "ObservationId",
27
+ "PersonaId",
28
+ "ProjectId",
29
+ "RootValueObject",
30
+ "ValueObject",
31
+ ]
@@ -0,0 +1,9 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class Aggregate(BaseModel):
5
+ """Consistency boundary. Mutable, and owns its own state transitions.
6
+
7
+ An aggregate raises InvalidStateError rather than letting a caller put it
8
+ into an illegal state.
9
+ """
@@ -0,0 +1,33 @@
1
+ """The capture vocabulary.
2
+
3
+ Shared kernel: authoring declares requirements over these kinds; consultation
4
+ enforces them at close. Each kind names a `bench` call and maps 1:1 to a
5
+ journal event type.
6
+ """
7
+
8
+ from enum import StrEnum
9
+ from typing import Literal
10
+
11
+ from benchside.domain.shared.model.value import ValueObject
12
+
13
+ RecordKind = Literal[
14
+ "study-design", "methods", "results", "reproducibility", "literature", "review"
15
+ ]
16
+
17
+
18
+ class CaptureKind(StrEnum):
19
+ HYPOTHESIS = "hypothesis"
20
+ CRITIQUE = "critique"
21
+ RESOLUTION = "resolution"
22
+ DECISION = "decision"
23
+ GAP = "gap"
24
+ RECORD = "record"
25
+ QUESTION = "question"
26
+ ANSWER = "answer"
27
+
28
+
29
+ class CloseRequirement(ValueObject):
30
+ """A minimum capture count a sitting must reach to close converged."""
31
+
32
+ kind: CaptureKind
33
+ minimum: int = 1
@@ -0,0 +1,5 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class Entity(BaseModel):
5
+ """Has identity and a lifecycle, but is not a consistency boundary."""
@@ -0,0 +1,89 @@
1
+ """The gap taxonomy.
2
+
3
+ Kernel rather than domain-owned: consultation records gaps as they occur,
4
+ export reads them. A gap is the *shape* of a workflow breakdown, captured as a
5
+ closed sum at the moment it happens rather than distilled from prose later.
6
+
7
+ Free text describes tooling and process only -- never a hypothesis, a result,
8
+ or data. Redaction and consent are enforced by the export domain.
9
+ """
10
+
11
+ from typing import Literal
12
+
13
+ from pydantic import ConfigDict, field_validator, model_serializer
14
+
15
+ from benchside.domain.shared.model.value import ValueObject
16
+
17
+
18
+ class GapContext(ValueObject):
19
+ """Optional public tooling/process context, never private scientific details."""
20
+
21
+ model_config = ConfigDict(frozen=True, extra="forbid")
22
+ tool_name: str | None = None
23
+ tool_version: str | None = None
24
+ dataset_name: str | None = None
25
+ dataset_version: str | None = None
26
+ workflow_area: str | None = None
27
+ frequency: str | None = None
28
+ impact: str | None = None
29
+ workaround: str | None = None
30
+ desired_improvement: str | None = None
31
+
32
+ @field_validator("*")
33
+ @classmethod
34
+ def bounded_text(cls, value):
35
+ if value is not None and len(value.encode("utf-16-le")) // 2 > 2000:
36
+ raise ValueError("Context text must be at most 2000 UTF-16 characters")
37
+ return value
38
+
39
+ @model_serializer(mode="wrap")
40
+ def omit_unknown(self, handler):
41
+ return {key: value for key, value in handler(self).items() if value is not None}
42
+
43
+
44
+ class ContextualGap(ValueObject):
45
+ context: GapContext | None = None
46
+
47
+ @model_serializer(mode="wrap")
48
+ def preserve_legacy_shape(self, handler):
49
+ value = handler(self)
50
+ if not value.get("context"):
51
+ value.pop("context", None)
52
+ return value
53
+
54
+
55
+ class MissingTool(ContextualGap):
56
+ task: str
57
+ reached_for: str
58
+ why_failed: str
59
+ kind: Literal["missing_tool"] = "missing_tool"
60
+
61
+
62
+ class UnfindableData(ContextualGap):
63
+ sought: str
64
+ where_searched: tuple[str, ...]
65
+ kind: Literal["unfindable_data"] = "unfindable_data"
66
+
67
+
68
+ class ManualToil(ContextualGap):
69
+ task: str
70
+ frequency: str
71
+ kind: Literal["manual_toil"] = "manual_toil"
72
+
73
+
74
+ class DeadEnd(ContextualGap):
75
+ approach: str
76
+ cost: str
77
+ kind: Literal["dead_end"] = "dead_end"
78
+
79
+
80
+ class MissingIndex(ContextualGap):
81
+ question: str
82
+ kind: Literal["missing_index"] = "missing_index"
83
+
84
+
85
+ Gap = MissingTool | UnfindableData | ManualToil | DeadEnd | MissingIndex
86
+
87
+ GAP_KINDS: frozenset[str] = frozenset(
88
+ {"missing_tool", "unfindable_data", "manual_toil", "dead_end", "missing_index"}
89
+ )