benchside 0.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- benchside/__init__.py +1 -0
- benchside/_content/app/SKILL.md +155 -0
- benchside/_content/app/references/app-api.md +261 -0
- benchside/_content/app/references/generic-agents.md +69 -0
- benchside/_content/app/references/metascience.md +346 -0
- benchside/_content/app/references/native-memory.md +429 -0
- benchside/_content/app/references/onboarding.md +313 -0
- benchside/_content/app/references/sharing.md +159 -0
- benchside/_content/app/scripts/benchside_app.py +311 -0
- benchside/_content/app-requirements.txt +197 -0
- benchside/_content/claude/bench-init/SKILL.md +37 -0
- benchside/_content/claude/bench-share/SKILL.md +44 -0
- benchside/_content/fixtures/.gitkeep +0 -0
- benchside/_content/legacy-skill-digests.json +26 -0
- benchside/_content/personas/journal-club.yaml +45 -0
- benchside/_content/personas/methods-clinic.yaml +49 -0
- benchside/_content/personas/peer-review.yaml +45 -0
- benchside/_content/personas/pi-hypothesis.yaml +121 -0
- benchside/_content/personas/pi.yaml +87 -0
- benchside/_content/personas/repro-check.yaml +45 -0
- benchside/_content/personas/results-meeting.yaml +46 -0
- benchside/_content/personas/study-design.yaml +50 -0
- benchside/_content/templates/app-role.md.tmpl +31 -0
- benchside/_content/templates/blocks/capture-contract.md +40 -0
- benchside/_content/templates/blocks/sovereignty.md +36 -0
- benchside/_content/templates/skill.md.tmpl +54 -0
- benchside/application/__init__.py +0 -0
- benchside/application/app.py +458 -0
- benchside/application/bridge.py +55 -0
- benchside/application/contributions.py +39 -0
- benchside/application/di.py +35 -0
- benchside/application/metascience.py +671 -0
- benchside/application/native.py +1088 -0
- benchside/application/packaging.py +19 -0
- benchside/application/sharing.py +439 -0
- benchside/application/submission_failures.py +28 -0
- benchside/cli/__init__.py +0 -0
- benchside/cli/hooks.py +159 -0
- benchside/cli/install.py +276 -0
- benchside/cli/journal.py +232 -0
- benchside/cli/main.py +761 -0
- benchside/cli/runtime.py +245 -0
- benchside/cli/sharing.py +66 -0
- benchside/cli/ui/__init__.py +5 -0
- benchside/cli/ui/_glyphs.py +21 -0
- benchside/cli/ui/_model.py +66 -0
- benchside/cli/ui/_renderer.py +110 -0
- benchside/cli/ui/_rich.py +75 -0
- benchside/config.py +122 -0
- benchside/domain/__init__.py +0 -0
- benchside/domain/authoring/__init__.py +0 -0
- benchside/domain/authoring/command/__init__.py +0 -0
- benchside/domain/authoring/command/compile.py +28 -0
- benchside/domain/authoring/model/__init__.py +0 -0
- benchside/domain/authoring/model/flow.py +27 -0
- benchside/domain/authoring/model/persona.py +56 -0
- benchside/domain/authoring/model/skill.py +32 -0
- benchside/domain/authoring/model/value.py +42 -0
- benchside/domain/authoring/port/__init__.py +5 -0
- benchside/domain/authoring/port/renderer.py +17 -0
- benchside/domain/authoring/port/repository.py +28 -0
- benchside/domain/authoring/port/skill_writer.py +19 -0
- benchside/domain/authoring/query/__init__.py +0 -0
- benchside/domain/authoring/query/get_persona.py +30 -0
- benchside/domain/authoring/query/list_personas.py +21 -0
- benchside/domain/authoring/service/__init__.py +0 -0
- benchside/domain/authoring/service/authoring.py +99 -0
- benchside/domain/authoring/util/__init__.py +0 -0
- benchside/domain/authoring/util/di/__init__.py +3 -0
- benchside/domain/authoring/util/di/provider.py +15 -0
- benchside/domain/consultation/__init__.py +0 -0
- benchside/domain/consultation/command/__init__.py +0 -0
- benchside/domain/consultation/command/capture_gap.py +28 -0
- benchside/domain/consultation/command/close.py +29 -0
- benchside/domain/consultation/command/open.py +36 -0
- benchside/domain/consultation/command/raise_critique.py +30 -0
- benchside/domain/consultation/command/record_decision.py +30 -0
- benchside/domain/consultation/command/resolve_critique.py +32 -0
- benchside/domain/consultation/command/state_hypothesis.py +28 -0
- benchside/domain/consultation/event/__init__.py +22 -0
- benchside/domain/consultation/event/closed.py +13 -0
- benchside/domain/consultation/event/critique_raised.py +12 -0
- benchside/domain/consultation/event/critique_resolved.py +12 -0
- benchside/domain/consultation/event/decision_recorded.py +13 -0
- benchside/domain/consultation/event/gap_observed.py +16 -0
- benchside/domain/consultation/event/hypothesis_stated.py +12 -0
- benchside/domain/consultation/event/opened.py +23 -0
- benchside/domain/consultation/event/question.py +16 -0
- benchside/domain/consultation/event/research_recorded.py +9 -0
- benchside/domain/consultation/model/__init__.py +0 -0
- benchside/domain/consultation/model/consultation.py +60 -0
- benchside/domain/consultation/model/project.py +78 -0
- benchside/domain/consultation/model/value.py +150 -0
- benchside/domain/consultation/port/__init__.py +6 -0
- benchside/domain/consultation/port/repository.py +32 -0
- benchside/domain/consultation/query/__init__.py +0 -0
- benchside/domain/consultation/query/get_consultation.py +28 -0
- benchside/domain/consultation/query/recall_project.py +97 -0
- benchside/domain/consultation/service/__init__.py +0 -0
- benchside/domain/consultation/service/consultation.py +373 -0
- benchside/domain/consultation/util/__init__.py +0 -0
- benchside/domain/consultation/util/di/__init__.py +3 -0
- benchside/domain/consultation/util/di/provider.py +33 -0
- benchside/domain/export/__init__.py +0 -0
- benchside/domain/export/command/__init__.py +0 -0
- benchside/domain/export/command/export_observations.py +31 -0
- benchside/domain/export/command/grant_consent.py +26 -0
- benchside/domain/export/command/revoke_consent.py +20 -0
- benchside/domain/export/event/__init__.py +19 -0
- benchside/domain/export/event/consent_granted.py +9 -0
- benchside/domain/export/event/consent_revoked.py +8 -0
- benchside/domain/export/event/observations_exported.py +12 -0
- benchside/domain/export/event/reporting.py +24 -0
- benchside/domain/export/model/__init__.py +0 -0
- benchside/domain/export/model/ledger.py +40 -0
- benchside/domain/export/model/metascience.py +418 -0
- benchside/domain/export/model/reporting.py +193 -0
- benchside/domain/export/model/value.py +79 -0
- benchside/domain/export/model/wire.py +104 -0
- benchside/domain/export/port/__init__.py +5 -0
- benchside/domain/export/port/redactor.py +27 -0
- benchside/domain/export/port/repository.py +25 -0
- benchside/domain/export/port/sink.py +19 -0
- benchside/domain/export/query/__init__.py +0 -0
- benchside/domain/export/query/consent_status.py +30 -0
- benchside/domain/export/query/preview_export.py +37 -0
- benchside/domain/export/service/__init__.py +0 -0
- benchside/domain/export/service/consent.py +53 -0
- benchside/domain/export/service/export.py +171 -0
- benchside/domain/export/service/reporting.py +281 -0
- benchside/domain/export/util/__init__.py +0 -0
- benchside/domain/export/util/di/__init__.py +3 -0
- benchside/domain/export/util/di/provider.py +22 -0
- benchside/domain/shared/__init__.py +0 -0
- benchside/domain/shared/command.py +44 -0
- benchside/domain/shared/error.py +51 -0
- benchside/domain/shared/event.py +46 -0
- benchside/domain/shared/model/__init__.py +31 -0
- benchside/domain/shared/model/aggregate.py +9 -0
- benchside/domain/shared/model/capture.py +33 -0
- benchside/domain/shared/model/entity.py +5 -0
- benchside/domain/shared/model/gap.py +89 -0
- benchside/domain/shared/model/ids.py +64 -0
- benchside/domain/shared/model/provenance.py +16 -0
- benchside/domain/shared/model/value.py +17 -0
- benchside/domain/shared/port/__init__.py +4 -0
- benchside/domain/shared/port/base.py +9 -0
- benchside/domain/shared/port/journal.py +36 -0
- benchside/domain/shared/query.py +42 -0
- benchside/domain/shared/service.py +31 -0
- benchside/infrastructure/__init__.py +9 -0
- benchside/infrastructure/content/__init__.py +0 -0
- benchside/infrastructure/content/loader.py +108 -0
- benchside/infrastructure/content/renderer.py +129 -0
- benchside/infrastructure/content/writer.py +26 -0
- benchside/infrastructure/files.py +43 -0
- benchside/infrastructure/http_sink.py +128 -0
- benchside/infrastructure/journal/__init__.py +0 -0
- benchside/infrastructure/journal/di.py +85 -0
- benchside/infrastructure/journal/projection.py +244 -0
- benchside/infrastructure/journal/registry.py +24 -0
- benchside/infrastructure/journal/store.py +134 -0
- benchside/infrastructure/placeholders.py +28 -0
- benchside/infrastructure/readable_records.py +211 -0
- benchside/infrastructure/readable_refresh.py +58 -0
- benchside/infrastructure/redaction.py +44 -0
- benchside/infrastructure/session_context.py +225 -0
- benchside/infrastructure/storage_layout.py +104 -0
- benchside/reporting.py +333 -0
- benchside/util/__init__.py +0 -0
- benchside/util/di/__init__.py +4 -0
- benchside/util/di/base.py +16 -0
- benchside/util/di/scope.py +18 -0
- benchside-0.4.1.dist-info/METADATA +97 -0
- benchside-0.4.1.dist-info/RECORD +178 -0
- benchside-0.4.1.dist-info/WHEEL +4 -0
- benchside-0.4.1.dist-info/entry_points.txt +2 -0
- benchside-0.4.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Export value objects.
|
|
2
|
+
|
|
3
|
+
Consent is event-sourced: a grant is never mutated, only superseded by a
|
|
4
|
+
revocation. That is what makes revocation meaningful -- the ledger records
|
|
5
|
+
exactly what left the machine and when.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from enum import StrEnum
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
from benchside.domain.shared.model.gap import Gap
|
|
13
|
+
from benchside.domain.shared.model.ids import GrantId, ObservationId, ProjectId
|
|
14
|
+
from benchside.domain.shared.model.value import ValueObject
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class GrantStatus(StrEnum):
|
|
18
|
+
ACTIVE = "active"
|
|
19
|
+
REVOKED = "revoked"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Grant(ValueObject):
|
|
23
|
+
"""Permission to share observations of the listed gap kinds."""
|
|
24
|
+
|
|
25
|
+
id: GrantId
|
|
26
|
+
gap_kinds: frozenset[str]
|
|
27
|
+
granted_at: datetime
|
|
28
|
+
revoked_at: datetime | None = None
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def status(self) -> GrantStatus:
|
|
32
|
+
return GrantStatus.ACTIVE if self.revoked_at is None else GrantStatus.REVOKED
|
|
33
|
+
|
|
34
|
+
def covers(self, gap: Gap) -> bool:
|
|
35
|
+
return self.revoked_at is None and gap.kind in self.gap_kinds
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Observation(ValueObject):
|
|
39
|
+
"""A captured gap, folded from the journal. Local until an export sends it."""
|
|
40
|
+
|
|
41
|
+
id: ObservationId
|
|
42
|
+
project_id: ProjectId
|
|
43
|
+
gap: Gap
|
|
44
|
+
origin: Literal["benchside", "selected_conversation"] = "benchside"
|
|
45
|
+
basis: Literal["model_inferred", "researcher_reported", "unknown"] = "unknown"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ExportRecord(ValueObject):
|
|
49
|
+
"""Proof of what one export sent. Content-free.
|
|
50
|
+
|
|
51
|
+
Holds ids and a digest of the payload, never the payload itself, so the
|
|
52
|
+
ledger can be audited without re-exposing what it describes.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
grant_id: GrantId
|
|
56
|
+
observation_ids: tuple[ObservationId, ...]
|
|
57
|
+
payload_sha256: str
|
|
58
|
+
exported_at: datetime
|
|
59
|
+
destination: str = ""
|
|
60
|
+
received_at: str | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ExportPreview(ValueObject):
|
|
64
|
+
"""Exactly what would be sent, for the scientist to read before deciding."""
|
|
65
|
+
|
|
66
|
+
payload: str
|
|
67
|
+
observation_ids: tuple[ObservationId, ...]
|
|
68
|
+
withheld: tuple[ObservationId, ...] = ()
|
|
69
|
+
redaction_findings: tuple[str, ...] = ()
|
|
70
|
+
grant_id: GrantId | None = None
|
|
71
|
+
payload_sha256: str = ""
|
|
72
|
+
destination: str = ""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class DeliveryReceipt(ValueObject):
|
|
76
|
+
status: str
|
|
77
|
+
sha256: str
|
|
78
|
+
received_at: str
|
|
79
|
+
observations: int
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Strict legacy and linked gap contracts, including UTF-16 text limits."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from benchside.domain.shared.error import ValidationError
|
|
7
|
+
from benchside.domain.shared.model.gap import GapContext
|
|
8
|
+
|
|
9
|
+
MAX_BYTES = 512 * 1024
|
|
10
|
+
MAX_OBSERVATIONS = 1000
|
|
11
|
+
GAP_FIELDS = {
|
|
12
|
+
"missing_tool": {"task", "reached_for", "why_failed"},
|
|
13
|
+
"unfindable_data": {"sought", "where_searched"},
|
|
14
|
+
"manual_toil": {"task", "frequency"},
|
|
15
|
+
"dead_end": {"approach", "cost"},
|
|
16
|
+
"missing_index": {"question"},
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def validate_gap(gap: dict, *, allow_context: bool = True) -> None:
|
|
21
|
+
if (
|
|
22
|
+
not isinstance(gap, dict)
|
|
23
|
+
or not isinstance(gap.get("kind"), str)
|
|
24
|
+
or gap["kind"] not in GAP_FIELDS
|
|
25
|
+
):
|
|
26
|
+
raise ValidationError("Unknown workflow observation kind")
|
|
27
|
+
context_fields = {"context"} if allow_context and "context" in gap else set()
|
|
28
|
+
if set(gap) != GAP_FIELDS[gap["kind"]] | {"kind"} | context_fields:
|
|
29
|
+
raise ValidationError("Workflow observations contain missing or unknown fields")
|
|
30
|
+
for key, value in gap.items():
|
|
31
|
+
if key == "context":
|
|
32
|
+
if (
|
|
33
|
+
not isinstance(value, dict)
|
|
34
|
+
or not value
|
|
35
|
+
or set(value) - set(GapContext.model_fields)
|
|
36
|
+
):
|
|
37
|
+
raise ValidationError("Invalid optional workflow context")
|
|
38
|
+
for item in value.values():
|
|
39
|
+
_text(item, 2000)
|
|
40
|
+
elif key == "where_searched":
|
|
41
|
+
if not isinstance(value, list) or len(value) > 50:
|
|
42
|
+
raise ValidationError("where_searched must have at most 50 entries")
|
|
43
|
+
for item in value:
|
|
44
|
+
_text(item, 500)
|
|
45
|
+
else:
|
|
46
|
+
_text(value, 2000)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _text(value, maximum):
|
|
50
|
+
if not isinstance(value, str) or len(value.encode("utf-16-le")) // 2 > maximum:
|
|
51
|
+
raise ValidationError(f"Shared text must be a string of at most {maximum} characters")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def validate_payload(payload: str) -> dict:
|
|
55
|
+
if len(payload.encode("utf-8")) > MAX_BYTES:
|
|
56
|
+
raise ValidationError("Batch exceeds the collector's 512 KiB limit")
|
|
57
|
+
try:
|
|
58
|
+
data = json.loads(payload)
|
|
59
|
+
except (TypeError, json.JSONDecodeError) as err:
|
|
60
|
+
raise ValidationError("Invalid export JSON") from err
|
|
61
|
+
contextual = isinstance(data, dict) and data.get("schema") == "benchside.gaps.v3"
|
|
62
|
+
linked = isinstance(data, dict) and (
|
|
63
|
+
data.get("schema") == "benchside.gaps.v2" or (contextual and "contributor_id" in data)
|
|
64
|
+
)
|
|
65
|
+
fields = {"schema", "observations"} | ({"contributor_id"} if linked else set())
|
|
66
|
+
if not isinstance(data, dict) or set(data) != fields:
|
|
67
|
+
raise ValidationError("Invalid export fields")
|
|
68
|
+
if linked and (
|
|
69
|
+
not isinstance(data["contributor_id"], str)
|
|
70
|
+
or not re.fullmatch(r"[a-f0-9]{32}", data["contributor_id"])
|
|
71
|
+
):
|
|
72
|
+
raise ValidationError("Invalid contributor identifier")
|
|
73
|
+
observations = data["observations"]
|
|
74
|
+
if data["schema"] not in {
|
|
75
|
+
"benchside.gaps.v1",
|
|
76
|
+
"benchside.gaps.v2",
|
|
77
|
+
"benchside.gaps.v3",
|
|
78
|
+
} or not isinstance(observations, list):
|
|
79
|
+
raise ValidationError("Invalid export schema")
|
|
80
|
+
if not 1 <= len(observations) <= MAX_OBSERVATIONS:
|
|
81
|
+
raise ValidationError("An export needs 1–1000 observations")
|
|
82
|
+
seen = set()
|
|
83
|
+
for observation in observations:
|
|
84
|
+
provenance = linked and isinstance(observation, dict) and "origin" in observation
|
|
85
|
+
fields = {"id", "gap"} | ({"origin", "basis"} if provenance else set())
|
|
86
|
+
if not isinstance(observation, dict) or set(observation) != fields:
|
|
87
|
+
raise ValidationError("Invalid observation fields")
|
|
88
|
+
if provenance and (
|
|
89
|
+
not isinstance(observation["origin"], str)
|
|
90
|
+
or not isinstance(observation["basis"], str)
|
|
91
|
+
or observation["origin"] not in {"benchside", "selected_conversation"}
|
|
92
|
+
or observation["basis"] not in {"model_inferred", "researcher_reported", "unknown"}
|
|
93
|
+
):
|
|
94
|
+
raise ValidationError("Invalid observation origin or evidence basis")
|
|
95
|
+
identifier = observation["id"]
|
|
96
|
+
if not isinstance(identifier, str) or not re.fullmatch(
|
|
97
|
+
r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}", identifier
|
|
98
|
+
):
|
|
99
|
+
raise ValidationError("Invalid observation identifier")
|
|
100
|
+
if identifier in seen:
|
|
101
|
+
raise ValidationError("Repeated observation identifier")
|
|
102
|
+
seen.add(identifier)
|
|
103
|
+
validate_gap(observation["gap"], allow_context=contextual)
|
|
104
|
+
return data
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
from benchside.domain.export.port.redactor import Finding, Redactor
|
|
2
|
+
from benchside.domain.export.port.repository import ConsentRepository, ObservationReader
|
|
3
|
+
from benchside.domain.export.port.sink import ExportSink
|
|
4
|
+
|
|
5
|
+
__all__ = ["ConsentRepository", "ExportSink", "Finding", "ObservationReader", "Redactor"]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Redaction, applied to everything before it can leave the machine.
|
|
2
|
+
|
|
3
|
+
Scan the exact bytes that will be sent. Never scan a string and then re-render
|
|
4
|
+
it: that reopens a scan-versus-send gap.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from abc import abstractmethod
|
|
8
|
+
from typing import Protocol
|
|
9
|
+
|
|
10
|
+
from benchside.domain.shared.model.value import ValueObject
|
|
11
|
+
from benchside.domain.shared.port.base import Port
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Finding(ValueObject):
|
|
15
|
+
"""Something the redactor objects to, and where."""
|
|
16
|
+
|
|
17
|
+
tier: str
|
|
18
|
+
category: str
|
|
19
|
+
field: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Redactor(Port, Protocol):
|
|
23
|
+
@abstractmethod
|
|
24
|
+
def scan(self, payload: str) -> list[Finding]: ...
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def apply(self, payload: str) -> str: ...
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from abc import abstractmethod
|
|
2
|
+
from typing import Protocol
|
|
3
|
+
|
|
4
|
+
from benchside.domain.export.model.ledger import ConsentLedger
|
|
5
|
+
from benchside.domain.export.model.value import Observation
|
|
6
|
+
from benchside.domain.shared.port.base import Port
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ConsentRepository(Port, Protocol):
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def load(self) -> ConsentLedger: ...
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ObservationReader(Port, Protocol):
|
|
15
|
+
"""Read-only cross-domain port.
|
|
16
|
+
|
|
17
|
+
Gaps are recorded by consultation; this folds GapObserved events out of the
|
|
18
|
+
journal so export never reaches into consultation's aggregates.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def list_all(self) -> list[Observation]: ...
|
|
23
|
+
|
|
24
|
+
@abstractmethod
|
|
25
|
+
def list_unshared(self) -> list[Observation]: ...
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""The one way observations leave the machine.
|
|
2
|
+
|
|
3
|
+
Every implementation must be reachable only through ExportService.export,
|
|
4
|
+
which requires an active grant. A static test enforces that no other module
|
|
5
|
+
imports this port.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from abc import abstractmethod
|
|
9
|
+
from typing import Protocol
|
|
10
|
+
|
|
11
|
+
from benchside.domain.export.model.value import DeliveryReceipt
|
|
12
|
+
from benchside.domain.shared.port.base import Port
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ExportSink(Port, Protocol):
|
|
16
|
+
destination: str
|
|
17
|
+
|
|
18
|
+
@abstractmethod
|
|
19
|
+
def send(self, payload: str) -> DeliveryReceipt | None: ...
|
|
File without changes
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from pydantic import Field
|
|
2
|
+
|
|
3
|
+
from benchside.domain.export.service.consent import ConsentService
|
|
4
|
+
from benchside.domain.shared.command import Result
|
|
5
|
+
from benchside.domain.shared.model.ids import GrantId
|
|
6
|
+
from benchside.domain.shared.query import Query, QueryHandler
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class GetConsentStatus(Query):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ConsentStatus(Result):
|
|
14
|
+
has_active_grant: bool
|
|
15
|
+
grant_id: GrantId | None = None
|
|
16
|
+
gap_kinds: list[str] = Field(default_factory=list)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class GetConsentStatusHandler(QueryHandler[GetConsentStatus, ConsentStatus]):
|
|
20
|
+
consent_service: ConsentService
|
|
21
|
+
|
|
22
|
+
def run(self, query: GetConsentStatus) -> ConsentStatus:
|
|
23
|
+
grant = self.consent_service.active_grant()
|
|
24
|
+
if grant is None:
|
|
25
|
+
return ConsentStatus(has_active_grant=False)
|
|
26
|
+
return ConsentStatus(
|
|
27
|
+
has_active_grant=True,
|
|
28
|
+
grant_id=grant.id,
|
|
29
|
+
gap_kinds=sorted(grant.gap_kinds),
|
|
30
|
+
)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""What the scientist reads before deciding to share.
|
|
2
|
+
|
|
3
|
+
The payload is the literal bytes an export would send, not a summary of them.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from pydantic import Field
|
|
7
|
+
|
|
8
|
+
from benchside.domain.export.service.export import ExportService
|
|
9
|
+
from benchside.domain.shared.command import Result
|
|
10
|
+
from benchside.domain.shared.model.ids import ObservationId
|
|
11
|
+
from benchside.domain.shared.query import Query, QueryHandler
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PreviewExport(Query):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ExportPreviewDetail(Result):
|
|
19
|
+
payload: str
|
|
20
|
+
observation_ids: list[ObservationId] = Field(default_factory=list)
|
|
21
|
+
withheld: list[ObservationId] = Field(default_factory=list)
|
|
22
|
+
redaction_findings: list[str] = Field(default_factory=list)
|
|
23
|
+
has_active_grant: bool = False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PreviewExportHandler(QueryHandler[PreviewExport, ExportPreviewDetail]):
|
|
27
|
+
export_service: ExportService
|
|
28
|
+
|
|
29
|
+
def run(self, query: PreviewExport) -> ExportPreviewDetail:
|
|
30
|
+
preview = self.export_service.preview()
|
|
31
|
+
return ExportPreviewDetail(
|
|
32
|
+
payload=preview.payload,
|
|
33
|
+
observation_ids=list(preview.observation_ids),
|
|
34
|
+
withheld=list(preview.withheld),
|
|
35
|
+
redaction_findings=list(preview.redaction_findings),
|
|
36
|
+
has_active_grant=self.export_service.consent.has_active_grant(),
|
|
37
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Consent business logic.
|
|
2
|
+
|
|
3
|
+
The sole authority on whether anything may be shared. ExportService asks this
|
|
4
|
+
service and nothing else.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
|
|
10
|
+
from benchside.domain.export.event.consent_granted import ConsentGranted
|
|
11
|
+
from benchside.domain.export.event.consent_revoked import ConsentRevoked
|
|
12
|
+
from benchside.domain.export.model.value import Grant
|
|
13
|
+
from benchside.domain.export.port.repository import ConsentRepository
|
|
14
|
+
from benchside.domain.shared.event import new_event_id
|
|
15
|
+
from benchside.domain.shared.model.gap import GAP_KINDS
|
|
16
|
+
from benchside.domain.shared.model.ids import CONSENT_LEDGER_PROJECT, GrantId
|
|
17
|
+
from benchside.domain.shared.port.journal import Journal
|
|
18
|
+
from benchside.domain.shared.service import Service
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ConsentService(Service):
|
|
24
|
+
repository: ConsentRepository
|
|
25
|
+
journal: Journal
|
|
26
|
+
|
|
27
|
+
def active_grant(self) -> Grant | None:
|
|
28
|
+
return self.repository.load().active_grant
|
|
29
|
+
|
|
30
|
+
def has_active_grant(self) -> bool:
|
|
31
|
+
return self.active_grant() is not None
|
|
32
|
+
|
|
33
|
+
def grant(self, *, grant_id: GrantId, gap_kinds: frozenset[str]) -> Grant:
|
|
34
|
+
unknown = gap_kinds - GAP_KINDS
|
|
35
|
+
if unknown:
|
|
36
|
+
raise ValueError(f"Unknown gap kinds: {sorted(unknown)}")
|
|
37
|
+
ledger = self.repository.load()
|
|
38
|
+
grant = Grant(id=grant_id, gap_kinds=gap_kinds, granted_at=datetime.now(UTC))
|
|
39
|
+
ledger.grant(grant)
|
|
40
|
+
self.journal.append(
|
|
41
|
+
CONSENT_LEDGER_PROJECT,
|
|
42
|
+
ConsentGranted(id=new_event_id(), grant_id=grant_id, gap_kinds=gap_kinds),
|
|
43
|
+
)
|
|
44
|
+
return grant
|
|
45
|
+
|
|
46
|
+
def revoke(self) -> Grant:
|
|
47
|
+
ledger = self.repository.load()
|
|
48
|
+
revoked = ledger.revoke(datetime.now(UTC))
|
|
49
|
+
self.journal.append(
|
|
50
|
+
CONSENT_LEDGER_PROJECT,
|
|
51
|
+
ConsentRevoked(id=new_event_id(), grant_id=revoked.id),
|
|
52
|
+
)
|
|
53
|
+
return revoked
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Consent and approval are checked against the exact frozen bytes at send time."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import field
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
|
|
8
|
+
from benchside.domain.export.event.observations_exported import ObservationsExported
|
|
9
|
+
from benchside.domain.export.model.value import ExportPreview, ExportRecord
|
|
10
|
+
from benchside.domain.export.model.wire import (
|
|
11
|
+
MAX_BYTES,
|
|
12
|
+
MAX_OBSERVATIONS,
|
|
13
|
+
validate_gap,
|
|
14
|
+
validate_payload,
|
|
15
|
+
)
|
|
16
|
+
from benchside.domain.export.port.redactor import Redactor
|
|
17
|
+
from benchside.domain.export.port.repository import ConsentRepository, ObservationReader
|
|
18
|
+
from benchside.domain.export.port.sink import ExportSink
|
|
19
|
+
from benchside.domain.export.service.consent import CONSENT_LEDGER_PROJECT, ConsentService
|
|
20
|
+
from benchside.domain.shared.error import ConsentRequiredError, ValidationError
|
|
21
|
+
from benchside.domain.shared.event import new_event_id
|
|
22
|
+
from benchside.domain.shared.port.journal import Journal
|
|
23
|
+
from benchside.domain.shared.service import Service
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ExportService(Service):
|
|
27
|
+
observations: ObservationReader
|
|
28
|
+
consent: ConsentService
|
|
29
|
+
redactor: Redactor
|
|
30
|
+
sink: ExportSink
|
|
31
|
+
ledger: ConsentRepository
|
|
32
|
+
journal: Journal
|
|
33
|
+
# Set by the sharing adapter only after the linked-sharing policy is accepted.
|
|
34
|
+
# This is configuration, not a dependency for the legacy CLI composition root.
|
|
35
|
+
contributor_id: str | None = field(default=None, init=False)
|
|
36
|
+
|
|
37
|
+
def preview(self, *, only=None, edits=None) -> ExportPreview:
|
|
38
|
+
previews = self.previews(only=only, edits=edits)
|
|
39
|
+
if len(previews) > 1:
|
|
40
|
+
raise ValidationError(
|
|
41
|
+
"Several batches are needed; review each batch using share preview"
|
|
42
|
+
)
|
|
43
|
+
return previews[0]
|
|
44
|
+
|
|
45
|
+
def previews(self, *, only=None, edits=None) -> tuple[ExportPreview, ...]:
|
|
46
|
+
grant = self.consent.active_grant()
|
|
47
|
+
unshared = self.observations.list_unshared()
|
|
48
|
+
covered = [
|
|
49
|
+
o
|
|
50
|
+
for o in unshared
|
|
51
|
+
if grant is not None and grant.covers(o.gap) and (only is None or o.id in only)
|
|
52
|
+
]
|
|
53
|
+
if only is not None and set(only) - {o.id for o in covered}:
|
|
54
|
+
raise ValidationError("Selection includes unknown, shared or unconsented observations")
|
|
55
|
+
edits = edits or {}
|
|
56
|
+
if set(edits) - {o.id for o in covered}:
|
|
57
|
+
raise ValidationError("Edits must refer to selected observations")
|
|
58
|
+
withheld = tuple(o.id for o in unshared if o not in covered)
|
|
59
|
+
batches, batch = [], []
|
|
60
|
+
for observation in covered:
|
|
61
|
+
gap = edits.get(observation.id, observation.gap.model_dump(mode="json"))
|
|
62
|
+
validate_gap(gap)
|
|
63
|
+
if gap["kind"] != observation.gap.kind:
|
|
64
|
+
raise ValidationError("An edit cannot change an observation's kind")
|
|
65
|
+
item = {"id": observation.id, "gap": gap}
|
|
66
|
+
if self.contributor_id:
|
|
67
|
+
item.update(origin=observation.origin, basis=observation.basis)
|
|
68
|
+
candidate = self.redactor.apply(self._payload(batch + [item]))
|
|
69
|
+
if batch and (
|
|
70
|
+
len(batch) == MAX_OBSERVATIONS or len(candidate.encode("utf-8")) > MAX_BYTES
|
|
71
|
+
):
|
|
72
|
+
batches.append(batch)
|
|
73
|
+
batch = []
|
|
74
|
+
batch.append(item)
|
|
75
|
+
batches.append(batch)
|
|
76
|
+
result = []
|
|
77
|
+
for items in batches:
|
|
78
|
+
payload = self.redactor.apply(self._payload(items))
|
|
79
|
+
if items:
|
|
80
|
+
validate_payload(payload)
|
|
81
|
+
result.append(
|
|
82
|
+
ExportPreview(
|
|
83
|
+
payload=payload,
|
|
84
|
+
observation_ids=tuple(o["id"] for o in items),
|
|
85
|
+
withheld=withheld,
|
|
86
|
+
grant_id=grant.id if grant else None,
|
|
87
|
+
payload_sha256=self._digest(payload),
|
|
88
|
+
destination=self.sink.destination,
|
|
89
|
+
redaction_findings=tuple(
|
|
90
|
+
f"{f.tier}:{f.category} in {f.field}" for f in self.redactor.scan(payload)
|
|
91
|
+
),
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
return tuple(result)
|
|
95
|
+
|
|
96
|
+
def export(
|
|
97
|
+
self, *, preview: ExportPreview | None = None, approved_sha256: str | None = None
|
|
98
|
+
) -> ExportRecord:
|
|
99
|
+
grant = self.consent.active_grant()
|
|
100
|
+
if grant is None:
|
|
101
|
+
raise ConsentRequiredError("No active consent grant; nothing was shared")
|
|
102
|
+
if preview is None:
|
|
103
|
+
if not any(grant.covers(o.gap) for o in self.observations.list_unshared()):
|
|
104
|
+
return ExportRecord(
|
|
105
|
+
grant_id=grant.id,
|
|
106
|
+
observation_ids=(),
|
|
107
|
+
payload_sha256="",
|
|
108
|
+
exported_at=datetime.now(UTC),
|
|
109
|
+
)
|
|
110
|
+
raise ConsentRequiredError("An exact reviewed preview and its approval are required")
|
|
111
|
+
if preview.grant_id != grant.id:
|
|
112
|
+
raise ConsentRequiredError("The consent changed; review the export again")
|
|
113
|
+
digest = self._digest(preview.payload)
|
|
114
|
+
if digest != preview.payload_sha256 or digest != approved_sha256:
|
|
115
|
+
raise ConsentRequiredError("The reviewed payload changed or has not been approved")
|
|
116
|
+
if preview.destination != self.sink.destination:
|
|
117
|
+
raise ConsentRequiredError("The destination changed; review the export again")
|
|
118
|
+
for previous in self.ledger.load().exports:
|
|
119
|
+
if previous.payload_sha256 == digest and previous.destination == preview.destination:
|
|
120
|
+
return previous
|
|
121
|
+
data = validate_payload(preview.payload)
|
|
122
|
+
ids = tuple(o["id"] for o in data["observations"])
|
|
123
|
+
if ids != preview.observation_ids:
|
|
124
|
+
raise ValidationError("Preview identifiers do not match its payload")
|
|
125
|
+
current = {o.id: o for o in self.observations.list_unshared()}
|
|
126
|
+
for item in data["observations"]:
|
|
127
|
+
original = current.get(item["id"])
|
|
128
|
+
if (
|
|
129
|
+
original is None
|
|
130
|
+
or not grant.covers(original.gap)
|
|
131
|
+
or original.gap.kind != item["gap"]["kind"]
|
|
132
|
+
):
|
|
133
|
+
raise ConsentRequiredError("Observation selection changed; review the export again")
|
|
134
|
+
if any(f.tier == "HIGH" for f in self.redactor.scan(preview.payload)):
|
|
135
|
+
raise ValidationError("Sensitive content remains; edit and review before sending")
|
|
136
|
+
receipt = self.sink.send(preview.payload)
|
|
137
|
+
event = ObservationsExported(
|
|
138
|
+
id=new_event_id(),
|
|
139
|
+
grant_id=grant.id,
|
|
140
|
+
observation_ids=ids,
|
|
141
|
+
payload_sha256=digest,
|
|
142
|
+
destination=preview.destination,
|
|
143
|
+
received_at=receipt.received_at if receipt else None,
|
|
144
|
+
)
|
|
145
|
+
self.journal.append(CONSENT_LEDGER_PROJECT, event)
|
|
146
|
+
return ExportRecord(
|
|
147
|
+
grant_id=grant.id,
|
|
148
|
+
observation_ids=ids,
|
|
149
|
+
payload_sha256=digest,
|
|
150
|
+
exported_at=event.recorded_at,
|
|
151
|
+
destination=event.destination,
|
|
152
|
+
received_at=event.received_at,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
def _payload(self, observations: list[dict]) -> str:
|
|
156
|
+
schema = "benchside.gaps.v2" if self.contributor_id else "benchside.gaps.v1"
|
|
157
|
+
if any("context" in item["gap"] for item in observations):
|
|
158
|
+
schema = "benchside.gaps.v3"
|
|
159
|
+
return json.dumps(
|
|
160
|
+
{
|
|
161
|
+
"schema": schema,
|
|
162
|
+
**({"contributor_id": self.contributor_id} if self.contributor_id else {}),
|
|
163
|
+
"observations": observations,
|
|
164
|
+
},
|
|
165
|
+
ensure_ascii=False,
|
|
166
|
+
indent=2,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
@staticmethod
|
|
170
|
+
def _digest(payload: str) -> str:
|
|
171
|
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|