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,54 @@
1
+ ---
2
+ name: {{PERSONA_ID}}
3
+ description: >
4
+ {{PERSONA_DESCRIPTION}}
5
+ allowed-tools: "Bash(bench *)"
6
+ ---
7
+
8
+ # /{{PERSONA_ID}} — {{PERSONA_TITLE}}
9
+
10
+ ## Who you are
11
+
12
+ {{PERSONA_STANCE}}
13
+
14
+ Expertise: {{PERSONA_EXPERTISE}}.
15
+
16
+ **Voice.** {{PERSONA_VOICE}}
17
+
18
+ {{SOVEREIGNTY}}
19
+
20
+ {{CAPTURE_CONTRACT}}
21
+
22
+ ## The meeting
23
+
24
+ Work the phases in order. One question at a time — ask, then stop and wait.
25
+ Adapt to what the scientist has already supplied. Do not invent a hypothesis,
26
+ an objection or a reference to satisfy a phase. Distinguish observations,
27
+ interpretations, proposals and the scientist's decisions.
28
+
29
+ {{FLOW}}
30
+
31
+ ## Forcing questions
32
+
33
+ Use these when a clarification would change the discussion. Ask one at a time,
34
+ use what is already known, and respect the escalation rules and declined questions.
35
+
36
+ {{FORCING_QUESTIONS}}
37
+
38
+ ## Escalation rules
39
+
40
+ {{ESCALATION_RULES}}
41
+
42
+ ## Never do this
43
+
44
+ Each of these is a named failure mode this persona is evaluated against:
45
+
46
+ {{FAILURE_MODES}}
47
+
48
+ ## Ending
49
+
50
+ Before closing, run `bench sitting status`. Close converged when the scientist
51
+ has agreed the output and next step. If they pause, leave the sitting open for
52
+ resumption. Close abandoned only when they explicitly stop the work. The sitting id marker
53
+ (`<bench-sitting:...>`) printed at open
54
+ belongs in your first message so the record is recoverable.
File without changes
@@ -0,0 +1,458 @@
1
+ """Structured app adapter. The assistant calls this; scientists need no terminal.
2
+
3
+ Storage is a provider/user-owned durable directory, never a Git repository.
4
+ Cloud hosts must prove that the same directory survives a new conversation;
5
+ an ephemeral execution sandbox is deliberately not certified as durable memory.
6
+ """
7
+
8
+ import hashlib
9
+ import json
10
+ import uuid
11
+
12
+ from pydantic import TypeAdapter
13
+
14
+ from benchside.application.sharing import SharingFlow
15
+ from benchside.config import Paths, resolve_content_root
16
+ from benchside.domain.consultation.model.value import ResearchRecord, Resolution, Target
17
+ from benchside.domain.consultation.query.recall_project import RecallProject, RecallProjectHandler
18
+ from benchside.domain.consultation.service.consultation import ConsultationService
19
+ from benchside.domain.export.model.reporting import AppVersion
20
+ from benchside.domain.shared.error import BenchsideError, InvalidStateError, ValidationError
21
+ from benchside.domain.shared.model.gap import Gap
22
+ from benchside.domain.shared.model.ids import PersonaId, user_project_id
23
+ from benchside.domain.shared.model.provenance import AppProvenance
24
+ from benchside.infrastructure.content.loader import YamlPersonaRepository
25
+ from benchside.infrastructure.files import atomic_json, file_lock
26
+ from benchside.infrastructure.journal.projection import (
27
+ JournalConsultationRepository,
28
+ JournalProjectRepository,
29
+ )
30
+ from benchside.infrastructure.journal.store import JsonlJournal
31
+ from benchside.infrastructure.session_context import recording_context
32
+
33
+ READ_ACTIONS = {
34
+ "recall",
35
+ "records.export",
36
+ "records.preferences",
37
+ "roles",
38
+ "projects",
39
+ "profile.status",
40
+ "participation.status",
41
+ "sharing.status",
42
+ "sharing.history",
43
+ "storage.check",
44
+ "metascience.status",
45
+ "metascience.history",
46
+ "metascience.batch",
47
+ }
48
+
49
+
50
+ class App:
51
+ def __init__(self, paths: Paths):
52
+ self.paths = paths
53
+ self.journal = JsonlJournal(paths)
54
+ self.consultations = JournalConsultationRepository(self.journal)
55
+ self.service = ConsultationService(
56
+ projects=JournalProjectRepository(self.journal),
57
+ consultations=self.consultations,
58
+ journal=self.journal,
59
+ )
60
+ self.personas = YamlPersonaRepository(resolve_content_root() / "personas")
61
+
62
+ def run(self, request: dict):
63
+ action = request.get("action")
64
+ if not isinstance(action, str):
65
+ raise ValidationError("An app action is required")
66
+ try:
67
+ self._storage_boundary()
68
+ if action == "storage.organise":
69
+ from benchside.infrastructure.storage_layout import organise
70
+
71
+ if self.paths.store_root is None:
72
+ raise ValidationError("Folder organisation is only available for durable local storage")
73
+ result = organise(self.paths.store_root, request.get("confirm_idle", False))
74
+ from benchside.config import local_paths
75
+ from benchside.infrastructure.readable_records import export_project
76
+
77
+ refreshed = App(local_paths(self.paths.store_root, self.paths.repo_root))
78
+ projects = {p.root for p in refreshed.journal.projects()} | {
79
+ p.stem for p in (refreshed.paths.home / "app-projects").glob("p-*.json")
80
+ }
81
+ count = 0
82
+ with file_lock(refreshed.paths.home / ".transaction.lock"):
83
+ for project in sorted(projects - {"consent-ledger", "reporting-ledger"}):
84
+ try:
85
+ export_project(refreshed.paths, refreshed.journal, project)
86
+ count += 1
87
+ except Exception: # noqa: BLE001 - migration succeeded; derived copy can retry
88
+ result["readable_records_warning"] = "Folder organisation succeeded; some readable copies need records.export to be retried."
89
+ return {**result, "readable_projects": count}
90
+ with file_lock(self.paths.home / ".transaction.lock"):
91
+ from benchside.infrastructure.readable_refresh import readable_refresh
92
+
93
+ self._storage_boundary()
94
+ self.journal.readable_records_warning = None
95
+ with readable_refresh() as readable:
96
+ result = self._dispatch(action, request)
97
+ if action == "setup":
98
+ readable.mark(self.paths, self.journal, result["project_id"])
99
+ if action == "setup":
100
+ exported = readable.results.get((self.paths.home.resolve(), result["project_id"]))
101
+ if exported:
102
+ result["readable_records"] = exported
103
+ if isinstance(result, dict) and readable.warning:
104
+ result["readable_records_warning"] = readable.warning
105
+ return result
106
+ except BenchsideError as error:
107
+ self._failure(action, error)
108
+ raise
109
+ except (KeyError, TypeError, ValueError) as err:
110
+ self._failure(action, err)
111
+ raise ValidationError(f"Invalid {action} request: {err}") from err
112
+
113
+ def _failure(self, action, error):
114
+ if (
115
+ action in READ_ACTIONS
116
+ or action.startswith(
117
+ ("sharing.", "storage.", "metascience.", "profile.", "participation.", "records.")
118
+ )
119
+ or action == "setup"
120
+ ):
121
+ return
122
+ from benchside.domain.export.service.reporting import ReportingService
123
+ from benchside.domain.shared.error import StorageUnavailableError
124
+
125
+ code = (
126
+ "recording_unavailable"
127
+ if isinstance(error, (StorageUnavailableError, OSError))
128
+ else "recording_invalid"
129
+ )
130
+ try:
131
+ with file_lock(self.paths.home / ".transaction.lock"):
132
+ ReportingService(journal=self.journal).failure(code)
133
+ except (BenchsideError, OSError):
134
+ pass # A reporting failure must not mask the scientific-record failure.
135
+
136
+ def _storage_boundary(self):
137
+ from benchside.infrastructure.storage_layout import organised
138
+
139
+ root = self.paths.store_root
140
+ if root and organised(root) and self.paths.home.resolve() != (root / "agent").resolve():
141
+ raise InvalidStateError("This store moved into agent; reopen Benchside before recording")
142
+ home = self.paths.home.resolve()
143
+ if any((directory / ".git").exists() for directory in (home, *home.parents)):
144
+ raise InvalidStateError("Benchside's journal must be stored outside Git")
145
+
146
+ def _dispatch(self, action, request):
147
+ if action in {"records.preferences", "records.configure"}:
148
+ from benchside.infrastructure.readable_records import configure, preferences
149
+
150
+ return preferences(self.paths) if action == "records.preferences" else configure(self.paths, request["format"])
151
+ if action.startswith("metascience."):
152
+ from benchside.application.metascience import Metascience
153
+
154
+ return Metascience(self.paths).dispatch(request)
155
+ if action == "storage.probe":
156
+ token = uuid.uuid4().hex
157
+ atomic_json(self.paths.home / "app-probe.json", {"token": token})
158
+ return {
159
+ "token": token,
160
+ "storage": str(self.paths.store_root or self.paths.home),
161
+ "agent": str(self.paths.home),
162
+ "status": "written",
163
+ "next": "In a new conversation, call storage.check with this token.",
164
+ }
165
+ if action == "storage.check":
166
+ probe = self.paths.home / "app-probe.json"
167
+ return {
168
+ "matched": probe.exists()
169
+ and json.loads(probe.read_text()).get("token") == request["token"],
170
+ "storage": str(self.paths.store_root or self.paths.home),
171
+ "agent": str(self.paths.home),
172
+ "note": "A same-process or same-sandbox check does not prove cross-chat persistence.",
173
+ }
174
+ if action == "projects":
175
+ return [
176
+ {
177
+ "project_id": path.stem,
178
+ "title": json.loads(path.read_text()).get("title", path.stem),
179
+ }
180
+ for path in sorted((self.paths.home / "app-projects").glob("p-*.json"))
181
+ ]
182
+ if action == "roles":
183
+ return [
184
+ {
185
+ "id": p.id.root,
186
+ "title": p.title,
187
+ "description": p.description,
188
+ "record_kind": p.record_kind,
189
+ "version": p.version,
190
+ }
191
+ for p in self.personas.list_all()
192
+ ]
193
+ if action == "profile.status":
194
+ return SharingFlow(self.paths).profile().model_dump(mode="json")
195
+ if action == "participation.status":
196
+ return SharingFlow(self.paths).participation().model_dump(mode="json")
197
+ if action == "participation.set":
198
+ return SharingFlow(self.paths).set_participation(request["response"])
199
+ if action == "profile.set":
200
+ return SharingFlow(self.paths).set_profile(
201
+ request["demographics"], request["include_in_usage"]
202
+ )
203
+ if action.startswith("sharing."):
204
+ flow = SharingFlow(self.paths)
205
+ match action:
206
+ case "sharing.status":
207
+ return flow.status()
208
+ case "sharing.consent":
209
+ if type(request.get("enabled")) is not bool:
210
+ raise ValidationError("Consent enabled must be true or false")
211
+ flow.set_consent(
212
+ request["channel"], request["enabled"], kinds=request.get("kinds")
213
+ )
214
+ return flow.status()
215
+ case "sharing.feedback":
216
+ return flow.feedback(**request["feedback"]).model_dump(mode="json")
217
+ case "sharing.preview":
218
+ return [
219
+ d.model_dump(mode="json")
220
+ for d in flow.prepare(
221
+ request["channel"],
222
+ only=request.get("only"),
223
+ edits=request.get("edits"),
224
+ feedback_id=request.get("feedback_id"),
225
+ comment=request.get("comment"),
226
+ week=request.get("week"),
227
+ )
228
+ ]
229
+ case "sharing.send":
230
+ return flow.send(request["draft_id"], request["approved_sha256"]).model_dump(
231
+ mode="json"
232
+ )
233
+ case "sharing.history":
234
+ return flow.history()
235
+ raise ValidationError("Unknown sharing action")
236
+ if action == "setup":
237
+ # Stable host project identity, not a title that can be renamed or collide.
238
+ host = request.get("host", "unknown")
239
+ app_version = TypeAdapter(AppVersion).validate_python(
240
+ request.get("app_version", "unknown")
241
+ )
242
+ surface = request.get("surface", "unknown")
243
+ if host not in {"chatgpt", "claude", "unknown"} or surface not in {
244
+ "web",
245
+ "desktop",
246
+ "cli",
247
+ "unknown",
248
+ }:
249
+ raise ValidationError("Unknown app or surface")
250
+ title = request.get("title")
251
+ if title is not None and (
252
+ not isinstance(title, str)
253
+ or not 1 <= len(title) <= 160
254
+ or any(ord(char) < 32 for char in title)
255
+ ):
256
+ raise ValidationError("Use a project title of 1–160 printable characters")
257
+ selected = request.get("project_id")
258
+ if selected:
259
+ project_id = user_project_id(selected).root
260
+ config = self.paths.home / "app-projects" / f"{project_id}.json"
261
+ if not config.is_file():
262
+ raise InvalidStateError(
263
+ "Choose an existing project from projects or create a new one"
264
+ )
265
+ if title is not None:
266
+ identity = json.loads(config.read_text())
267
+ identity["title"] = title
268
+ atomic_json(config, identity)
269
+ else:
270
+ key = request.get("project_key")
271
+ if not isinstance(key, str) or not key.strip():
272
+ raise ValidationError("A stable project ID or local folder path is required")
273
+ project_id = "p-" + hashlib.sha256(f"{host}:{key}".encode()).hexdigest()[:32]
274
+ config = self.paths.home / "app-projects" / f"{project_id}.json"
275
+ if not config.exists():
276
+ identity = {"host": host, "app_version": app_version, "surface": surface}
277
+ if title is not None:
278
+ identity["title"] = title
279
+ atomic_json(config, identity)
280
+ # Creation identity is immutable. Each caller gets its own app context,
281
+ # so another agent opening the same project cannot relabel this session.
282
+ session_id = uuid.uuid4().hex
283
+ atomic_json(
284
+ self.paths.home / "app-sessions" / f"{session_id}.json",
285
+ {
286
+ "project_id": project_id,
287
+ "host": host,
288
+ "app_version": app_version,
289
+ "surface": surface,
290
+ },
291
+ )
292
+ return {
293
+ "project_id": project_id,
294
+ "session_id": session_id,
295
+ "sharing": SharingFlow(self.paths).status(),
296
+ }
297
+
298
+ project_id = user_project_id(request["project_id"])
299
+ project_config = self.paths.home / "app-projects" / f"{project_id.root}.json"
300
+ if not project_config.exists():
301
+ raise InvalidStateError("Set up this app project before recording")
302
+ config = json.loads(project_config.read_text())
303
+ recall = RecallProjectHandler(consultation_service=self.service)
304
+ project_title = config.get("title")
305
+
306
+ def recalled():
307
+ result = recall.run(
308
+ RecallProject(
309
+ project_id=project_id,
310
+ history=request.get("history", "recent") if action == "recall" else "recent",
311
+ )
312
+ ).model_dump(mode="json")
313
+ if project_title:
314
+ result["title"] = project_title
315
+ return result
316
+
317
+ if action == "records.export":
318
+ from benchside.infrastructure.readable_records import export_project
319
+
320
+ return export_project(self.paths, self.journal, project_id.root)
321
+ if action == "recall":
322
+ return recalled()
323
+ session = request.get("session_id")
324
+ from benchside.infrastructure.session_context import validate_session_id
325
+
326
+ if not session:
327
+ raise ValidationError("Use the session_id returned by setup for recording")
328
+ validate_session_id(session)
329
+ session_file = self.paths.home / "app-sessions" / f"{session}.json"
330
+ if not session_file.is_file():
331
+ raise InvalidStateError("This session is missing; run setup to resume the project")
332
+ config = json.loads(session_file.read_text())
333
+ if config["project_id"] != project_id.root:
334
+ raise InvalidStateError("This session belongs to another project")
335
+ with recording_context(
336
+ session_id=session,
337
+ provenance=AppProvenance(
338
+ host=config["host"],
339
+ app_version=config.get("app_version", "unknown"),
340
+ surface=config["surface"],
341
+ ),
342
+ ):
343
+ if action == "start":
344
+ persona = self.personas.get(PersonaId(request["role"]))
345
+ if persona is None:
346
+ raise ValidationError("Unknown research role")
347
+ new_sitting = request.get("new_sitting", False)
348
+ if type(new_sitting) is not bool:
349
+ raise ValidationError("new_sitting must be true or false")
350
+ if new_sitting and request.get("sitting_id"):
351
+ raise ValidationError("Choose a sitting_id or new_sitting, not both")
352
+ candidates = [] if new_sitting else [
353
+ sitting
354
+ for sitting in self.consultations.list_for_project(project_id)
355
+ if sitting.persona_id == persona.id
356
+ and sitting.state.kind not in {"converged", "abandoned"}
357
+ ]
358
+ selected = request.get("sitting_id")
359
+ if selected:
360
+ candidates = [s for s in candidates if s.id == selected]
361
+ if not candidates:
362
+ raise ValidationError("That sitting is not open for this project and role")
363
+ if len(candidates) > 1:
364
+ raise InvalidStateError(
365
+ "Several sittings are open for this role; choose a sitting_id from recall"
366
+ )
367
+ sitting = (
368
+ candidates[0]
369
+ if candidates
370
+ else self.service.open(
371
+ consultation_id=f"c-{uuid.uuid4().hex}",
372
+ project_id=project_id,
373
+ persona_id=persona.id,
374
+ close_requires=persona.flow.close_requires,
375
+ critique_requires_hypothesis=persona.critique_requires_hypothesis,
376
+ record_kind=persona.record_kind,
377
+ persona_version=persona.version,
378
+ host=config["host"],
379
+ app_version=config.get("app_version", "unknown"),
380
+ surface=config["surface"],
381
+ )
382
+ )
383
+ return {
384
+ "sitting": sitting.model_dump(mode="json"),
385
+ "role_update_available": sitting.persona_version != persona.version,
386
+ "recall": recalled(),
387
+ }
388
+ sitting = self.service.get(request["sitting_id"])
389
+ if sitting.project_id != project_id:
390
+ raise InvalidStateError("A sitting from another project cannot be used here")
391
+ sitting._require_live()
392
+ identifier = uuid.uuid4().hex
393
+ common = {"consultation_id": sitting.id}
394
+ match action:
395
+ case "question":
396
+ from benchside.domain.consultation.model.value import ResearchQuestion
397
+
398
+ question = ResearchQuestion(id=f"q-{identifier}", question=request["question"])
399
+ self.service.record_question(**common, question=question)
400
+ identifier = question.id
401
+ case "answer":
402
+ identifier = request["question_id"]
403
+ self.service.answer_question(**common, question_id=identifier, answer=request["answer"])
404
+ case "record":
405
+ record = ResearchRecord(id=f"r-{identifier}", **request["record"])
406
+ self.service.record_research(**common, record=record)
407
+ identifier = record.id
408
+ case "hypothesis":
409
+ identifier = f"h-{identifier}"
410
+ self.service.state_hypothesis(
411
+ **common,
412
+ hypothesis_id=identifier,
413
+ statement=request["statement"],
414
+ supersedes=request.get("supersedes"),
415
+ )
416
+ case "critique":
417
+ identifier = f"k-{identifier}"
418
+ self.service.raise_critique(
419
+ **common,
420
+ critique_id=identifier,
421
+ target=TypeAdapter(Target).validate_python(request["target"]),
422
+ )
423
+ case "resolve":
424
+ identifier = request["critique_id"]
425
+ self.service.resolve_critique(
426
+ **common,
427
+ critique_id=identifier,
428
+ resolution=Resolution(request["resolution"]),
429
+ )
430
+ case "decide":
431
+ identifier = f"d-{identifier}"
432
+ self.service.record_decision(
433
+ **common,
434
+ decision_id=identifier,
435
+ decision=request["decision"],
436
+ rationale=request["rationale"],
437
+ supersedes=request.get("supersedes"),
438
+ )
439
+ case "gap":
440
+ identifier = f"o-{identifier}"
441
+ self.service.capture_gap(
442
+ **common,
443
+ observation_id=identifier,
444
+ gap=TypeAdapter(Gap).validate_python(request["gap"]),
445
+ )
446
+ case "close":
447
+ if type(request.get("converged")) is not bool:
448
+ raise ValidationError("converged must be true or false")
449
+ self.service.close(
450
+ **common, converged=request["converged"], detail=request["detail"]
451
+ )
452
+ identifier = sitting.id
453
+ case _:
454
+ raise ValidationError("Unknown app action")
455
+ return {
456
+ "recorded": identifier,
457
+ "recall": recalled(),
458
+ }
@@ -0,0 +1,55 @@
1
+ """One JSON protocol for source installs and packaged app runtimes."""
2
+
3
+ import json
4
+ import sys
5
+
6
+ from benchside.application.app import App
7
+ from benchside.config import configure_local_storage, resolve_paths
8
+
9
+
10
+ def run(request):
11
+ if not isinstance(request, dict) or not isinstance(request.get("action"), str):
12
+ raise TypeError("Provide a JSON object with an action")
13
+ if request["action"] == "version":
14
+ from benchside import __version__
15
+
16
+ return {"version": __version__}
17
+ if request["action"] == "connection.check":
18
+ from benchside.application.metascience import StudyClient
19
+ from benchside.domain.shared.error import InfrastructureError
20
+ from benchside.infrastructure.http_sink import COLLECTOR
21
+
22
+ endpoint = f"{COLLECTOR}/v1/studies"
23
+ try:
24
+ StudyClient(endpoint).fetch()
25
+ except InfrastructureError as error:
26
+ raise InfrastructureError(
27
+ "Collector reachability could not be verified; no contribution was submitted. "
28
+ "Private research work can continue."
29
+ ) from error
30
+ return {"reachable": True, "endpoint": endpoint, "method": "GET", "submitted": False}
31
+ if request["action"].startswith("native."):
32
+ from benchside.application.native import run_native
33
+
34
+ return run_native(request)
35
+ if request["action"] == "storage.configure":
36
+ return configure_local_storage(request["directory"])
37
+ if request["action"] == "storage.location":
38
+ paths = resolve_paths()
39
+ return {"storage": str(paths.store_root or paths.home), "agent": str(paths.home),
40
+ "researcher": str((paths.store_root or paths.home) / "researcher")}
41
+ return App(resolve_paths()).run(request)
42
+
43
+
44
+ def main():
45
+ try:
46
+ result = run(json.load(sys.stdin))
47
+ print(json.dumps({"ok": True, "result": result}, ensure_ascii=False))
48
+ return 0
49
+ except Exception as error: # noqa: BLE001 - JSON process boundary, including IO failures.
50
+ print(
51
+ json.dumps(
52
+ {"ok": False, "error": str(error), "code": getattr(error, "code", "setup_failed")}
53
+ )
54
+ )
55
+ return 1
@@ -0,0 +1,39 @@
1
+ """One random contributor identifier per private store; no account identifiers."""
2
+
3
+ import json
4
+ import re
5
+ import uuid
6
+ from typing import Annotated, Literal
7
+
8
+ from pydantic import Field, StringConstraints
9
+
10
+ from benchside.domain.export.model.reporting import StrictValue
11
+ from benchside.domain.shared.error import ValidationError
12
+ from benchside.infrastructure.files import atomic_json
13
+
14
+ POLICY = "pseudonymous-contributions-1"
15
+
16
+
17
+ class ContributionPolicy(StrictValue):
18
+ policy: Literal["pseudonymous-contributions-1"] = POLICY
19
+ grants: dict[
20
+ Literal["gaps", "feedback", "usage"],
21
+ Annotated[str, StringConstraints(min_length=1, max_length=100)],
22
+ ] = Field(default_factory=dict)
23
+
24
+
25
+ def contributor_id(paths):
26
+ path = paths.home / "reporting/installation.json"
27
+ if path.exists():
28
+ try:
29
+ value = json.loads(path.read_text())["id"]
30
+ except (OSError, ValueError, TypeError, KeyError) as error:
31
+ raise ValidationError(
32
+ "Invalid contributor identifier; preserve and repair this store"
33
+ ) from error
34
+ if not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{32}", value):
35
+ raise ValidationError("Invalid contributor identifier; preserve and repair this store")
36
+ return value
37
+ value = uuid.uuid4().hex
38
+ atomic_json(path, {"id": value})
39
+ return value
@@ -0,0 +1,35 @@
1
+ """The composition root.
2
+
3
+ The only place that knows every provider. Domain providers bind services and
4
+ handlers; infrastructure providers bind ports to implementations. Later
5
+ providers override earlier ones for the same type, which is how tests
6
+ substitute fakes:
7
+
8
+ container = create_container(FakeJournalProvider())
9
+ """
10
+
11
+ from dishka import Container, make_container
12
+ from dishka import Provider as DishkaProvider
13
+
14
+ from benchside.domain.authoring.util.di import AuthoringProvider
15
+ from benchside.domain.consultation.util.di import ConsultationProvider
16
+ from benchside.domain.export.util.di import ExportProvider
17
+ from benchside.infrastructure.journal.di import FileProvider
18
+ from benchside.util.di import Scope
19
+
20
+
21
+ def create_container(*extra_providers: DishkaProvider) -> Container:
22
+ """Build the container.
23
+
24
+ Args:
25
+ extra_providers: Appended after the defaults. Use `override=True` on a
26
+ provision to replace a default binding.
27
+ """
28
+ return make_container(
29
+ FileProvider(),
30
+ ConsultationProvider(),
31
+ AuthoringProvider(),
32
+ ExportProvider(),
33
+ *extra_providers,
34
+ scopes=Scope, # type: ignore[arg-type]
35
+ )