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,1088 @@
1
+ """Portable native-document memory, independent of an execution sandbox.
2
+
3
+ The host reads/writes the private document with its own authorized tools. This
4
+ module validates and runs a transaction in a disposable directory and returns a
5
+ candidate snapshot. Only guarded host save + readback confirms persistence.
6
+ Compression is for document size, not encryption or anonymisation.
7
+ """
8
+
9
+ import base64
10
+ import copy
11
+ import hashlib
12
+ import json
13
+ import re
14
+ import tempfile
15
+ import uuid
16
+ import zlib
17
+ from pathlib import Path
18
+
19
+ from benchside.application.app import READ_ACTIONS, App
20
+ from benchside.application.sharing import ParticipationChoice, SharingFlow, SubmissionDraft
21
+ from benchside.config import Paths
22
+ from benchside.domain.export.model.metascience import MetaState
23
+ from benchside.domain.export.model.reporting import ResearchProfile, UsagePayload
24
+ from benchside.domain.shared.error import BenchsideError, ValidationError
25
+ from benchside.domain.shared.event import Event
26
+ from benchside.infrastructure.journal.registry import ensure_events_registered
27
+ from benchside.infrastructure.session_context import validate_session_id
28
+
29
+ SCHEMA = "benchside.native.v1"
30
+ CHECKPOINT_SCHEMA = "benchside.native.v2"
31
+ CONTEXT_SCHEMA = "benchside.native.v3"
32
+ RESEARCH_SCHEMA = "benchside.native.v4"
33
+ SCHEMA_ORDER = (SCHEMA, CHECKPOINT_SCHEMA, CONTEXT_SCHEMA, RESEARCH_SCHEMA)
34
+ MAX_DOCUMENT_BYTES = 190_000 # Fits one native Pages edit with room for transport metadata.
35
+ MAX_METASCIENCE_DOCUMENT_BYTES = 48 * 1024
36
+ MAX_STATE_BYTES = 8 * 1024 * 1024
37
+ # Ordinary writes leave room to withdraw consent even when recording is full.
38
+ DOCUMENT_CONTROL_RESERVE = 16 * 1024
39
+ STATE_CONTROL_RESERVE = 64 * 1024
40
+ MAX_REPLAY_CACHE_BYTES = 32 * 1024
41
+ MAX_COMPACT_RESULT_BYTES = 4 * 1024
42
+ MAX_OPERATION_RECEIPTS = 128
43
+ MAX_OPERATION_INDEX_BYTES = 64 * 1024
44
+ RETAIN_OPERATION_RECEIPTS = 64
45
+ PROJECT = r"p-[a-f0-9]{32}"
46
+ FILE = re.compile(
47
+ rf"(?:app-projects/{PROJECT}\.json|app-sessions/[a-f0-9]{{32}}\.json|"
48
+ rf"projects/(?:{PROJECT}|consent-ledger|reporting-ledger)/journal\.jsonl|"
49
+ r"sharing/drafts/[a-f0-9]{32}\.json|"
50
+ r"reporting/(?:installation|profile|participation|contributions|usage-\d{4}-\d{2}-\d{2})\.json|metascience/state\.json)"
51
+ )
52
+ HEX = re.compile(r"[a-f0-9]{32}")
53
+ OPERATION = re.compile(r"(?:g([1-9][0-9]{0,9})-)?[a-f0-9]{32}")
54
+
55
+
56
+ def _json(value):
57
+ return json.dumps(
58
+ value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False
59
+ )
60
+
61
+
62
+ def _digest(value):
63
+ return hashlib.sha256(_json(value).encode("utf-8")).hexdigest()
64
+
65
+
66
+ def _pairs(pairs):
67
+ result = {}
68
+ for key, value in pairs:
69
+ if key in result:
70
+ raise ValueError("Duplicate JSON key")
71
+ result[key] = value
72
+ return result
73
+
74
+
75
+ def _loads(text):
76
+ return json.loads(text, object_pairs_hook=_pairs)
77
+
78
+
79
+ def _fail(message):
80
+ raise ValidationError(message, code="native_storage_invalid")
81
+
82
+
83
+ def _update_required():
84
+ raise ValidationError(
85
+ "This notebook contains records from a newer Benchside version. Update the installed "
86
+ "Benchside package, then reread this same notebook; do not delete, replace or skip records.",
87
+ code="native_update_required",
88
+ )
89
+
90
+
91
+ def _capacity_error():
92
+ raise ValidationError(
93
+ "Native notebook capacity is exhausted; nothing new should be submitted. "
94
+ "Preserve this notebook and arrange archival or larger storage. Consent withdrawal "
95
+ "can use reserved space; do not truncate scientific history.",
96
+ code="native_capacity",
97
+ )
98
+
99
+
100
+ def _check_files(files):
101
+ ensure_events_registered()
102
+ if not isinstance(files, dict):
103
+ _fail("Native memory files must be an object")
104
+ for name, text in files.items():
105
+ if not FILE.fullmatch(name) or not isinstance(text, str):
106
+ _fail("Native memory contains an unsupported file")
107
+ if name.endswith("journal.jsonl"):
108
+ project = name.split("/")[1]
109
+ for line in text.splitlines():
110
+ if not line.strip():
111
+ continue
112
+ envelope = _loads(line)
113
+ if set(envelope) != {"type", "session", "data"}:
114
+ _fail("Native journal envelope is incomplete")
115
+ if envelope["session"] is not None:
116
+ validate_session_id(envelope["session"])
117
+ try:
118
+ event_type = Event.resolve(envelope["type"])
119
+ except KeyError:
120
+ _update_required()
121
+ if set(envelope["data"]) - set(event_type.model_fields):
122
+ _update_required()
123
+ event_type.model_validate(envelope["data"])
124
+ if "project_id" in envelope["data"] and envelope["data"]["project_id"] != project:
125
+ _fail("Native journal event belongs to another project")
126
+ elif name == "reporting/profile.json":
127
+ ResearchProfile.model_validate_json(text)
128
+ elif name == "reporting/participation.json":
129
+ ParticipationChoice.model_validate_json(text)
130
+ elif name == "reporting/contributions.json":
131
+ from benchside.application.contributions import ContributionPolicy
132
+
133
+ ContributionPolicy.model_validate_json(text)
134
+ elif name == "metascience/state.json":
135
+ MetaState.model_validate_json(text)
136
+ elif name.startswith("sharing/"):
137
+ draft = SubmissionDraft.model_validate_json(text)
138
+ if Path(name).stem != draft.id:
139
+ _fail("Native draft identifier does not match its filename")
140
+ elif name.startswith("reporting/usage-"):
141
+ usage = UsagePayload.model_validate_json(text)
142
+ if name != f"reporting/usage-{usage.week}.json":
143
+ _fail("Native usage week does not match its filename")
144
+ else:
145
+ data = _loads(text)
146
+ if name == "reporting/installation.json":
147
+ if set(data) != {"id"} or not HEX.fullmatch(data["id"]):
148
+ _fail("Invalid native installation identity")
149
+ elif (
150
+ (set(data) - ({"title"} if name.startswith("app-projects/") else set()))
151
+ != (
152
+ {"host", "app_version", "surface", "project_id"}
153
+ if name.startswith("app-sessions/")
154
+ else {"host", "app_version", "surface"}
155
+ )
156
+ or data["host"] not in {"claude", "chatgpt", "unknown"}
157
+ or data["surface"] not in {"web", "desktop", "cli", "unknown"}
158
+ or not isinstance(data["app_version"], str)
159
+ ):
160
+ _fail("Invalid native project configuration")
161
+ if "title" in data and (
162
+ not isinstance(data["title"], str)
163
+ or not 1 <= len(data["title"]) <= 160
164
+ or any(ord(char) < 32 for char in data["title"])
165
+ ):
166
+ _fail("Invalid native project title")
167
+ if name.startswith("app-sessions/") and (
168
+ not isinstance(data.get("project_id"), str)
169
+ or not re.fullmatch(PROJECT, data["project_id"])
170
+ or f"app-projects/{data['project_id']}.json" not in files
171
+ ):
172
+ _fail("Native session references a missing project")
173
+
174
+
175
+ def _validate_body(body):
176
+ if (
177
+ not isinstance(body, dict)
178
+ or not {"files", "projects", "operations"} <= set(body)
179
+ or set(body) - {"files", "projects", "operations", "replay"}
180
+ ):
181
+ _fail("Invalid native memory contents")
182
+ if "replay" in body and (
183
+ not isinstance(body["replay"], dict)
184
+ or set(body["replay"]) != {"generation"}
185
+ or type(body["replay"]["generation"]) is not int
186
+ or not 1 <= body["replay"]["generation"] <= 2**32 - 1
187
+ ):
188
+ _fail("Invalid native replay generation")
189
+ _check_files(body["files"])
190
+ if not isinstance(body["projects"], dict) or not isinstance(body["operations"], dict):
191
+ _fail("Invalid native project or operation index")
192
+ for identifier, project in body["projects"].items():
193
+ if not re.fullmatch(PROJECT, identifier):
194
+ _fail("Invalid native project identity")
195
+ if f"app-projects/{identifier}.json" not in body["files"]:
196
+ _fail("Native project configuration is missing")
197
+ _validate_project(project)
198
+ config = _loads(body["files"][f"app-projects/{identifier}.json"])
199
+ key = f"{config['host']}:{project['document_id']}"
200
+ if identifier != "p-" + hashlib.sha256(key.encode()).hexdigest()[:32]:
201
+ _fail("Native project document does not match its stable identity")
202
+ for identifier, operation in body["operations"].items():
203
+ if not isinstance(operation, dict) or _operation_generation(identifier) > _generation(body):
204
+ _fail("Invalid native operation identity")
205
+ if not {"request_sha256", "result"} <= set(operation) or set(operation) - {
206
+ "request_sha256",
207
+ "result",
208
+ "revision",
209
+ "result_compacted",
210
+ }:
211
+ _update_required()
212
+ if not re.fullmatch(r"[a-f0-9]{64}", operation["request_sha256"]):
213
+ _fail("Invalid native operation receipt")
214
+ if "revision" in operation and (
215
+ type(operation["revision"]) is not int or operation["revision"] < 0
216
+ ):
217
+ _fail("Invalid native operation revision")
218
+ if "result_compacted" in operation and type(operation["result_compacted"]) is not bool:
219
+ _fail("Invalid native operation result marker")
220
+
221
+
222
+ def _validate_project(project):
223
+ if not isinstance(project, dict) or set(project) != {"document_id", "title"}:
224
+ _fail("Provide the native project document ID and title")
225
+ if any(
226
+ not isinstance(project[key], str)
227
+ or not 1 <= len(project[key]) <= limit
228
+ or any(ord(char) < 32 for char in project[key])
229
+ for key, limit in (("document_id", 256), ("title", 160))
230
+ ):
231
+ _fail("Invalid native project document ID or title")
232
+
233
+
234
+ def _has_gap_context(value):
235
+ """Include JSONL journals, frozen draft JSON and operation results in the gate.
236
+
237
+ Older packages must refuse a context-bearing notebook instead of silently
238
+ discarding nested fields when replaying their older event models.
239
+ """
240
+ if isinstance(value, dict):
241
+ if value.get("schema") == "benchside.gaps.v3" or ("kind" in value and "context" in value):
242
+ return True
243
+ return any(_has_gap_context(item) for item in value.values())
244
+ if isinstance(value, list):
245
+ return any(_has_gap_context(item) for item in value)
246
+ if isinstance(value, str) and ("context" in value or "benchside.gaps.v3" in value):
247
+ for line in [value, *value.splitlines()]:
248
+ try:
249
+ decoded = json.loads(line)
250
+ except (ValueError, TypeError):
251
+ continue
252
+ if not isinstance(decoded, str) and _has_gap_context(decoded):
253
+ return True
254
+ return False
255
+
256
+
257
+ def _document_limit(request):
258
+ # A host store may hold less than one Pages edit: Claude Docs caps a code block
259
+ # at 65,536 characters. Omitted means the original limit for every other host.
260
+ limit = request.get("document_limit_bytes")
261
+ if limit is None:
262
+ return MAX_DOCUMENT_BYTES
263
+ if type(limit) is not int or not 2 * DOCUMENT_CONTROL_RESERVE <= limit <= MAX_DOCUMENT_BYTES:
264
+ _fail(f"document_limit_bytes must be an integer from 32768 to {MAX_DOCUMENT_BYTES}")
265
+ return limit
266
+
267
+
268
+ def _has_extended_research(value):
269
+ """Gate 0.4 values in files, frozen payloads and cached results for older clients."""
270
+ if isinstance(value, dict):
271
+ if isinstance(value.get("discipline"), list) or any(
272
+ value.get(key) == "pi-hypothesis" for key in ("role", "benchside_role", "persona_id")
273
+ ):
274
+ return True
275
+ return any(_has_extended_research(item) for item in value.values())
276
+ if isinstance(value, list):
277
+ return any(_has_extended_research(item) for item in value)
278
+ if isinstance(value, str) and ("discipline" in value or "pi-hypothesis" in value):
279
+ for line in [value, *value.splitlines()]:
280
+ try:
281
+ decoded = json.loads(line)
282
+ except (ValueError, TypeError):
283
+ continue
284
+ if not isinstance(decoded, str) and _has_extended_research(decoded):
285
+ return True
286
+ return False
287
+
288
+
289
+ def _minimum_schema(body):
290
+ if _has_extended_research(body):
291
+ return RESEARCH_SCHEMA
292
+ if _has_gap_context(body):
293
+ return CONTEXT_SCHEMA
294
+ return CHECKPOINT_SCHEMA if "replay" in body else SCHEMA
295
+
296
+
297
+ def pack(body, workspace_id, revision, *, limit=MAX_DOCUMENT_BYTES):
298
+ _validate_body(body)
299
+ raw = _json(body).encode("utf-8")
300
+ if len(raw) > MAX_STATE_BYTES:
301
+ _capacity_error()
302
+ snapshot = {
303
+ "schema": _minimum_schema(body),
304
+ "workspace_id": workspace_id,
305
+ "revision": revision,
306
+ "payload": base64.b64encode(zlib.compress(raw)).decode("ascii"),
307
+ }
308
+ snapshot["sha256"] = _digest(snapshot)
309
+ if len(_json(snapshot).encode("utf-8")) > limit:
310
+ _capacity_error()
311
+ return snapshot
312
+
313
+
314
+ def unpack(document, expected_workspace_id=None):
315
+ """Reject damaged/foreign memory before restoring anything to a filesystem."""
316
+ try:
317
+ if isinstance(document, str):
318
+ if len(document.encode("utf-8")) > MAX_DOCUMENT_BYTES + 4096:
319
+ _fail("Native memory document is too large")
320
+ if document.strip().startswith("{"):
321
+ snapshot = _loads(document)
322
+ else:
323
+ blocks = re.findall(
324
+ r"^```json\s*\n(.*?)\n```\s*$", document, re.MULTILINE | re.DOTALL
325
+ )
326
+ if len(blocks) != 1:
327
+ _fail("Read the complete, single Benchside state block")
328
+ snapshot = _loads(blocks[0])
329
+ else:
330
+ snapshot = document
331
+ if not isinstance(snapshot, dict) or set(snapshot) != {
332
+ "schema",
333
+ "workspace_id",
334
+ "revision",
335
+ "payload",
336
+ "sha256",
337
+ }:
338
+ _fail("Invalid native memory envelope")
339
+ if snapshot["schema"] not in SCHEMA_ORDER:
340
+ _update_required()
341
+ if (
342
+ not HEX.fullmatch(snapshot["workspace_id"])
343
+ or type(snapshot["revision"]) is not int
344
+ or snapshot["revision"] < 0
345
+ or len(_json(snapshot).encode("utf-8")) > MAX_DOCUMENT_BYTES
346
+ ):
347
+ _fail("Unsupported native memory version or identity")
348
+ if expected_workspace_id and snapshot["workspace_id"] != expected_workspace_id:
349
+ _fail("This document belongs to another Benchside notebook")
350
+ unsigned = {key: value for key, value in snapshot.items() if key != "sha256"}
351
+ if snapshot["sha256"] != _digest(unsigned):
352
+ _fail(
353
+ "Native memory checksum failed; keep the document and recover its last good version"
354
+ )
355
+ compressed = base64.b64decode(snapshot["payload"], validate=True)
356
+ decoder = zlib.decompressobj()
357
+ raw = decoder.decompress(compressed, MAX_STATE_BYTES + 1)
358
+ if len(raw) > MAX_STATE_BYTES or not decoder.eof or decoder.unused_data:
359
+ _fail("Invalid or oversized compressed native memory")
360
+ body = _loads(raw.decode("utf-8"))
361
+ _validate_body(body)
362
+ # 0.4.0 already saved extended research values under v1-v3. Validate
363
+ # them with current models and upgrade on pack; never strand those stores.
364
+ required = CONTEXT_SCHEMA if _has_gap_context(body) else (
365
+ CHECKPOINT_SCHEMA if "replay" in body else SCHEMA
366
+ )
367
+ if SCHEMA_ORDER.index(snapshot["schema"]) < SCHEMA_ORDER.index(required):
368
+ _fail("Native memory features require a newer snapshot schema")
369
+ return snapshot, body
370
+ except (ValueError, KeyError, TypeError, AttributeError, zlib.error) as error:
371
+ raise ValidationError(
372
+ "Native memory could not be validated", code="native_storage_invalid"
373
+ ) from error
374
+
375
+
376
+ def markdown(snapshot):
377
+ return "```json\n" + _json(snapshot) + "\n```"
378
+
379
+
380
+ def reference(snapshot):
381
+ return {key: snapshot[key] for key in ("workspace_id", "revision", "sha256")}
382
+
383
+
384
+ def _generation(body):
385
+ return body.get("replay", {}).get("generation", 0)
386
+
387
+
388
+ def _operation_generation(identifier):
389
+ match = OPERATION.fullmatch(identifier) if isinstance(identifier, str) else None
390
+ if not match:
391
+ _fail("Use a UUID for generation 0, or g<operation_generation>-<UUID> after a checkpoint")
392
+ return int(match.group(1) or 0)
393
+
394
+
395
+ def _new_operation_id(body):
396
+ generation = _generation(body)
397
+ return (f"g{generation}-" if generation else "") + uuid.uuid4().hex
398
+
399
+
400
+ def _bound_operations(body, *, current=None):
401
+ """Expire a whole ID generation before forgetting any replay receipt."""
402
+ operations = body["operations"]
403
+ if (
404
+ len(operations) <= MAX_OPERATION_RECEIPTS
405
+ and len(_json(operations).encode("utf-8")) <= MAX_OPERATION_INDEX_BYTES
406
+ ):
407
+ return
408
+ generation = _generation(body) + 1
409
+ if generation > 2**32 - 1:
410
+ _capacity_error()
411
+ retained = {}
412
+ ordered = sorted(
413
+ operations,
414
+ key=lambda key: (key == current, operations[key].get("revision", 0)),
415
+ reverse=True,
416
+ )
417
+ # Leave half the index budget for new work so concurrent requests do not
418
+ # expire on every subsequent write. Keep the current result even when its
419
+ # exact response alone occupies the bounded 32 KiB response cache.
420
+ for identifier in ordered:
421
+ candidate = {**retained, identifier: operations[identifier]}
422
+ if len(candidate) > RETAIN_OPERATION_RECEIPTS or (
423
+ identifier != current
424
+ and len(_json(candidate).encode("utf-8")) > MAX_OPERATION_INDEX_BYTES // 2
425
+ ):
426
+ break
427
+ retained = candidate
428
+ body["operations"] = retained
429
+ body["replay"] = {"generation": generation}
430
+
431
+
432
+ def _checkpoint_sampling_format(body, original_body):
433
+ """Use the v2 envelope before persisting sampling fields old readers reject."""
434
+ if _generation(body):
435
+ return
436
+ path = "metascience/state.json"
437
+ saved = body["files"].get(path)
438
+ if saved is None or saved == original_body["files"].get(path):
439
+ return
440
+ state = _loads(saved)
441
+ if any("sampling" in sample for sample in state.get("samples", {}).values()):
442
+ # Even a newly serialized legacy sampling tag is an unknown field to
443
+ # pre-0.1.3 readers. A compatibility checkpoint fences pending old IDs,
444
+ # while every retained receipt still replays; no receipts are evicted here.
445
+ body["replay"] = {"generation": 1}
446
+
447
+
448
+ def _capacity(body, snapshot, limit=MAX_DOCUMENT_BYTES):
449
+ state_bytes = len(_json(body).encode("utf-8"))
450
+ document_bytes = len(_json(snapshot).encode("utf-8"))
451
+ return {
452
+ "state_bytes": state_bytes,
453
+ "document_bytes": document_bytes,
454
+ "document_limit_bytes": limit,
455
+ "ordinary_state_bytes_remaining": max(
456
+ 0, MAX_STATE_BYTES - STATE_CONTROL_RESERVE - state_bytes
457
+ ),
458
+ "ordinary_document_bytes_remaining": max(
459
+ 0, limit - DOCUMENT_CONTROL_RESERVE - document_bytes
460
+ ),
461
+ "control_reserve_document_bytes": DOCUMENT_CONTROL_RESERVE,
462
+ "optional_history_document_bytes": _metascience_size(body),
463
+ "optional_history_limit_bytes": MAX_METASCIENCE_DOCUMENT_BYTES,
464
+ }
465
+
466
+
467
+ def _metascience_size(body):
468
+ text = body["files"].get("metascience/state.json", "")
469
+ return len(base64.b64encode(zlib.compress(text.encode("utf-8")))) if text else 0
470
+
471
+
472
+ def _require_metascience_headroom(body, original=None, *, additional=0):
473
+ size = _metascience_size(body)
474
+ if original is not None and size <= _metascience_size(original):
475
+ return # Reads, research records, withdrawal and shrinking state remain available.
476
+ if size + (additional * 4 + 2) // 3 > MAX_METASCIENCE_DOCUMENT_BYTES:
477
+ raise ValidationError(
478
+ "Optional analysis and study history has reached its cloud notebook allowance. "
479
+ "No new analysis or submission was saved. Existing records and receipts remain "
480
+ "intact; research work and consent withdrawal can continue. Preserve this notebook "
481
+ "and choose larger private storage, or discuss an explicitly approved archival/summary "
482
+ "plan before extending optional history. No automatic compaction is performed; "
483
+ "a summary alone does not replace the receipts and consent state needed to resume.",
484
+ code="native_capacity",
485
+ )
486
+
487
+
488
+ def _require_headroom(body, snapshot, *, additional=0, limit=MAX_DOCUMENT_BYTES):
489
+ capacity = _capacity(body, snapshot, limit)
490
+ # Base64 and conservative compression/framing allowance. Collector receipts
491
+ # are bounded separately; reserve their worst-case metadata before any POST.
492
+ encoded_growth = (additional * 4 + 2) // 3 + (1024 if additional else 0)
493
+ if (
494
+ capacity["state_bytes"] + additional > MAX_STATE_BYTES - STATE_CONTROL_RESERVE
495
+ or capacity["document_bytes"] + encoded_growth > limit - DOCUMENT_CONTROL_RESERVE
496
+ ):
497
+ _capacity_error()
498
+
499
+
500
+ def _result_identity(value):
501
+ """Keep replay identities, never duplicate scientific text or growing recall."""
502
+ if isinstance(value, list):
503
+ return [_result_identity(item) for item in value]
504
+ if not isinstance(value, dict):
505
+ return None
506
+ identifiers = {
507
+ "id",
508
+ "recorded",
509
+ "project_id",
510
+ "session_id",
511
+ "draft_id",
512
+ "batch_id",
513
+ "week",
514
+ "token",
515
+ "channel",
516
+ "payload_sha256",
517
+ "sha256",
518
+ "received_at",
519
+ }
520
+ result = {
521
+ key: item
522
+ for key, item in value.items()
523
+ if key in identifiers and isinstance(item, str) and len(item) <= 128
524
+ }
525
+ for key in ("sitting", "preview", "invitation"):
526
+ if key in value:
527
+ result[key] = _result_identity(value[key])
528
+ if isinstance(value.get("steps"), dict):
529
+ result["steps"] = {key: _result_identity(item) for key, item in value["steps"].items()}
530
+ return result
531
+
532
+
533
+ def _compact_operations(body, *, current=None, all_results=False):
534
+ """Bound the response cache while retaining every operation ID and input hash."""
535
+ remaining = 0 if all_results else MAX_REPLAY_CACHE_BYTES
536
+ ordered = sorted(
537
+ body["operations"],
538
+ key=lambda key: (key == current, body["operations"][key].get("revision", 0)),
539
+ reverse=True,
540
+ )
541
+ for identifier in ordered:
542
+ operation = body["operations"][identifier]
543
+ if operation.get("result_compacted"):
544
+ continue
545
+ size = len(_json(operation["result"]).encode("utf-8"))
546
+ if size <= remaining:
547
+ remaining -= size
548
+ else:
549
+ summary = _result_identity(operation["result"])
550
+ if len(_json(summary).encode("utf-8")) > MAX_COMPACT_RESULT_BYTES:
551
+ # An unusually large read nested inside a batch is not another
552
+ # unbounded cache. The durable operation/hash still proves it
553
+ # completed; obtain current data with a separate read.
554
+ summary = {"completed": True}
555
+ body["operations"][identifier] = {
556
+ **operation,
557
+ "result": summary,
558
+ "result_compacted": True,
559
+ }
560
+
561
+
562
+ def _privacy_controls(app):
563
+ flow = SharingFlow(app.paths)
564
+ status = flow.status()
565
+ profile = flow.profile()
566
+ enabled = {f"sharing.{key}" for key in ("gaps", "feedback", "usage") if status[key]["enabled"]}
567
+ meta_path = app.paths.home / "metascience/state.json"
568
+ scopes = []
569
+ if meta_path.exists():
570
+ state = MetaState.model_validate_json(meta_path.read_text())
571
+ enabled.update(f"metascience.{key}" for key in state.grants)
572
+ scopes = state.scopes
573
+ if profile.include_in_usage:
574
+ enabled.add("profile.include_in_usage")
575
+ return {"enabled": enabled, "demographics": profile.demographics.model_dump(), "scopes": scopes}
576
+
577
+
578
+ def _commands(command):
579
+ return (
580
+ [step["request"] for step in command["steps"]]
581
+ if command["action"] == "batch"
582
+ else [command]
583
+ )
584
+
585
+
586
+ def _withdrawal(command, before, after):
587
+ """Reserve capacity for actual opt-outs, never repeated off/preference writes."""
588
+ for item in _commands(command):
589
+ action = item["action"]
590
+ if action in READ_ACTIONS:
591
+ continue
592
+ if action in {"sharing.consent", "metascience.consent"} and item.get("enabled") is False:
593
+ continue
594
+ if action == "participation.set" and item.get("response") in ("declined", "deferred"):
595
+ continue
596
+ if action == "profile.set" and item.get("include_in_usage") is False:
597
+ demographics = item.get("demographics")
598
+ if (
599
+ isinstance(demographics, dict)
600
+ and {
601
+ "discipline": None,
602
+ "career_stage": None,
603
+ **demographics,
604
+ }
605
+ == before["demographics"]
606
+ ):
607
+ continue
608
+ # A batch may use the reserve only for literal opt-outs and reads.
609
+ # Unrelated profile changes and unresolved references use ordinary space.
610
+ return False
611
+ return bool(before["enabled"] - after["enabled"]) and not (after["enabled"] - before["enabled"])
612
+
613
+
614
+ def _retired_analysis(command, before, after):
615
+ # Repeated analysis opt-outs also remove cached references left by older
616
+ # versions. Retain replay IDs/hashes, not withdrawn source/session details.
617
+ return (
618
+ before["scopes"] != after["scopes"]
619
+ or "metascience.analysis" in (before["enabled"] ^ after["enabled"])
620
+ or any(
621
+ item["action"] == "metascience.consent" and item.get("choice") == "analysis"
622
+ for item in _commands(command)
623
+ )
624
+ )
625
+
626
+
627
+ def _compact_control_history(body):
628
+ """Emergency consent checkpoint only; never drop science, receipts or operation IDs."""
629
+ name = "projects/consent-ledger/journal.jsonl"
630
+ if name not in body["files"]:
631
+ return
632
+ rows = [_loads(line) for line in body["files"][name].splitlines() if line.strip()]
633
+ revoked = {row["data"]["grant_id"] for row in rows if row["type"] == "ConsentRevoked"}
634
+ active = [
635
+ row
636
+ for row in rows
637
+ if row["type"] == "ConsentGranted" and row["data"]["grant_id"] not in revoked
638
+ ]
639
+ latest = {}
640
+ for row in rows:
641
+ if row["type"] == "ReportingConsentChanged":
642
+ latest[row["data"]["channel"]] = row
643
+ retained = [
644
+ row
645
+ for row in rows
646
+ if row["type"] not in {"ConsentGranted", "ConsentRevoked", "ReportingConsentChanged"}
647
+ ]
648
+ retained += active[-1:]
649
+ retained += [row for row in latest.values() if row["data"]["enabled"]]
650
+ body["files"][name] = "".join(_json(row) + "\n" for row in retained)
651
+
652
+
653
+ def _preflight_submission(body, snapshot, command, limit=MAX_DOCUMENT_BYTES):
654
+ if command["action"] not in {"sharing.send", "metascience.send"}:
655
+ return
656
+ # Duplicate destination/ID metadata can appear in both the durable receipt
657
+ # and its cached result. Include the entire bounded HTTP receipt (8 KiB)
658
+ # twice and framing, even though normal server receipts are much smaller.
659
+ if command["action"] == "sharing.send":
660
+ text = body["files"].get(f"sharing/drafts/{command.get('draft_id')}.json")
661
+ if text is None:
662
+ return # The ordinary validation rejects an unknown draft without network.
663
+ preview = SubmissionDraft.model_validate_json(text).preview
664
+ metadata = _json(
665
+ {
666
+ "destination": preview.destination,
667
+ "observation_ids": preview.observation_ids,
668
+ "grant_id": preview.grant_id,
669
+ }
670
+ )
671
+ else:
672
+ text = body["files"].get("metascience/state.json")
673
+ if text is None:
674
+ return # Let the ordinary unknown-draft validation supply recovery guidance.
675
+ state = MetaState.model_validate_json(text)
676
+ draft = state.drafts.get(command.get("draft_id"))
677
+ if draft is None:
678
+ return
679
+ metadata = _json({"destination": draft.destination, "draft_id": draft.id})
680
+ if draft.id not in state.receipts:
681
+ _require_metascience_headroom(
682
+ body, additional=10 * 1024 + len(metadata.encode("utf-8"))
683
+ )
684
+ _require_headroom(
685
+ body, snapshot, additional=18 * 1024 + 2 * len(metadata.encode("utf-8")), limit=limit
686
+ )
687
+
688
+
689
+ def _restore(files, home):
690
+ for name, content in files.items():
691
+ path = home / name # All paths have been allowlisted by unpack.
692
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
693
+ path.write_text(content, encoding="utf-8")
694
+ path.chmod(0o600)
695
+
696
+
697
+ def _capture(home):
698
+ return {
699
+ path.relative_to(home).as_posix(): path.read_text(encoding="utf-8")
700
+ for path in sorted(home.rglob("*"))
701
+ if path.is_file() and FILE.fullmatch(path.relative_to(home).as_posix())
702
+ }
703
+
704
+
705
+ def _quote(text):
706
+ # Scientific text stays quoted content, never executable Page/agent instructions.
707
+ return "\n".join("> " + line for line in str(text).splitlines())
708
+
709
+
710
+ def journal_view(app, project_id, projects, revision, history="recent"):
711
+ recall = app.run({"action": "recall", "project_id": project_id, "history": history})
712
+ lines = [
713
+ f"Snapshot revision: {revision}.",
714
+ (
715
+ "This page is a readable view of that snapshot, not a live save status. "
716
+ "Benchside checks the private notebook for the current saved revision; "
717
+ "ask Benchside to record corrections so history is preserved."
718
+ ),
719
+ (
720
+ f"Showing {len(recall['recent_decisions'])} of {recall['total_decisions']} decisions "
721
+ f"and {len(recall['recent_records'])} of {recall['total_records']} research records. "
722
+ + ("Ask Benchside for all history to see older entries." if history == "recent" else "")
723
+ ).strip(),
724
+ "## Current hypothesis",
725
+ _quote(recall["current_hypothesis"]) if recall["current_hypothesis"] else "None recorded.",
726
+ "## Unresolved questions",
727
+ *[_quote(question) for question in recall["open_questions"]],
728
+ ]
729
+ if not recall["open_questions"]:
730
+ lines.append("None recorded.")
731
+ label = "All" if history == "all" else "Recent"
732
+ lines.append(f"## {label} decisions")
733
+ for decision in recall["recent_decisions"]:
734
+ lines.extend([_quote(decision["decision"]), _quote(decision["rationale"])])
735
+ lines.extend(["", f"## {label} research questions and answers"])
736
+ for question in recall["recent_questions"]:
737
+ lines.extend([_quote(question["question"]), _quote(question["answer"] or "Unresolved")])
738
+ if not recall["recent_questions"]:
739
+ lines.append("None recorded.")
740
+ lines.append(f"## {label} research records")
741
+ for record in recall["recent_records"]:
742
+ lines.append(_quote(record["summary"]))
743
+ lines.extend(_quote(detail) for detail in record["details"])
744
+ lines.extend(_quote("Source: " + source) for source in record["sources"])
745
+ lines.append("## Open discussions")
746
+ lines.extend(
747
+ _quote(sitting["persona"] + ": " + sitting["id"]) for sitting in recall["open_sittings"]
748
+ )
749
+ if not recall["open_sittings"]:
750
+ lines.append("None open.")
751
+ return {
752
+ "project_id": project_id,
753
+ **projects.get(project_id, {}),
754
+ "markdown": "\n\n".join(lines),
755
+ }
756
+
757
+
758
+ BATCH_ACTIONS = {
759
+ "setup",
760
+ "roles",
761
+ "projects",
762
+ "recall",
763
+ "start",
764
+ "hypothesis",
765
+ "record",
766
+ "question",
767
+ "answer",
768
+ "critique",
769
+ "resolve",
770
+ "decide",
771
+ "gap",
772
+ "close",
773
+ "profile.status",
774
+ "profile.set",
775
+ "participation.status",
776
+ "participation.set",
777
+ "sharing.status",
778
+ "sharing.consent",
779
+ "metascience.status",
780
+ "metascience.consent",
781
+ "metascience.scopes",
782
+ }
783
+
784
+
785
+ def _references(value, results):
786
+ if isinstance(value, dict):
787
+ if set(value) == {"$ref"}:
788
+ path = value["$ref"]
789
+ if not isinstance(path, str):
790
+ _fail("A batch reference must name an earlier step result")
791
+ resolved = results
792
+ for key in path.split("."):
793
+ if not isinstance(resolved, dict) or key not in resolved:
794
+ _fail("A batch reference must name an earlier step result")
795
+ resolved = resolved[key]
796
+ return copy.deepcopy(resolved)
797
+ return {key: _references(item, results) for key, item in value.items()}
798
+ if isinstance(value, list):
799
+ return [_references(item, results) for item in value]
800
+ return value
801
+
802
+
803
+ def _checked_command(body, command, project):
804
+ if not isinstance(command, dict) or not isinstance(command.get("action"), str):
805
+ _fail("Provide an app request inside native.run")
806
+ if command["action"].startswith(("native.", "storage.")):
807
+ _fail("Native documents replace the local storage probe")
808
+ if command["action"] == "setup":
809
+ _validate_project(project)
810
+ selected = command.get("project_id")
811
+ if selected:
812
+ existing = body["projects"].get(selected)
813
+ if not existing or existing["document_id"] != project["document_id"]:
814
+ _fail("Select the existing project and its registered journal document")
815
+ elif command.get("project_key") != project["document_id"]:
816
+ _fail("Use the observed native project document ID as project_key")
817
+ else:
818
+ registered = [
819
+ identifier
820
+ for identifier, saved in body["projects"].items()
821
+ if saved["document_id"] == project["document_id"]
822
+ ]
823
+ if len(registered) > 1:
824
+ _fail("Several projects use this journal document; select an existing project_id")
825
+ if registered:
826
+ # The native document identifies the project across host apps.
827
+ # Keep its original creation identity instead of hashing a new host.
828
+ command = {**command, "project_id": registered[0]}
829
+ command = {**command, "title": project["title"]}
830
+ elif project is not None:
831
+ _fail("Project document registration is only supported during setup")
832
+ return command
833
+
834
+
835
+ def _execute(app, body, command, project):
836
+ command = _checked_command(body, command, project)
837
+ result = app.run(command)
838
+ if project is not None:
839
+ body["projects"][result["project_id"]] = project
840
+ # Older notebooks can have the friendly title only in the native index.
841
+ project_id = command.get("project_id")
842
+ if project_id in body["projects"] and isinstance(result, dict):
843
+ recalled = result if command["action"] == "recall" else result.get("recall")
844
+ if isinstance(recalled, dict):
845
+ recalled["title"] = body["projects"][project_id]["title"]
846
+ return result
847
+
848
+
849
+ def _execute_batch(app, body, steps):
850
+ if not isinstance(steps, list) or not 1 <= len(steps) <= 16:
851
+ _fail("A native batch needs 1–16 private steps")
852
+ identifiers = set()
853
+ # Validate the whole action list before executing any step. Network and
854
+ # preview/approval actions must remain separate from these private saves.
855
+ for step in steps:
856
+ if not isinstance(step, dict) or set(step) - {"id", "request", "project_document"}:
857
+ _fail("Invalid native batch step")
858
+ identifier = step.get("id")
859
+ if not isinstance(identifier, str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,31}", identifier):
860
+ _fail("Use a short unique batch step ID")
861
+ if identifier in identifiers:
862
+ _fail("Use a short unique batch step ID")
863
+ identifiers.add(identifier)
864
+ command = step.get("request")
865
+ if (
866
+ not isinstance(command, dict)
867
+ or not isinstance(command.get("action"), str)
868
+ or command["action"] not in BATCH_ACTIONS
869
+ ):
870
+ _fail("Batches support private actions only; keep network and previews separate")
871
+ results = {}
872
+ project_id = None
873
+ for step in steps:
874
+ command = _references(step["request"], results)
875
+ result = _execute(app, body, command, step.get("project_document"))
876
+ results[step["id"]] = result
877
+ project_id = command.get("project_id", project_id)
878
+ if command["action"] == "setup":
879
+ project_id = result["project_id"]
880
+ return {"steps": results, "project_id": project_id}
881
+
882
+
883
+ def run_native(request):
884
+ """Host-neutral entry point used by the bundled app script."""
885
+ if not isinstance(request, dict) or not isinstance(request.get("action"), str):
886
+ _fail("Provide a native memory action")
887
+ action = request["action"]
888
+ if action == "native.create":
889
+ snapshot = pack({"files": {}, "projects": {}, "operations": {}}, uuid.uuid4().hex, 0)
890
+ return {
891
+ "snapshot": snapshot,
892
+ "markdown": markdown(snapshot),
893
+ "operation_generation": 0,
894
+ "saved": False,
895
+ }
896
+ if action not in {"native.inspect", "native.run", "native.batch", "native.confirm"}:
897
+ _fail("Unknown native memory action")
898
+ limit = _document_limit(request)
899
+ expected = request.get("workspace_id")
900
+ if not isinstance(expected, str) or not HEX.fullmatch(expected):
901
+ _fail("Use the notebook workspace ID returned by native.create")
902
+ if request.get("document") is None:
903
+ _fail("Read and provide the complete saved native document before continuing")
904
+ snapshot, body = unpack(request["document"], expected)
905
+ if action == "native.confirm":
906
+ if reference(snapshot) != request.get("expected"):
907
+ raise ValidationError(
908
+ "Native save was not confirmed; reread and reconcile before retrying",
909
+ code="native_save_conflict",
910
+ )
911
+ return {"saved": True, **reference(snapshot)}
912
+ if action == "native.inspect":
913
+ return {
914
+ **reference(snapshot),
915
+ "projects": body["projects"],
916
+ "capacity": _capacity(body, snapshot, limit),
917
+ "operation_generation": _generation(body),
918
+ }
919
+
920
+ batch = action == "native.batch"
921
+ command = (
922
+ {"action": "batch", "steps": request.get("steps")} if batch else request.get("request")
923
+ )
924
+ if not isinstance(command, dict) or not isinstance(command.get("action"), str):
925
+ _fail("Provide an app request inside native.run")
926
+ project = request.get("project_document")
927
+ if batch and project is not None:
928
+ _fail("Put project_document on the batch setup step")
929
+ if not batch:
930
+ _checked_command(body, command, project)
931
+ operation_id = request.get("operation_id", _new_operation_id(body))
932
+ operation_generation = _operation_generation(operation_id)
933
+ request_hash = _digest({"request": command, "project_document": project})
934
+ previous = body["operations"].get(operation_id)
935
+ if previous and previous["request_sha256"] != request_hash:
936
+ _fail("This operation ID was already used for a different request")
937
+ if not previous and operation_generation != _generation(body):
938
+ raise ValidationError(
939
+ "This operation is outside the notebook's active replay generation. It cannot be "
940
+ "safely replayed. Preserve the original request and reconcile saved scientific "
941
+ "records or submission receipts before deciding what to do. Do not automatically "
942
+ "retry with a new operation ID. Read native.inspect for the current generation.",
943
+ code="native_operation_expired",
944
+ )
945
+
946
+ original_body = copy.deepcopy(body)
947
+ with tempfile.TemporaryDirectory(prefix="benchside-native-") as temporary:
948
+ home = Path(temporary)
949
+ _restore(body["files"], home)
950
+ app = App(Paths(home=home, repo_root=home))
951
+ outcome = {"ok": True}
952
+ withdrawal = False
953
+ if previous:
954
+ result = previous["result"]
955
+ else:
956
+ try:
957
+ original_controls = _privacy_controls(app)
958
+ if command["action"] in {"sharing.send", "metascience.send"}:
959
+ # Capacity checks may migrate an old, oversized replay index.
960
+ # Do that only on a copy: a failed send must keep its original
961
+ # generation so the same operation can be retried safely.
962
+ preflight = copy.deepcopy(body)
963
+ _compact_operations(preflight)
964
+ _bound_operations(preflight)
965
+ _preflight_submission(
966
+ preflight,
967
+ pack(preflight, expected, snapshot["revision"], limit=limit),
968
+ command,
969
+ limit,
970
+ )
971
+ result = (
972
+ _execute_batch(app, body, command["steps"])
973
+ if batch
974
+ else _execute(app, body, command, project)
975
+ )
976
+ mutates = (
977
+ any(step["request"]["action"] not in READ_ACTIONS for step in command["steps"])
978
+ if batch
979
+ else command["action"] not in READ_ACTIONS
980
+ )
981
+ if mutates:
982
+ current_controls = _privacy_controls(app)
983
+ withdrawal = _withdrawal(command, original_controls, current_controls)
984
+ body["operations"][operation_id] = {
985
+ "request_sha256": request_hash,
986
+ "result": result,
987
+ "revision": snapshot["revision"] + 1,
988
+ }
989
+ _compact_operations(
990
+ body,
991
+ current=operation_id,
992
+ all_results=_retired_analysis(command, original_controls, current_controls),
993
+ )
994
+ _bound_operations(body, current=operation_id)
995
+ except BenchsideError as error:
996
+ result = None
997
+ outcome = {"ok": False, "error": str(error), "code": error.code}
998
+ if batch:
999
+ # No partial setup, preferences, events or failure counters
1000
+ # escape a failed private transaction.
1001
+ body = original_body
1002
+ if not batch or outcome["ok"]:
1003
+ body["files"] = _capture(home)
1004
+ _checkpoint_sampling_format(body, original_body)
1005
+ # Compression bytes can differ across runtimes without a state change.
1006
+ # Preserve the original envelope for reads, replays and rolled-back
1007
+ # batches so a different zlib representation cannot trigger a save.
1008
+ changed = _json(body) != _json(original_body)
1009
+ control_history_compacted = False
1010
+ candidate_failed = False
1011
+ delivery_confirmed = False
1012
+ try:
1013
+ if changed and not withdrawal:
1014
+ _require_metascience_headroom(body, original_body)
1015
+ try:
1016
+ candidate = (
1017
+ pack(body, expected, snapshot["revision"] + 1, limit=limit)
1018
+ if changed
1019
+ else snapshot
1020
+ )
1021
+ except ValidationError as error:
1022
+ if error.code != "native_capacity" or not outcome["ok"] or not withdrawal:
1023
+ raise
1024
+ _compact_operations(body, all_results=True)
1025
+ _compact_control_history(body)
1026
+ candidate = pack(body, expected, snapshot["revision"] + 1, limit=limit)
1027
+ control_history_compacted = True
1028
+ if changed and not withdrawal:
1029
+ _require_headroom(body, candidate, limit=limit)
1030
+ except ValidationError as error:
1031
+ if error.code != "native_capacity":
1032
+ raise
1033
+ # No private transaction is committed if its candidate cannot fit.
1034
+ # A collector receipt, if already obtained despite the conservative
1035
+ # preflight, must still be returned and described as unsaved.
1036
+ delivery_confirmed = outcome["ok"] and command["action"] in {
1037
+ "sharing.send",
1038
+ "metascience.send",
1039
+ }
1040
+ outcome = {"ok": False, "error": str(error), "code": error.code}
1041
+ if delivery_confirmed:
1042
+ outcome["error"] = (
1043
+ "Collector delivery was confirmed but its native receipt could not be saved. "
1044
+ "Preserve the returned receipt and original notebook; retry only the same "
1045
+ "approved draft after recovering capacity."
1046
+ )
1047
+ else:
1048
+ result = None
1049
+ if withdrawal:
1050
+ outcome["error"] = (
1051
+ "Consent withdrawal could not fit in this legacy notebook, even after "
1052
+ "compacting replay responses and consent history. It has not been saved. "
1053
+ "Stop sharing, preserve the notebook, and recover capacity or move to "
1054
+ "larger private storage before continuing."
1055
+ )
1056
+ candidate, body = snapshot, original_body
1057
+ changed, candidate_failed = False, True
1058
+ project_id = (result or {}).get("project_id") if isinstance(result, dict) else None
1059
+ project_id = project_id or command.get("project_id")
1060
+ view = (
1061
+ journal_view(
1062
+ app,
1063
+ project_id,
1064
+ body["projects"],
1065
+ candidate["revision"],
1066
+ command.get("history", "recent") if command["action"] == "recall" else "recent",
1067
+ )
1068
+ if not candidate_failed and project_id in body["projects"]
1069
+ else None
1070
+ )
1071
+ return {
1072
+ **outcome,
1073
+ "result": result,
1074
+ "operation_id": operation_id,
1075
+ "operation_generation": _generation(body),
1076
+ "replay_checkpointed": _generation(body) != _generation(original_body),
1077
+ "replayed": bool(previous),
1078
+ "result_compacted": bool(previous and previous.get("result_compacted")),
1079
+ "control_history_compacted": control_history_compacted,
1080
+ **({"delivery_confirmed": True} if delivery_confirmed else {}),
1081
+ "base": reference(snapshot),
1082
+ "snapshot": candidate,
1083
+ "markdown": markdown(candidate),
1084
+ "changed": changed,
1085
+ "saved": False,
1086
+ "project_journal": view,
1087
+ "capacity": _capacity(body, candidate, limit),
1088
+ }