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,64 @@
|
|
|
1
|
+
"""Typed identifiers.
|
|
2
|
+
|
|
3
|
+
No bare primitives across boundaries: a PersonaId can never be passed where a
|
|
4
|
+
ProjectId is expected.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from typing import ClassVar, NewType
|
|
9
|
+
|
|
10
|
+
from pydantic import field_validator
|
|
11
|
+
|
|
12
|
+
from benchside.domain.shared.model.value import RootValueObject
|
|
13
|
+
|
|
14
|
+
ConsultationId = NewType("ConsultationId", str)
|
|
15
|
+
HypothesisId = NewType("HypothesisId", str)
|
|
16
|
+
CritiqueId = NewType("CritiqueId", str)
|
|
17
|
+
DecisionId = NewType("DecisionId", str)
|
|
18
|
+
ObservationId = NewType("ObservationId", str)
|
|
19
|
+
GrantId = NewType("GrantId", str)
|
|
20
|
+
|
|
21
|
+
_SLUG = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ProjectId(RootValueObject[str]):
|
|
25
|
+
"""The unit of continuity: one line of work, journalled together.
|
|
26
|
+
|
|
27
|
+
Slug-shaped so it is safe as a directory name under the state root.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
_re: ClassVar[re.Pattern[str]] = _SLUG
|
|
31
|
+
|
|
32
|
+
@field_validator("root")
|
|
33
|
+
@classmethod
|
|
34
|
+
def _validate(cls, v: str) -> str:
|
|
35
|
+
v = v.strip().lower()
|
|
36
|
+
if not _SLUG.match(v):
|
|
37
|
+
raise ValueError("invalid ProjectId (expected a lowercase slug)")
|
|
38
|
+
return v
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PersonaId(RootValueObject[str]):
|
|
42
|
+
"""Identifies a persona record in content/personas/."""
|
|
43
|
+
|
|
44
|
+
_re: ClassVar[re.Pattern[str]] = _SLUG
|
|
45
|
+
|
|
46
|
+
@field_validator("root")
|
|
47
|
+
@classmethod
|
|
48
|
+
def _validate(cls, v: str) -> str:
|
|
49
|
+
v = v.strip().lower()
|
|
50
|
+
if not _SLUG.match(v):
|
|
51
|
+
raise ValueError("invalid PersonaId (expected a lowercase slug)")
|
|
52
|
+
return v
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
CONSENT_LEDGER_PROJECT = ProjectId("consent-ledger")
|
|
56
|
+
"""Reserved stream for machine-wide consent events. Not a user project."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def user_project_id(raw: str) -> ProjectId:
|
|
60
|
+
"""Parse a user-supplied project id, rejecting reserved names."""
|
|
61
|
+
project_id = ProjectId(raw)
|
|
62
|
+
if project_id == CONSENT_LEDGER_PROJECT or project_id.root == "reporting-ledger":
|
|
63
|
+
raise ValueError(f"'{raw}' is reserved for the consent ledger")
|
|
64
|
+
return project_id
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Private, content-free context for the app that produced a journal event."""
|
|
2
|
+
|
|
3
|
+
from typing import Annotated, Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, StringConstraints
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AppProvenance(BaseModel):
|
|
9
|
+
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
|
|
10
|
+
|
|
11
|
+
host: Literal["chatgpt", "claude", "unknown"] = "unknown"
|
|
12
|
+
app_version: (
|
|
13
|
+
Annotated[str, StringConstraints(pattern=r"^[0-9][A-Za-z0-9.-]{0,39}$")]
|
|
14
|
+
| Literal["unknown"]
|
|
15
|
+
) = "unknown"
|
|
16
|
+
surface: Literal["web", "desktop", "cli", "unknown"] = "unknown"
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from typing import Generic, TypeVar
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict, RootModel
|
|
4
|
+
|
|
5
|
+
T = TypeVar("T")
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ValueObject(BaseModel):
|
|
9
|
+
"""Defined by its attributes, not identity. Frozen."""
|
|
10
|
+
|
|
11
|
+
model_config = ConfigDict(frozen=True)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class RootValueObject(RootModel[T], Generic[T]):
|
|
15
|
+
"""A validated wrapper over a single primitive (an id, a slug, a version)."""
|
|
16
|
+
|
|
17
|
+
model_config = ConfigDict(frozen=True)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""The journal port.
|
|
2
|
+
|
|
3
|
+
Kernel rather than domain-owned: consultation appends, export reads. One
|
|
4
|
+
append-only stream per project.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from abc import abstractmethod
|
|
8
|
+
from collections.abc import Iterable
|
|
9
|
+
from typing import Protocol
|
|
10
|
+
|
|
11
|
+
from benchside.domain.shared.event import Event
|
|
12
|
+
from benchside.domain.shared.model.ids import ProjectId
|
|
13
|
+
from benchside.domain.shared.port.base import Port
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Journal(Port, Protocol):
|
|
17
|
+
"""Append-only event stream, partitioned by project.
|
|
18
|
+
|
|
19
|
+
Implementations must append atomically and must never rewrite history:
|
|
20
|
+
corrections are new events that supersede old ones.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
@abstractmethod
|
|
24
|
+
def append(self, project_id: ProjectId, event: Event) -> None: ...
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def read(self, project_id: ProjectId) -> Iterable[Event]: ...
|
|
28
|
+
|
|
29
|
+
@abstractmethod
|
|
30
|
+
def read_envelopes(self, project_id: ProjectId) -> Iterable[dict]:
|
|
31
|
+
"""Raw records: type, session (the Claude conversation id that
|
|
32
|
+
produced the event, when known), and data."""
|
|
33
|
+
...
|
|
34
|
+
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def projects(self) -> Iterable[ProjectId]: ...
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Query side: the read half of CQRS.
|
|
2
|
+
|
|
3
|
+
Same shape as command.py -- Query DTO, Result DTO, Handler per file -- but
|
|
4
|
+
handlers must not mutate state.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from abc import ABCMeta, abstractmethod
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Generic, TypeVar, dataclass_transform
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel
|
|
12
|
+
|
|
13
|
+
from benchside.domain.shared.command import Result
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Query(BaseModel):
|
|
17
|
+
"""A request for state. Also the CLI argument shape."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass_transform()
|
|
21
|
+
class _QueryHandlerMeta(ABCMeta):
|
|
22
|
+
def __new__(
|
|
23
|
+
mcs,
|
|
24
|
+
name: str,
|
|
25
|
+
bases: tuple[type, ...],
|
|
26
|
+
namespace: dict[str, Any],
|
|
27
|
+
) -> type:
|
|
28
|
+
cls = super().__new__(mcs, name, bases, namespace)
|
|
29
|
+
if any(isinstance(b, mcs) for b in bases):
|
|
30
|
+
return dataclass(cls)
|
|
31
|
+
return cls
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
Q = TypeVar("Q", bound=Query)
|
|
35
|
+
R = TypeVar("R", bound=Result)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class QueryHandler(Generic[Q, R], metaclass=_QueryHandlerMeta):
|
|
39
|
+
"""Entry point for a read. Delegates to a service; never mutates."""
|
|
40
|
+
|
|
41
|
+
@abstractmethod
|
|
42
|
+
def run(self, query: Q) -> R: ...
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Service base.
|
|
2
|
+
|
|
3
|
+
Subclasses declare their dependencies as annotated fields; the metaclass makes
|
|
4
|
+
them dataclasses so Dishka can construct them by keyword.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, dataclass_transform
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass_transform()
|
|
12
|
+
class _ServiceMeta(type):
|
|
13
|
+
def __new__(
|
|
14
|
+
mcs,
|
|
15
|
+
name: str,
|
|
16
|
+
bases: tuple[type, ...],
|
|
17
|
+
namespace: dict[str, Any],
|
|
18
|
+
) -> type:
|
|
19
|
+
cls = super().__new__(mcs, name, bases, namespace)
|
|
20
|
+
if any(isinstance(b, mcs) for b in bases):
|
|
21
|
+
return dataclass(cls)
|
|
22
|
+
return cls
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Service(metaclass=_ServiceMeta):
|
|
26
|
+
"""Base for domain services. Subclasses are automatically dataclasses.
|
|
27
|
+
|
|
28
|
+
Services hold the business logic. They depend on their own domain's ports,
|
|
29
|
+
on the journal, and on other domains' services -- never on another domain's
|
|
30
|
+
repository directly.
|
|
31
|
+
"""
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Port implementations.
|
|
2
|
+
|
|
3
|
+
One subpackage per technology, each with a `di.py` exposing a
|
|
4
|
+
`<Tech>Provider` that binds ports to concrete classes via `provides=`.
|
|
5
|
+
Planned: `journal/` (JSONL append-only store), `content/` (persona and
|
|
6
|
+
template loading from content/), `redact/` (the redaction engine).
|
|
7
|
+
|
|
8
|
+
Nothing here may be imported from benchside/domain/.
|
|
9
|
+
"""
|
|
File without changes
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Loading persona records and templates from content/.
|
|
2
|
+
|
|
3
|
+
Personas are authored as YAML. Adding a specialist means adding a file here --
|
|
4
|
+
never touching orchestration code.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import yaml
|
|
12
|
+
|
|
13
|
+
from benchside.domain.authoring.model.flow import Flow, Phase
|
|
14
|
+
from benchside.domain.authoring.model.persona import Persona
|
|
15
|
+
from benchside.domain.authoring.model.value import FailureMode, ForcingQuestion
|
|
16
|
+
from benchside.domain.shared.error import ValidationError
|
|
17
|
+
from benchside.domain.shared.model.ids import PersonaId
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class YamlPersonaRepository:
|
|
23
|
+
def __init__(self, personas_dir: Path) -> None:
|
|
24
|
+
self._dir = personas_dir
|
|
25
|
+
|
|
26
|
+
def get(self, persona_id: PersonaId) -> Persona | None:
|
|
27
|
+
path = self._dir / f"{persona_id.root}.yaml"
|
|
28
|
+
if not path.exists():
|
|
29
|
+
return None
|
|
30
|
+
return self._parse(path)
|
|
31
|
+
|
|
32
|
+
def list_all(self) -> list[Persona]:
|
|
33
|
+
if not self._dir.exists():
|
|
34
|
+
return []
|
|
35
|
+
return [self._parse(p) for p in sorted(self._dir.glob("*.yaml"))]
|
|
36
|
+
|
|
37
|
+
def _parse(self, path: Path) -> Persona:
|
|
38
|
+
raw: dict[str, Any] = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
39
|
+
try:
|
|
40
|
+
return Persona(
|
|
41
|
+
id=PersonaId(raw.get("id", path.stem)),
|
|
42
|
+
**{
|
|
43
|
+
key: raw[key]
|
|
44
|
+
for key in (
|
|
45
|
+
"title",
|
|
46
|
+
"description",
|
|
47
|
+
"version",
|
|
48
|
+
"critique_requires_hypothesis",
|
|
49
|
+
"record_kind",
|
|
50
|
+
)
|
|
51
|
+
if key in raw
|
|
52
|
+
},
|
|
53
|
+
stance=raw["stance"],
|
|
54
|
+
expertise=tuple(raw.get("expertise", ())),
|
|
55
|
+
voice=raw["voice"],
|
|
56
|
+
forcing_questions=tuple(
|
|
57
|
+
ForcingQuestion(
|
|
58
|
+
ask=q["ask"],
|
|
59
|
+
push_until=q["push_until"],
|
|
60
|
+
red_flags=tuple(q.get("red_flags", ())),
|
|
61
|
+
)
|
|
62
|
+
for q in raw.get("forcing_questions", ())
|
|
63
|
+
),
|
|
64
|
+
failure_modes=tuple(
|
|
65
|
+
FailureMode(name=f["name"], description=f["description"])
|
|
66
|
+
for f in raw.get("failure_modes", ())
|
|
67
|
+
),
|
|
68
|
+
escalation_rules=tuple(raw.get("escalation_rules", ())),
|
|
69
|
+
flow=_parse_flow(raw.get("flow", {})),
|
|
70
|
+
)
|
|
71
|
+
except (KeyError, TypeError, ValueError) as err:
|
|
72
|
+
raise ValidationError(f"Malformed persona record at {path}: {err}") from err
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _parse_flow(raw: dict[str, Any]) -> Flow:
|
|
76
|
+
from benchside.domain.shared.model.capture import CaptureKind, CloseRequirement
|
|
77
|
+
|
|
78
|
+
return Flow(
|
|
79
|
+
phases=tuple(
|
|
80
|
+
Phase(
|
|
81
|
+
id=p["id"],
|
|
82
|
+
goal=p["goal"],
|
|
83
|
+
guidance=p.get("guidance", ""),
|
|
84
|
+
captures=tuple(CaptureKind(c) for c in p.get("captures", ())),
|
|
85
|
+
exit_when=p.get("exit_when", ""),
|
|
86
|
+
)
|
|
87
|
+
for p in raw.get("phases", ())
|
|
88
|
+
),
|
|
89
|
+
close_requires=tuple(
|
|
90
|
+
CloseRequirement(kind=CaptureKind(r["kind"]), minimum=int(r.get("minimum", 1)))
|
|
91
|
+
for r in raw.get("close_requires", ())
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class FileTemplateRepository:
|
|
97
|
+
def __init__(self, templates_dir: Path) -> None:
|
|
98
|
+
self._dir = templates_dir
|
|
99
|
+
|
|
100
|
+
def skill_template(self) -> str:
|
|
101
|
+
path = self._dir / "skill.md.tmpl"
|
|
102
|
+
if not path.exists():
|
|
103
|
+
raise ValidationError(f"Missing skill template at {path}")
|
|
104
|
+
return path.read_text(encoding="utf-8")
|
|
105
|
+
|
|
106
|
+
def block(self, name: str) -> str | None:
|
|
107
|
+
path = self._dir / "blocks" / f"{name}.md"
|
|
108
|
+
return path.read_text(encoding="utf-8") if path.exists() else None
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Template rendering.
|
|
2
|
+
|
|
3
|
+
Expands {{PLACEHOLDER}} tokens against a persona and the shared block library.
|
|
4
|
+
Two rules, both enforced rather than documented: an unknown placeholder is a
|
|
5
|
+
hard error, and any token left unresolved after expansion is a hard error.
|
|
6
|
+
Silent empties are how generated prompts rot.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
12
|
+
from benchside.domain.authoring.model.persona import Persona
|
|
13
|
+
from benchside.domain.authoring.port.repository import TemplateRepository
|
|
14
|
+
from benchside.domain.shared.error import ValidationError
|
|
15
|
+
|
|
16
|
+
_TOKEN = re.compile(r"\{\{([A-Z_]+)\}\}")
|
|
17
|
+
_MAX_PASSES = 5
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PlaceholderRenderer:
|
|
21
|
+
"""Multi-pass so blocks may themselves contain placeholders."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, templates: TemplateRepository, *, app: bool = False) -> None:
|
|
24
|
+
self._templates = templates
|
|
25
|
+
self._app = app
|
|
26
|
+
|
|
27
|
+
def render(self, template: str, persona: Persona) -> str:
|
|
28
|
+
resolvers = self._resolvers(persona)
|
|
29
|
+
text = template
|
|
30
|
+
for _ in range(_MAX_PASSES):
|
|
31
|
+
if not _TOKEN.search(text):
|
|
32
|
+
break
|
|
33
|
+
text = _TOKEN.sub(lambda m: self._resolve(m.group(1), resolvers), text)
|
|
34
|
+
remaining = _TOKEN.findall(text)
|
|
35
|
+
if remaining:
|
|
36
|
+
raise ValidationError(
|
|
37
|
+
f"Unresolved placeholders after {_MAX_PASSES} passes: {remaining}"
|
|
38
|
+
)
|
|
39
|
+
return text
|
|
40
|
+
|
|
41
|
+
def _resolve(self, name: str, resolvers: dict[str, Callable[[], str]]) -> str:
|
|
42
|
+
if name in resolvers:
|
|
43
|
+
return resolvers[name]()
|
|
44
|
+
block = self._templates.block(name.lower().replace("_", "-"))
|
|
45
|
+
if block is not None:
|
|
46
|
+
return block
|
|
47
|
+
raise ValidationError(f"Unknown placeholder: {{{{{name}}}}}")
|
|
48
|
+
|
|
49
|
+
def _resolvers(self, persona: Persona) -> dict[str, Callable[[], str]]:
|
|
50
|
+
return {
|
|
51
|
+
"PERSONA_ID": lambda: persona.id.root,
|
|
52
|
+
"PERSONA_TITLE": lambda: persona.title,
|
|
53
|
+
"PERSONA_DESCRIPTION": lambda: persona.description,
|
|
54
|
+
"PERSONA_STANCE": lambda: persona.stance,
|
|
55
|
+
"PERSONA_VOICE": lambda: persona.voice,
|
|
56
|
+
"PERSONA_EXPERTISE": lambda: ", ".join(persona.expertise),
|
|
57
|
+
"FORCING_QUESTIONS": lambda: _forcing_questions(persona),
|
|
58
|
+
"FLOW": lambda: _flow(persona, app=self._app),
|
|
59
|
+
"FAILURE_MODES": lambda: _failure_modes(persona),
|
|
60
|
+
"ESCALATION_RULES": lambda: _escalation_rules(persona),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
_CAPTURE_CALL = {
|
|
65
|
+
"question": 'bench question "<question>"',
|
|
66
|
+
"answer": 'bench answer <question-id> "<answer>"',
|
|
67
|
+
"hypothesis": 'bench hypothesis "<statement>"',
|
|
68
|
+
"critique": "bench critique --target <claim|method|interpretation> ...",
|
|
69
|
+
"resolution": "bench resolve <critique-id> --as <resolution>",
|
|
70
|
+
"decision": 'bench decide "<decision>" --because "<rationale>"',
|
|
71
|
+
"gap": "bench gap <kind> ...",
|
|
72
|
+
"record": 'bench record --kind <kind> --summary "..." --detail "..." [--source "..."]',
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
_APP_CAPTURE_ACTION = {"decision": "decide", "resolution": "resolve"}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _flow(persona: Persona, *, app: bool = False) -> str:
|
|
79
|
+
"""Render the persona's phases as numbered sections with explicit
|
|
80
|
+
bench-call obligations derived from each phase's captures."""
|
|
81
|
+
if not persona.flow.phases:
|
|
82
|
+
return "_No flow declared._"
|
|
83
|
+
parts = []
|
|
84
|
+
for i, phase in enumerate(persona.flow.phases, start=1):
|
|
85
|
+
section = [f"### Phase {i} — `{phase.id}`: {phase.goal}", "", phase.guidance.rstrip()]
|
|
86
|
+
for kind in phase.captures:
|
|
87
|
+
call = (
|
|
88
|
+
f"{_APP_CAPTURE_ACTION.get(kind.value, kind.value)} adapter action"
|
|
89
|
+
if app
|
|
90
|
+
else _CAPTURE_CALL[kind.value]
|
|
91
|
+
)
|
|
92
|
+
if kind.value in {"critique", "gap", "resolution", "question", "answer"}:
|
|
93
|
+
section.append(f"\n**When this occurs, record it:** run `{call}`. Never invent it.")
|
|
94
|
+
else:
|
|
95
|
+
when = (
|
|
96
|
+
"Only after the researcher has actually chosen, record their decision"
|
|
97
|
+
if kind.value == "decision" else "Before moving on, record it"
|
|
98
|
+
)
|
|
99
|
+
section.append(f"\n**{when}:** run `{call}`.")
|
|
100
|
+
if phase.exit_when:
|
|
101
|
+
section.append(f"\n**Move on when:** {phase.exit_when}")
|
|
102
|
+
parts.append("\n".join(section))
|
|
103
|
+
return "\n\n".join(parts)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _forcing_questions(persona: Persona) -> str:
|
|
107
|
+
if not persona.forcing_questions:
|
|
108
|
+
return "_No forcing questions declared._"
|
|
109
|
+
parts = []
|
|
110
|
+
for i, q in enumerate(persona.forcing_questions, start=1):
|
|
111
|
+
flags = "\n".join(f" - {flag}" for flag in q.red_flags)
|
|
112
|
+
parts.append(
|
|
113
|
+
f"### Q{i}. {q.ask}\n\n"
|
|
114
|
+
f"**What to clarify:** {q.push_until}\n\n"
|
|
115
|
+
f"**Signals that clarification may help:**\n{flags}"
|
|
116
|
+
)
|
|
117
|
+
return "\n\n".join(parts)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _failure_modes(persona: Persona) -> str:
|
|
121
|
+
if not persona.failure_modes:
|
|
122
|
+
return "_No failure modes declared._"
|
|
123
|
+
return "\n".join(f"- **{f.name}** — {f.description}" for f in persona.failure_modes)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _escalation_rules(persona: Persona) -> str:
|
|
127
|
+
if not persona.escalation_rules:
|
|
128
|
+
return "_No escalation rules declared._"
|
|
129
|
+
return "\n".join(f"- {rule}" for rule in persona.escalation_rules)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Writing compiled skills to skills/<persona>/SKILL.md."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from benchside.domain.authoring.model.skill import SkillDocument
|
|
6
|
+
from benchside.domain.shared.error import StorageUnavailableError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FileSkillWriter:
|
|
10
|
+
def __init__(self, target_dir: Path) -> None:
|
|
11
|
+
self._dir = target_dir
|
|
12
|
+
|
|
13
|
+
def write(self, document: SkillDocument) -> None:
|
|
14
|
+
path = self._path(document.filename)
|
|
15
|
+
try:
|
|
16
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
17
|
+
path.write_text(document.render(), encoding="utf-8")
|
|
18
|
+
except OSError as err:
|
|
19
|
+
raise StorageUnavailableError(f"Could not write skill to {path}: {err}") from err
|
|
20
|
+
|
|
21
|
+
def read_existing(self, filename: str) -> str | None:
|
|
22
|
+
path = self._path(filename)
|
|
23
|
+
return path.read_text(encoding="utf-8") if path.exists() else None
|
|
24
|
+
|
|
25
|
+
def _path(self, filename: str):
|
|
26
|
+
return self._dir / filename
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Small durable-file primitives. State is outside project source control."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import tempfile
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@contextmanager
|
|
11
|
+
def file_lock(path: Path):
|
|
12
|
+
"""Serialize read/validate/write transactions on supported POSIX hosts."""
|
|
13
|
+
import fcntl
|
|
14
|
+
|
|
15
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
16
|
+
with path.open("a", encoding="utf-8") as handle:
|
|
17
|
+
os.chmod(path, 0o600)
|
|
18
|
+
fcntl.flock(handle, fcntl.LOCK_EX)
|
|
19
|
+
try:
|
|
20
|
+
yield
|
|
21
|
+
finally:
|
|
22
|
+
fcntl.flock(handle, fcntl.LOCK_UN)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def atomic_json(path: Path, value) -> None:
|
|
26
|
+
atomic_bytes(path, (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def atomic_bytes(path: Path, data: bytes) -> None:
|
|
30
|
+
from benchside.domain.shared.error import ValidationError
|
|
31
|
+
|
|
32
|
+
if path.is_symlink():
|
|
33
|
+
raise ValidationError("Atomic file destination must not be a symlink")
|
|
34
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
35
|
+
fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".benchside-")
|
|
36
|
+
try:
|
|
37
|
+
with os.fdopen(fd, "wb") as handle:
|
|
38
|
+
handle.write(data)
|
|
39
|
+
handle.flush()
|
|
40
|
+
os.fsync(handle.fileno())
|
|
41
|
+
os.replace(temporary, path)
|
|
42
|
+
finally:
|
|
43
|
+
Path(temporary).unlink(missing_ok=True)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Write-only collector client: exact UTF-8 bytes, verified receipts, no redirects."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from urllib.error import HTTPError, URLError
|
|
7
|
+
from urllib.parse import urlsplit
|
|
8
|
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
9
|
+
|
|
10
|
+
from benchside import __version__
|
|
11
|
+
from benchside.domain.export.model.value import DeliveryReceipt
|
|
12
|
+
from benchside.domain.export.model.wire import MAX_BYTES
|
|
13
|
+
from benchside.domain.shared.error import ConfigurationError, InfrastructureError
|
|
14
|
+
|
|
15
|
+
COLLECTOR = "https://ingest.benchside.science.works"
|
|
16
|
+
USER_AGENT = f"Benchside/{__version__}"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _NoRedirect(HTTPRedirectHandler):
|
|
20
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
21
|
+
return None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class HttpExportSink:
|
|
25
|
+
def __init__(self, destination: str, *, allow_local: bool = False, opener=None):
|
|
26
|
+
url = urlsplit(destination)
|
|
27
|
+
local = (
|
|
28
|
+
allow_local
|
|
29
|
+
and url.scheme == "http"
|
|
30
|
+
and url.hostname in {"localhost", "127.0.0.1", "::1"}
|
|
31
|
+
)
|
|
32
|
+
if (
|
|
33
|
+
(url.scheme != "https" and not local)
|
|
34
|
+
or not url.hostname
|
|
35
|
+
or url.username
|
|
36
|
+
or url.password
|
|
37
|
+
or url.query
|
|
38
|
+
or url.fragment
|
|
39
|
+
):
|
|
40
|
+
raise ConfigurationError("The collector requires an HTTPS endpoint without credentials")
|
|
41
|
+
self.destination = destination
|
|
42
|
+
self._opener = opener or build_opener(_NoRedirect())
|
|
43
|
+
|
|
44
|
+
def _network_denied(self, outcome: str, what: str) -> str:
|
|
45
|
+
# Host-neutral: an app sandbox with network access off, or an institutional
|
|
46
|
+
# proxy. Host-specific steps belong in that host's instructions.
|
|
47
|
+
host = urlsplit(self.destination).hostname
|
|
48
|
+
return (
|
|
49
|
+
f"{outcome}: a network proxy {what} {host} before it reached Science Works. "
|
|
50
|
+
"The reviewed submission is still pending. Once network access to "
|
|
51
|
+
f"{host} is allowed in the app or network settings, retry the same reviewed "
|
|
52
|
+
"submission. Do not change settings for the researcher."
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def send(self, payload: str) -> DeliveryReceipt:
|
|
56
|
+
body = payload.encode("utf-8")
|
|
57
|
+
if len(body) > MAX_BYTES:
|
|
58
|
+
raise InfrastructureError(
|
|
59
|
+
"Submission exceeds the collector limit", code="submission_invalid"
|
|
60
|
+
)
|
|
61
|
+
request = Request(
|
|
62
|
+
self.destination,
|
|
63
|
+
data=body,
|
|
64
|
+
method="POST",
|
|
65
|
+
headers={
|
|
66
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
67
|
+
"Accept": "application/json",
|
|
68
|
+
"User-Agent": USER_AGENT,
|
|
69
|
+
},
|
|
70
|
+
)
|
|
71
|
+
try:
|
|
72
|
+
with self._opener.open(request, timeout=10) as response:
|
|
73
|
+
status = response.status
|
|
74
|
+
raw = response.read(8193)
|
|
75
|
+
if status not in {200, 201} or len(raw) > 8192:
|
|
76
|
+
raise ValueError("Unexpected response")
|
|
77
|
+
data = json.loads(raw)
|
|
78
|
+
if set(data) != {"status", "sha256", "received_at", "observations"}:
|
|
79
|
+
raise ValueError("Unexpected receipt fields")
|
|
80
|
+
parsed = json.loads(payload)
|
|
81
|
+
count = len(parsed["observations"]) if "observations" in parsed else 1
|
|
82
|
+
expected_status = "stored" if status == 201 else "duplicate"
|
|
83
|
+
if (
|
|
84
|
+
data["status"] != expected_status
|
|
85
|
+
or data["sha256"] != hashlib.sha256(body).hexdigest()
|
|
86
|
+
or type(data["observations"]) is not int
|
|
87
|
+
or data["observations"] != count
|
|
88
|
+
or not isinstance(data["received_at"], str)
|
|
89
|
+
or datetime.fromisoformat(data["received_at"]).tzinfo is None
|
|
90
|
+
):
|
|
91
|
+
raise ValueError("Receipt does not match submission")
|
|
92
|
+
return DeliveryReceipt.model_validate(data)
|
|
93
|
+
except HTTPError as err:
|
|
94
|
+
err.close()
|
|
95
|
+
code = (
|
|
96
|
+
"submission_rate_limited"
|
|
97
|
+
if err.code == 429
|
|
98
|
+
else ("submission_unavailable" if err.code >= 500 else "submission_rejected")
|
|
99
|
+
)
|
|
100
|
+
# An HTTP response can arrive after the destination received the POST.
|
|
101
|
+
# Only a refused CONNECT tunnel below proves the payload was not sent.
|
|
102
|
+
message = f"Collector returned HTTP {err.code}; nothing was marked as shared. Retry the same reviewed submission."
|
|
103
|
+
if err.code == 403:
|
|
104
|
+
host = urlsplit(self.destination).hostname
|
|
105
|
+
message = (
|
|
106
|
+
"HTTP 403: no valid collector receipt was received; nothing was marked "
|
|
107
|
+
"as shared. The reviewed submission is still pending. A proxy or server "
|
|
108
|
+
f"policy may be refusing access to {host}. Check the app or network "
|
|
109
|
+
"settings before retrying the same reviewed submission. Do not change "
|
|
110
|
+
"settings for the researcher."
|
|
111
|
+
)
|
|
112
|
+
raise InfrastructureError(message, code=code) from err
|
|
113
|
+
except (URLError, TimeoutError, OSError) as err:
|
|
114
|
+
# Host egress proxies refuse the HTTPS tunnel before any payload is sent.
|
|
115
|
+
if str(getattr(err, "reason", err)).startswith("Tunnel connection failed: 403"):
|
|
116
|
+
raise InfrastructureError(
|
|
117
|
+
self._network_denied("Nothing was sent", "blocked the connection to"),
|
|
118
|
+
code="submission_unavailable",
|
|
119
|
+
) from err
|
|
120
|
+
raise InfrastructureError(
|
|
121
|
+
"Collector could not be reached; retry the same reviewed submission.",
|
|
122
|
+
code="submission_unavailable",
|
|
123
|
+
) from err
|
|
124
|
+
except (ValueError, TypeError, KeyError) as err:
|
|
125
|
+
raise InfrastructureError(
|
|
126
|
+
"Collector receipt could not be verified; retry the same reviewed submission.",
|
|
127
|
+
code="submission_receipt_invalid",
|
|
128
|
+
) from err
|
|
File without changes
|