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,85 @@
1
+ """File-backed bindings: the production port seam.
2
+
3
+ Everything durable routes through the JSONL journal; content comes from the
4
+ resolved content root (checkout or packaged data).
5
+ """
6
+
7
+ import os
8
+
9
+ from dishka import provide
10
+
11
+ from benchside.config import Paths, resolve_content_root, resolve_paths
12
+ from benchside.domain.authoring.port.renderer import TemplateRenderer
13
+ from benchside.domain.authoring.port.repository import PersonaRepository, TemplateRepository
14
+ from benchside.domain.authoring.port.skill_writer import SkillWriter
15
+ from benchside.domain.consultation.port.repository import (
16
+ ConsultationRepository,
17
+ ProjectRepository,
18
+ )
19
+ from benchside.domain.export.port.redactor import Redactor
20
+ from benchside.domain.export.port.repository import ConsentRepository, ObservationReader
21
+ from benchside.domain.export.port.sink import ExportSink
22
+ from benchside.domain.shared.port.journal import Journal
23
+ from benchside.infrastructure.content.loader import FileTemplateRepository, YamlPersonaRepository
24
+ from benchside.infrastructure.content.renderer import PlaceholderRenderer
25
+ from benchside.infrastructure.content.writer import FileSkillWriter
26
+ from benchside.infrastructure.http_sink import COLLECTOR, HttpExportSink
27
+ from benchside.infrastructure.journal.projection import (
28
+ JournalConsentRepository,
29
+ JournalConsultationRepository,
30
+ JournalObservationReader,
31
+ JournalProjectRepository,
32
+ )
33
+ from benchside.infrastructure.journal.store import JsonlJournal
34
+ from benchside.infrastructure.placeholders import RefusingExportSink
35
+ from benchside.infrastructure.redaction import TextRedactor
36
+ from benchside.util.di import Provider, Scope
37
+
38
+
39
+ class FileProvider(Provider):
40
+ @provide(scope=Scope.APP)
41
+ def get_paths(self) -> Paths:
42
+ return resolve_paths()
43
+
44
+ @provide(scope=Scope.APP)
45
+ def get_journal(self, paths: Paths) -> Journal:
46
+ return JsonlJournal(paths)
47
+
48
+ @provide(scope=Scope.UOW)
49
+ def get_projects(self, journal: Journal) -> ProjectRepository:
50
+ return JournalProjectRepository(journal)
51
+
52
+ @provide(scope=Scope.UOW)
53
+ def get_consultations(self, journal: Journal) -> ConsultationRepository:
54
+ return JournalConsultationRepository(journal)
55
+
56
+ @provide(scope=Scope.UOW)
57
+ def get_observations(self, journal: Journal) -> ObservationReader:
58
+ return JournalObservationReader(journal)
59
+
60
+ @provide(scope=Scope.UOW)
61
+ def get_consent_repo(self, journal: Journal) -> ConsentRepository:
62
+ return JournalConsentRepository(journal)
63
+
64
+ @provide(scope=Scope.APP)
65
+ def get_personas(self) -> PersonaRepository:
66
+ return YamlPersonaRepository(resolve_content_root() / "personas")
67
+
68
+ @provide(scope=Scope.APP)
69
+ def get_templates(self) -> TemplateRepository:
70
+ return FileTemplateRepository(resolve_content_root() / "templates")
71
+
72
+ @provide(scope=Scope.APP)
73
+ def get_renderer(self, templates: TemplateRepository) -> TemplateRenderer:
74
+ return PlaceholderRenderer(templates)
75
+
76
+ @provide(scope=Scope.APP)
77
+ def get_skill_writer(self, paths: Paths) -> SkillWriter:
78
+ return FileSkillWriter(paths.skills_dir)
79
+
80
+ redactor = provide(TextRedactor, scope=Scope.APP, provides=Redactor)
81
+
82
+ @provide(scope=Scope.APP)
83
+ def get_sink(self) -> ExportSink:
84
+ endpoint = os.environ.get("BENCHSIDE_GAPS_ENDPOINT", f"{COLLECTOR}/v1/gaps")
85
+ return HttpExportSink(endpoint) if endpoint else RefusingExportSink()
@@ -0,0 +1,244 @@
1
+ """Journal projections: folding the event stream back into aggregates.
2
+
3
+ This is where event-sourcing actually happens. The domain's repository ports
4
+ hide it entirely -- a service asks for a Project and gets one, without knowing
5
+ it was rebuilt from a file of events.
6
+
7
+ Folds are cheap at this scale (a project accumulates hundreds of events, not
8
+ millions). If that stops being true, the answer is a snapshot cache behind the
9
+ same ports, not a change to the domain.
10
+ """
11
+
12
+ from benchside.domain.consultation.event.closed import ConsultationClosed
13
+ from benchside.domain.consultation.event.critique_raised import CritiqueRaised
14
+ from benchside.domain.consultation.event.critique_resolved import CritiqueResolved
15
+ from benchside.domain.consultation.event.decision_recorded import DecisionRecorded
16
+ from benchside.domain.consultation.event.gap_observed import GapObserved
17
+ from benchside.domain.consultation.event.hypothesis_stated import HypothesisStated
18
+ from benchside.domain.consultation.event.opened import ConsultationOpened
19
+ from benchside.domain.consultation.event.question import QuestionAnswered, QuestionRecorded
20
+ from benchside.domain.consultation.event.research_recorded import ResearchRecorded
21
+ from benchside.domain.consultation.model.consultation import Consultation
22
+ from benchside.domain.consultation.model.project import Project
23
+ from benchside.domain.consultation.model.value import (
24
+ Abandoned,
25
+ Converged,
26
+ Critique,
27
+ Decision,
28
+ Hypothesis,
29
+ )
30
+ from benchside.domain.export.event.consent_granted import ConsentGranted
31
+ from benchside.domain.export.event.consent_revoked import ConsentRevoked
32
+ from benchside.domain.export.event.observations_exported import ObservationsExported
33
+ from benchside.domain.export.model.ledger import ConsentLedger
34
+ from benchside.domain.export.model.value import ExportRecord, Grant, Observation
35
+ from benchside.domain.shared.model.ids import (
36
+ CONSENT_LEDGER_PROJECT,
37
+ ConsultationId,
38
+ ObservationId,
39
+ ProjectId,
40
+ )
41
+ from benchside.domain.shared.port.journal import Journal
42
+
43
+
44
+ class JournalProjectRepository:
45
+ """Rebuilds Projects from their journals.
46
+
47
+ A project's title is not yet carried by any event, so it falls back to the
48
+ id until a ProjectNamed event exists.
49
+ """
50
+
51
+ def __init__(self, journal: Journal) -> None:
52
+ self._journal = journal
53
+
54
+ def get(self, project_id: ProjectId) -> Project | None:
55
+ events = list(self._journal.read(project_id))
56
+ if not events:
57
+ return None
58
+ project = Project(id=project_id, title=project_id.root)
59
+ for event in events:
60
+ match event:
61
+ case QuestionRecorded():
62
+ project.questions.append(event.question)
63
+ case QuestionAnswered():
64
+ for i, question in enumerate(project.questions):
65
+ if question.id == event.question_id:
66
+ project.questions[i] = question.model_copy(update={"answer": event.answer})
67
+ break
68
+ case ResearchRecorded():
69
+ project.research_records.append(event.record)
70
+ case HypothesisStated():
71
+ project.hypotheses.append(
72
+ Hypothesis(
73
+ id=event.hypothesis_id,
74
+ statement=event.statement,
75
+ supersedes=event.supersedes,
76
+ )
77
+ )
78
+ case CritiqueRaised():
79
+ project.critiques.append(Critique(id=event.critique_id, target=event.target))
80
+ case CritiqueResolved():
81
+ for i, critique in enumerate(project.critiques):
82
+ if critique.id == event.critique_id:
83
+ project.critiques[i] = critique.model_copy(
84
+ update={"resolution": event.resolution}
85
+ )
86
+ break
87
+ case DecisionRecorded():
88
+ project.decisions.append(
89
+ Decision(
90
+ id=event.decision_id,
91
+ decision=event.decision,
92
+ rationale=event.rationale,
93
+ decided_at=event.recorded_at,
94
+ supersedes=event.supersedes,
95
+ )
96
+ )
97
+ return project
98
+
99
+ def list_all(self) -> list[Project]:
100
+ found = [self.get(pid) for pid in self._journal.projects()]
101
+ return [p for p in found if p is not None]
102
+
103
+
104
+ class JournalConsultationRepository:
105
+ """Rebuilds Consultations, including their state machine, from journals.
106
+
107
+ State is replayed rather than stored: open critiques at the time of the
108
+ last event determine whether a live sitting is probing or challenged.
109
+ """
110
+
111
+ def __init__(self, journal: Journal) -> None:
112
+ self._journal = journal
113
+
114
+ def get(self, consultation_id: ConsultationId) -> Consultation | None:
115
+ for project_id in self._journal.projects():
116
+ for consultation in self.list_for_project(project_id):
117
+ if consultation.id == consultation_id:
118
+ return consultation
119
+ return None
120
+
121
+ def list_for_project(self, project_id: ProjectId) -> list[Consultation]:
122
+ sittings: dict[str, Consultation] = {}
123
+ open_critiques: list[str] = []
124
+ for event in self._journal.read(project_id):
125
+ match event:
126
+ case ConsultationOpened():
127
+ # Ignore duplicate opens: replaying one must never replace
128
+ # (and thereby reset) an existing sitting (bug B3).
129
+ if event.consultation_id not in sittings:
130
+ sittings[event.consultation_id] = Consultation(
131
+ id=event.consultation_id,
132
+ project_id=event.project_id,
133
+ persona_id=event.persona_id,
134
+ close_requires=event.close_requires,
135
+ critique_requires_hypothesis=event.critique_requires_hypothesis,
136
+ record_kind=event.record_kind,
137
+ persona_version=event.persona_version,
138
+ host=event.host,
139
+ app_version=event.app_version,
140
+ surface=event.surface,
141
+ )
142
+ case HypothesisStated() if event.consultation_id in sittings:
143
+ sittings[event.consultation_id].probe()
144
+ case ResearchRecorded() if event.consultation_id in sittings:
145
+ sittings[event.consultation_id].probe()
146
+ case CritiqueRaised() if event.consultation_id in sittings:
147
+ open_critiques.append(event.critique_id)
148
+ sittings[event.consultation_id].settle(tuple(open_critiques))
149
+ case CritiqueResolved() if event.consultation_id in sittings:
150
+ if event.critique_id in open_critiques:
151
+ open_critiques.remove(event.critique_id)
152
+ sittings[event.consultation_id].settle(tuple(open_critiques))
153
+ case ConsultationClosed() if event.consultation_id in sittings:
154
+ sitting = sittings[event.consultation_id]
155
+ sitting.state = (
156
+ Converged(outcome=event.detail)
157
+ if event.state == "converged"
158
+ else Abandoned(reason=event.detail)
159
+ )
160
+ return list(sittings.values())
161
+
162
+ def latest_for_project(self, project_id: ProjectId) -> Consultation | None:
163
+ found = self.list_for_project(project_id)
164
+ return found[-1] if found else None
165
+
166
+
167
+ class JournalObservationReader:
168
+ """Reads captured gaps across every project.
169
+
170
+ Read-only cross-domain access: export never reaches into consultation's
171
+ aggregates, it folds the same events out of the shared journal.
172
+ """
173
+
174
+ def __init__(self, journal: Journal) -> None:
175
+ self._journal = journal
176
+
177
+ def list_all(self) -> list[Observation]:
178
+ found: list[Observation] = []
179
+ for project_id in self._journal.projects():
180
+ if project_id.root == CONSENT_LEDGER_PROJECT.root:
181
+ continue
182
+ for event in self._journal.read(project_id):
183
+ if isinstance(event, GapObserved):
184
+ found.append(
185
+ Observation(
186
+ id=event.observation_id,
187
+ project_id=event.project_id,
188
+ gap=event.gap,
189
+ )
190
+ )
191
+ return found
192
+
193
+ def list_unshared(self) -> list[Observation]:
194
+ return [o for o in self.list_all() if o.id not in self._already_shared()]
195
+
196
+ def _already_shared(self) -> set[ObservationId]:
197
+ shared: set[ObservationId] = set()
198
+ for event in self._journal.read(CONSENT_LEDGER_PROJECT):
199
+ if isinstance(event, ObservationsExported):
200
+ shared.update(event.observation_ids)
201
+ return shared
202
+
203
+
204
+ class JournalConsentRepository:
205
+ """Rebuilds the consent ledger from its own stream.
206
+
207
+ Consent is machine-wide rather than per project, so it lives under a
208
+ reserved project id.
209
+ """
210
+
211
+ def __init__(self, journal: Journal) -> None:
212
+ self._journal = journal
213
+
214
+ def load(self) -> ConsentLedger:
215
+ ledger = ConsentLedger()
216
+ for event in self._journal.read(CONSENT_LEDGER_PROJECT):
217
+ match event:
218
+ case ConsentGranted():
219
+ ledger.grants.append(
220
+ Grant(
221
+ id=event.grant_id,
222
+ gap_kinds=event.gap_kinds,
223
+ granted_at=event.recorded_at,
224
+ )
225
+ )
226
+ case ConsentRevoked():
227
+ for i, grant in enumerate(ledger.grants):
228
+ if grant.id == event.grant_id and grant.revoked_at is None:
229
+ ledger.grants[i] = grant.model_copy(
230
+ update={"revoked_at": event.recorded_at}
231
+ )
232
+ break
233
+ case ObservationsExported():
234
+ ledger.exports.append(
235
+ ExportRecord(
236
+ grant_id=event.grant_id,
237
+ observation_ids=event.observation_ids,
238
+ payload_sha256=event.payload_sha256,
239
+ exported_at=event.recorded_at,
240
+ destination=event.destination,
241
+ received_at=event.received_at,
242
+ )
243
+ )
244
+ return ledger
@@ -0,0 +1,24 @@
1
+ """Event registration.
2
+
3
+ `Event.__init_subclass__` populates the registry, so every event module must be
4
+ imported before a journal can be parsed. Importing them here keeps that
5
+ requirement in one place instead of scattered through the adapters.
6
+ """
7
+
8
+ import importlib
9
+
10
+ _EVENT_MODULES = (
11
+ "benchside.domain.consultation.event",
12
+ "benchside.domain.export.event",
13
+ )
14
+
15
+ _registered = False
16
+
17
+
18
+ def ensure_events_registered() -> None:
19
+ global _registered
20
+ if _registered:
21
+ return
22
+ for module in _EVENT_MODULES:
23
+ importlib.import_module(module)
24
+ _registered = True
@@ -0,0 +1,134 @@
1
+ """The JSONL journal: benchside's source of truth.
2
+
3
+ One append-only file per project. Every line is one event, tagged with its
4
+ class name so it can be parsed back into its concrete type. History is never
5
+ rewritten -- corrections are new events that supersede old ones.
6
+
7
+ Each append holds a per-journal file lock, flushes and syncs the write, and
8
+ restricts the file to its owner. App and CLI commands also hold an installation
9
+ transaction lock around read/validate/write operations.
10
+ """
11
+
12
+ import json
13
+ import logging
14
+ import os
15
+ from collections.abc import Iterable
16
+ from pathlib import Path
17
+
18
+ from benchside.config import Paths
19
+ from benchside.domain.shared.error import (
20
+ ConfigurationError,
21
+ StorageUnavailableError,
22
+ )
23
+ from benchside.domain.shared.event import Event
24
+ from benchside.domain.shared.model.ids import ProjectId
25
+ from benchside.infrastructure.files import file_lock
26
+ from benchside.infrastructure.journal.registry import ensure_events_registered
27
+ from benchside.infrastructure.session_context import current_provenance, current_session
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class JsonlJournal:
33
+ def __init__(self, paths: Paths) -> None:
34
+ root = paths.home.resolve()
35
+ if any((directory / ".git").exists() for directory in (root, *root.parents)):
36
+ raise ConfigurationError("Benchside journals must be stored outside Git")
37
+ self._paths = paths
38
+ self.readable_records_warning = None
39
+ ensure_events_registered()
40
+
41
+ def append(self, project_id: ProjectId, event: Event) -> None:
42
+ from benchside.infrastructure.storage_layout import organised
43
+
44
+ root = self._paths.store_root
45
+ if root and organised(root) and self._paths.home.resolve() != (root / "agent").resolve():
46
+ raise ConfigurationError("This store moved into agent; reopen Benchside before recording")
47
+ path = self._paths.journal_file(project_id.root)
48
+ try:
49
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
50
+ provenance = current_provenance()
51
+ if provenance is not None and hasattr(event, "consultation_id"):
52
+ event = event.model_copy(update={"provenance": provenance})
53
+ data = event.model_dump(mode="json")
54
+ if not hasattr(event, "consultation_id") or event.provenance is None:
55
+ data.pop("provenance", None)
56
+ line = json.dumps(
57
+ {
58
+ "type": type(event).__name__,
59
+ "session": current_session(self._paths, project_id),
60
+ "data": data,
61
+ },
62
+ ensure_ascii=False,
63
+ )
64
+ with file_lock(path.with_suffix(".lock")), path.open("a", encoding="utf-8") as handle:
65
+ os.chmod(path, 0o600)
66
+ handle.write(line + "\n")
67
+ handle.flush()
68
+ os.fsync(handle.fileno())
69
+ except OSError as err:
70
+ raise StorageUnavailableError(f"Could not append to journal at {path}: {err}") from err
71
+
72
+ from benchside.infrastructure.readable_refresh import mark_readable
73
+
74
+ mark_readable(self._paths, self, project_id.root)
75
+
76
+ def read(self, project_id: ProjectId) -> Iterable[Event]:
77
+ path = self._paths.journal_file(project_id.root)
78
+ if not path.exists():
79
+ return []
80
+ return list(self._parse(path))
81
+
82
+ def read_envelopes(self, project_id: ProjectId) -> Iterable[dict]:
83
+ """Raw journal lines as dicts — type, session, data. For views and
84
+ analysis that need the session linkage the domain Event doesn't carry."""
85
+ path = self._paths.journal_file(project_id.root)
86
+ if not path.exists():
87
+ return []
88
+ envelopes = []
89
+ for number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
90
+ raw = raw.strip()
91
+ if not raw:
92
+ continue
93
+ try:
94
+ record = json.loads(raw)
95
+ if not isinstance(record, dict):
96
+ raise TypeError("Journal envelope must be an object")
97
+ record.setdefault("session", None)
98
+ envelopes.append(record)
99
+ except (ValueError, TypeError, AttributeError) as err:
100
+ self._log_unreadable(path, number, err)
101
+ return envelopes
102
+
103
+ def projects(self) -> Iterable[ProjectId]:
104
+ root = self._paths.journal_dir
105
+ if not root.exists():
106
+ return []
107
+ return [ProjectId(d.name) for d in sorted(root.iterdir()) if (d / "journal.jsonl").exists()]
108
+
109
+ def _parse(self, path: Path) -> Iterable[Event]:
110
+ """Skip unparseable lines rather than failing the whole read.
111
+
112
+ A single corrupt line must not make a scientist's entire project
113
+ unreadable. Skips are logged so they are not silent.
114
+ """
115
+ with path.open(encoding="utf-8") as handle:
116
+ for number, raw in enumerate(handle, start=1):
117
+ raw = raw.strip()
118
+ if not raw:
119
+ continue
120
+ try:
121
+ record = json.loads(raw)
122
+ if not isinstance(record, dict):
123
+ raise TypeError("Journal envelope must be an object")
124
+ event_type = Event.resolve(record["type"])
125
+ yield event_type.model_validate(record["data"])
126
+ except (KeyError, ValueError, TypeError, AttributeError) as err:
127
+ self._log_unreadable(path, number, err)
128
+
129
+ @staticmethod
130
+ def _log_unreadable(path: Path, number: int, error: Exception) -> None:
131
+ # Validation errors can contain research text. Log location and category only.
132
+ logger.warning(
133
+ "Skipping unreadable journal line %s:%d (%s)", path, number, type(error).__name__
134
+ )
@@ -0,0 +1,28 @@
1
+ """Deliberate production placeholders.
2
+
3
+ These are not test fakes: they are the safe defaults the container ships with
4
+ until the real implementations exist. The refusing sink is a security
5
+ property — the default wiring must not be able to leak.
6
+ """
7
+
8
+ from benchside.domain.export.port.redactor import Finding
9
+ from benchside.domain.shared.error import ConfigurationError
10
+
11
+
12
+ class PassthroughRedactor:
13
+ """No redaction yet. The export preview labels this state explicitly."""
14
+
15
+ def scan(self, payload: str) -> list[Finding]:
16
+ return []
17
+
18
+ def apply(self, payload: str) -> str:
19
+ return payload
20
+
21
+
22
+ class RefusingExportSink:
23
+ """Refuses to send anything until a real sink is configured explicitly."""
24
+
25
+ destination = "disabled"
26
+
27
+ def send(self, payload: str) -> None:
28
+ raise ConfigurationError("No export sink is configured; nothing was sent")