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,245 @@
1
+ """CLI runtime context: project resolution, sitting pointers, container access.
2
+
3
+ The CLI is the only writer to on-disk state and the layer where the model's
4
+ prose becomes typed records — or gets refused. Ids and timestamps are
5
+ generated here, never supplied by the model.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ import subprocess
12
+ import uuid
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+
16
+ import yaml
17
+ from pydantic import ValidationError as SchemaError
18
+
19
+ from benchside.config import Paths, resolve_paths
20
+ from benchside.domain.shared.error import DomainError
21
+ from benchside.domain.shared.model.ids import ProjectId, user_project_id
22
+ from benchside.domain.shared.model.provenance import AppProvenance
23
+
24
+ _NON_SLUG = re.compile(r"[^a-z0-9]+")
25
+
26
+
27
+ class NoOpenSittingError(DomainError):
28
+ """Raised when a capture command runs with no resolvable open sitting."""
29
+
30
+
31
+ class NotInitializedError(DomainError):
32
+ """Raised when a project-bound command runs outside an inited project."""
33
+
34
+
35
+ def require_initialized(cwd: Path | None = None) -> Path:
36
+ """Project-bound commands refuse to run outside a `bench init`-ed project.
37
+
38
+ Prevents accidental projects: /pi can load from a parent directory and
39
+ bench runs anywhere, so without this guard a sitting could be opened in a
40
+ directory that was never set up (and whose hooks therefore never fire).
41
+ Explicit BENCH_SITTING cleanup paths bypass this at the call site.
42
+ """
43
+ cwd = cwd or Path.cwd()
44
+ config = find_bench_config(cwd)
45
+ if config is None:
46
+ raise NotInitializedError(
47
+ f"'{cwd}' is not part of a benchside project",
48
+ hint="Run `bench init` here first — it sets up the project id, "
49
+ "session hooks, and the /pi skill.",
50
+ )
51
+ return config.parent.parent
52
+
53
+
54
+ def slugify(raw: str) -> str:
55
+ slug = _NON_SLUG.sub("-", raw.strip().lower()).strip("-")
56
+ return slug or "unnamed"
57
+
58
+
59
+ def short_id(prefix: str) -> str:
60
+ """Human-quotable unique id, generated CLI-side (never by the model)."""
61
+ return f"{prefix}-{uuid.uuid4().hex}"
62
+
63
+
64
+ # --- Project resolution (issue #2: config file > git remote > dirname) ---
65
+
66
+
67
+ def find_bench_config(start: Path) -> Path | None:
68
+ for directory in (start, *start.parents):
69
+ candidate = directory / ".bench" / "config.yaml"
70
+ if candidate.is_file():
71
+ return candidate
72
+ return None
73
+
74
+
75
+ def resolve_project(explicit: str | None = None, cwd: Path | None = None) -> ProjectId:
76
+ if explicit:
77
+ return user_project_id(slugify(explicit))
78
+ cwd = cwd or Path.cwd()
79
+
80
+ config = find_bench_config(cwd)
81
+ if config is not None:
82
+ raw = (yaml.safe_load(config.read_text(encoding="utf-8")) or {}).get("project")
83
+ if raw:
84
+ return user_project_id(slugify(str(raw)))
85
+
86
+ remote = _git_remote_slug(cwd)
87
+ if remote is not None:
88
+ return user_project_id(remote)
89
+
90
+ return user_project_id(slugify(cwd.name))
91
+
92
+
93
+ def _git_remote_slug(cwd: Path) -> str | None:
94
+ try:
95
+ result = subprocess.run(
96
+ ["git", "remote", "get-url", "origin"],
97
+ cwd=cwd,
98
+ capture_output=True,
99
+ text=True,
100
+ timeout=5,
101
+ check=False, # non-repo dirs are an expected, handled case
102
+ )
103
+ except (OSError, subprocess.TimeoutExpired):
104
+ return None
105
+ if result.returncode != 0:
106
+ return None
107
+ url = result.stdout.strip()
108
+ # git@host:owner/repo.git or https://host/owner/repo(.git)
109
+ match = re.search(r"[:/]([^/:]+)/([^/]+?)(?:\.git)?/?$", url)
110
+ if not match:
111
+ return None
112
+ return slugify(f"{match.group(1)}-{match.group(2)}")
113
+
114
+
115
+ # --- Sitting pointers (per session; parallel sessions never fight) ---
116
+
117
+
118
+ def session_name(paths: Paths | None = None, project_id: ProjectId | None = None) -> str:
119
+ """The session this bench invocation belongs to. Env wins; else the id
120
+ the SessionStart hook registered for this project; else 'local'."""
121
+ if paths is not None and project_id is not None:
122
+ from benchside.infrastructure.session_context import current_session
123
+
124
+ registered = current_session(paths, project_id)
125
+ return registered or "local"
126
+ env = os.environ.get("BENCHSIDE_SESSION_ID") or os.environ.get("CLAUDE_SESSION_ID")
127
+ if env:
128
+ from benchside.infrastructure.session_context import validate_session_id
129
+
130
+ return validate_session_id(env)
131
+ return "local"
132
+
133
+
134
+ def pointer_dir(paths: Paths) -> Path:
135
+ return paths.home / "sessions"
136
+
137
+
138
+ def write_pointer(paths: Paths, *, sitting_id: str, project_id: ProjectId, persona_id: str) -> None:
139
+ directory = pointer_dir(paths)
140
+ directory.mkdir(parents=True, exist_ok=True)
141
+ session = session_name(paths, project_id)
142
+ from benchside.infrastructure.files import atomic_json, file_lock
143
+
144
+ with file_lock(directory / f"{session}.lock"):
145
+ atomic_json(
146
+ directory / f"{session}.json",
147
+ {
148
+ "sitting_id": sitting_id,
149
+ "project_id": project_id.root,
150
+ "persona_id": persona_id,
151
+ "session": session,
152
+ "opened_at": datetime.now(UTC).isoformat(),
153
+ },
154
+ )
155
+
156
+
157
+ def clear_pointer(paths: Paths, sitting_id: str) -> None:
158
+ """Remove whichever live pointer references the sitting — not blindly this
159
+ session's, so cross-project cleanup via BENCH_SITTING clears the right one."""
160
+ from benchside.infrastructure.files import file_lock
161
+
162
+ directory = pointer_dir(paths)
163
+ for path in sorted(directory.iterdir()) if directory.is_dir() else []:
164
+ if path.suffix not in {".json", ".ended"}:
165
+ continue
166
+ try:
167
+ with file_lock(path.with_suffix(".lock")):
168
+ if json.loads(path.read_text(encoding="utf-8")).get("sitting_id") == sitting_id:
169
+ path.unlink(missing_ok=True)
170
+ except (OSError, json.JSONDecodeError):
171
+ continue
172
+
173
+
174
+ def live_pointers(paths: Paths) -> list[dict]:
175
+ directory = pointer_dir(paths)
176
+ records = []
177
+ for path in sorted(directory.glob("*.json")) if directory.is_dir() else []:
178
+ try:
179
+ records.append(json.loads(path.read_text(encoding="utf-8")))
180
+ except (OSError, json.JSONDecodeError):
181
+ continue
182
+ return records
183
+
184
+
185
+ def read_pointer(paths: Paths, project_id: ProjectId | None = None) -> dict | None:
186
+ """Resolve the active sitting FOR THIS PROJECT.
187
+
188
+ Sittings belong to projects; a pointer left behind by another project must
189
+ never be adopted (regression: /pi opened in the wrong directory bled into
190
+ the next project's session). Order: BENCH_SITTING env override (explicit,
191
+ allowed cross-project so stranded sittings can be cleaned up), then this
192
+ session's pointer (including the local terminal pointer), only when it
193
+ matches the current project. A missing ID never adopts another conversation.
194
+ """
195
+ override = os.environ.get("BENCH_SITTING")
196
+ if override:
197
+ for record in live_pointers(paths):
198
+ if record.get("sitting_id") == override:
199
+ return record
200
+ return {"sitting_id": override, "project_id": None}
201
+ # Expired fallback registrations do not retire explicit conversation pointers.
202
+ # Those pointers must not be adopted merely because only one remains.
203
+ mine = session_name(paths, project_id)
204
+ records = live_pointers(paths)
205
+ if project_id is not None:
206
+ records = [r for r in records if r.get("project_id") == project_id.root]
207
+ for record in records:
208
+ if record.get("session") == mine:
209
+ return record
210
+ return None
211
+
212
+
213
+ def require_pointer(paths: Paths, project_id: ProjectId | None = None) -> dict:
214
+ record = read_pointer(paths, project_id)
215
+ if record is None:
216
+ where = f" for project '{project_id.root}'" if project_id is not None else ""
217
+ raise NoOpenSittingError(
218
+ f"No open sitting{where}",
219
+ hint="Start one with `bench sitting open --persona <id>` "
220
+ "(or set BENCH_SITTING to an existing sitting id).",
221
+ )
222
+ return record
223
+
224
+
225
+ def current_paths() -> Paths:
226
+ return resolve_paths()
227
+
228
+
229
+ def recording_provenance() -> AppProvenance:
230
+ """Use only reported CLI metadata; never infer a release version."""
231
+ values = {
232
+ "host": os.environ.get(
233
+ "BENCHSIDE_HOST", "claude" if os.environ.get("CLAUDE_SESSION_ID") else "unknown"
234
+ ),
235
+ "app_version": os.environ.get("BENCHSIDE_APP_VERSION", "unknown"),
236
+ "surface": os.environ.get("BENCHSIDE_SURFACE", "cli"),
237
+ }
238
+ try:
239
+ return AppProvenance.model_validate(values)
240
+ except SchemaError as error:
241
+ # Optional host metadata cannot prevent a valid scientific record.
242
+ # Keep valid fields and replace unsupported labels with the wire sentinel.
243
+ for field in {issue["loc"][0] for issue in error.errors()}:
244
+ values[field] = "unknown"
245
+ return AppProvenance.model_validate(values)
@@ -0,0 +1,66 @@
1
+ """Human and agent surfaces for the same three-channel sharing flow."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from benchside.application.sharing import SharingFlow
7
+ from benchside.cli.runtime import current_paths
8
+ from benchside.domain.shared.error import ConsentRequiredError
9
+
10
+
11
+ def cmd_sharing(args):
12
+ flow = SharingFlow(current_paths())
13
+ channel = getattr(args, "channel", "gaps")
14
+ if args.action == "status":
15
+ print(json.dumps(flow.status(), indent=2))
16
+ elif args.action == "grant":
17
+ kinds = [k.strip() for k in (args.kinds or "").split(",") if k.strip()]
18
+ flow.set_consent(channel, True, kinds=kinds)
19
+ args.ui.success(f"{channel} consent enabled; review a submission before sending")
20
+ elif args.action == "revoke":
21
+ channels = ("gaps", "feedback", "usage") if channel == "all" else (channel,)
22
+ for name in channels:
23
+ flow.set_consent(name, False)
24
+ args.ui.success(
25
+ f"{channel} reporting stopped; previous submissions are listed in share history"
26
+ )
27
+ elif args.action == "feedback":
28
+ feedback = flow.feedback(
29
+ role=args.role,
30
+ host=args.host,
31
+ surface=args.surface,
32
+ ease=args.ease,
33
+ would_use_again=args.again,
34
+ comment=args.comment,
35
+ )
36
+ print(feedback.model_dump_json())
37
+ args.ui.info("Feedback saved locally; preview and approve it to share")
38
+ elif args.action == "preview":
39
+ edits = json.loads(Path(args.edits).read_text()) if args.edits else None
40
+ drafts = flow.prepare(
41
+ channel,
42
+ only=args.only,
43
+ edits=edits,
44
+ feedback_id=args.feedback_id,
45
+ comment=args.comment,
46
+ week=args.week,
47
+ )
48
+ for draft in drafts:
49
+ print(draft.preview.payload)
50
+ args.ui.info(f"Review {draft.channel} draft {draft.id}")
51
+ args.ui.detail(f"Destination: {draft.preview.destination}")
52
+ args.ui.detail(f"Approval digest: {draft.preview.payload_sha256}")
53
+ for finding in draft.preview.redaction_findings:
54
+ args.ui.warn(finding)
55
+ args.ui.warn("Redaction cannot detect all private research details. Review the full text.")
56
+ elif args.action == "send":
57
+ if not args.draft or not args.approve_sha256:
58
+ raise ConsentRequiredError(
59
+ "Consent, a reviewed draft and its approval digest are required; nothing was shared"
60
+ )
61
+ receipt = flow.send(args.draft, args.approve_sha256)
62
+ print(receipt.model_dump_json())
63
+ args.ui.success("Submission receipt verified")
64
+ elif args.action == "history":
65
+ print(json.dumps(flow.history(), indent=2))
66
+ return 0
@@ -0,0 +1,5 @@
1
+ from benchside.cli.ui._glyphs import GlyphSet, default_glyphs
2
+ from benchside.cli.ui._model import UI
3
+ from benchside.cli.ui._renderer import PlainRenderer, RecordingRenderer, Renderer
4
+
5
+ __all__ = ["UI", "GlyphSet", "PlainRenderer", "RecordingRenderer", "Renderer", "default_glyphs"]
@@ -0,0 +1,21 @@
1
+ """Glyph vocabulary. One place; two palettes."""
2
+
3
+ import os
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class GlyphSet:
9
+ check: str
10
+ cross: str
11
+ warn: str
12
+ arrow: str
13
+ dot: str
14
+
15
+
16
+ UNICODE = GlyphSet(check="✓", cross="✗", warn="⚠", arrow="→", dot="•")
17
+ ASCII = GlyphSet(check="+", cross="x", warn="!", arrow="->", dot="*")
18
+
19
+
20
+ def default_glyphs() -> GlyphSet:
21
+ return ASCII if os.name == "nt" else UNICODE
@@ -0,0 +1,66 @@
1
+ """The UI facade. Renderer-agnostic; owns the TTY gate.
2
+
3
+ Chrome goes through this class to stderr. Data (JSON, markers, hook context
4
+ injection) never comes through here — it stays on stdout via bare print.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ from typing import IO
10
+
11
+ from benchside.cli.ui._renderer import PlainRenderer, Renderer
12
+
13
+
14
+ def _should_use_rich(file: IO[str]) -> bool:
15
+ try:
16
+ is_tty = file.isatty()
17
+ except (AttributeError, ValueError):
18
+ is_tty = False
19
+ return (
20
+ is_tty
21
+ and not os.environ.get("NO_COLOR")
22
+ and not os.environ.get("CI")
23
+ and os.environ.get("TERM") != "dumb"
24
+ )
25
+
26
+
27
+ class UI:
28
+ def __init__(self, *, renderer: Renderer) -> None:
29
+ self._renderer = renderer
30
+
31
+ @classmethod
32
+ def create(cls, *, file: IO[str] | None = None, force_plain: bool | None = None) -> "UI":
33
+ file = file if file is not None else sys.stderr
34
+ use_rich = not force_plain if force_plain is not None else _should_use_rich(file)
35
+ if use_rich:
36
+ from benchside.cli.ui._rich import RichRenderer # lazy: only path importing rich
37
+
38
+ return cls(renderer=RichRenderer(file))
39
+ return cls(renderer=PlainRenderer(file))
40
+
41
+ def header(self, text: str) -> None:
42
+ self._renderer.header(text)
43
+
44
+ def section(self, title: str, *, meta: str | None = None) -> None:
45
+ self._renderer.section(title, meta=meta)
46
+
47
+ def block(self, text: str, *, dim: bool = False) -> None:
48
+ self._renderer.block(text, dim=dim)
49
+
50
+ def info(self, text: str) -> None:
51
+ self._renderer.info(text)
52
+
53
+ def detail(self, text: str) -> None:
54
+ self._renderer.detail(text)
55
+
56
+ def success(self, text: str) -> None:
57
+ self._renderer.success(text)
58
+
59
+ def warn(self, text: str) -> None:
60
+ self._renderer.warn(text)
61
+
62
+ def error(self, headline: str, *, cause: str | None = None, hint: str | None = None) -> None:
63
+ self._renderer.error(headline, cause=cause, hint=hint)
64
+
65
+ def table(self, columns: list[str], rows: list[list[str]]) -> None:
66
+ self._renderer.table(columns, rows)
@@ -0,0 +1,110 @@
1
+ """Renderer protocol, the plain implementation, and the test recorder.
2
+
3
+ The contract: plain and rich renderers produce identical wording; they differ
4
+ only in ANSI and styling. Plain output is exact-string testable.
5
+ """
6
+
7
+ import textwrap
8
+ from typing import IO, Protocol
9
+
10
+ from benchside.cli.ui._glyphs import default_glyphs
11
+
12
+
13
+ class Renderer(Protocol):
14
+ def header(self, text: str) -> None: ...
15
+ def section(self, title: str, *, meta: str | None = None) -> None: ...
16
+ def block(self, text: str, *, dim: bool = False) -> None: ...
17
+ def info(self, text: str) -> None: ...
18
+ def detail(self, text: str) -> None: ...
19
+ def success(self, text: str) -> None: ...
20
+ def warn(self, text: str) -> None: ...
21
+ def error(self, headline: str, *, cause: str | None, hint: str | None) -> None: ...
22
+ def table(self, columns: list[str], rows: list[list[str]]) -> None: ...
23
+
24
+
25
+ class PlainRenderer:
26
+ """Sequential lines, no ANSI. Same wording as the rich renderer."""
27
+
28
+ def __init__(self, file: IO[str]) -> None:
29
+ self._file = file
30
+ self._glyphs = default_glyphs()
31
+
32
+ def _line(self, text: str) -> None:
33
+ self._file.write(text + "\n")
34
+
35
+ def header(self, text: str) -> None:
36
+ self._line(f"── {text}")
37
+
38
+ def section(self, title: str, *, meta: str | None = None) -> None:
39
+ suffix = f" {meta}" if meta else ""
40
+ self._line("")
41
+ self._line(f"{title.upper()}{suffix}")
42
+
43
+ def block(self, text: str, *, dim: bool = False) -> None:
44
+ lines = textwrap.wrap(text, width=76, break_long_words=False, break_on_hyphens=False) or [
45
+ ""
46
+ ]
47
+ for line in lines:
48
+ self._line(f"│ {line}")
49
+
50
+ def info(self, text: str) -> None:
51
+ self._line(text)
52
+
53
+ def detail(self, text: str) -> None:
54
+ self._line(f" {text}")
55
+
56
+ def success(self, text: str) -> None:
57
+ self._line(f"{self._glyphs.check} {text}")
58
+
59
+ def warn(self, text: str) -> None:
60
+ self._line(f"{self._glyphs.warn} {text}")
61
+
62
+ def error(self, headline: str, *, cause: str | None, hint: str | None) -> None:
63
+ self._line(f"{self._glyphs.cross} {headline}")
64
+ if cause:
65
+ self._line(f" {cause}")
66
+ if hint:
67
+ self._line(f"{self._glyphs.arrow} {hint}")
68
+
69
+ def table(self, columns: list[str], rows: list[list[str]]) -> None:
70
+ widths = [
71
+ max(len(str(columns[i])), *(len(str(r[i])) for r in rows)) if rows else len(columns[i])
72
+ for i in range(len(columns))
73
+ ]
74
+ self._line(" ".join(c.ljust(widths[i]) for i, c in enumerate(columns)).rstrip())
75
+ for row in rows:
76
+ self._line(" ".join(str(cell).ljust(widths[i]) for i, cell in enumerate(row)).rstrip())
77
+
78
+
79
+ class RecordingRenderer:
80
+ """Appends (event, payload) tuples; asserts sequence independent of format."""
81
+
82
+ def __init__(self) -> None:
83
+ self.events: list[tuple[str, dict]] = []
84
+
85
+ def header(self, text: str) -> None:
86
+ self.events.append(("header", {"text": text}))
87
+
88
+ def section(self, title: str, *, meta: str | None = None) -> None:
89
+ self.events.append(("section", {"title": title, "meta": meta}))
90
+
91
+ def block(self, text: str, *, dim: bool = False) -> None:
92
+ self.events.append(("block", {"text": text, "dim": dim}))
93
+
94
+ def info(self, text: str) -> None:
95
+ self.events.append(("info", {"text": text}))
96
+
97
+ def detail(self, text: str) -> None:
98
+ self.events.append(("detail", {"text": text}))
99
+
100
+ def success(self, text: str) -> None:
101
+ self.events.append(("success", {"text": text}))
102
+
103
+ def warn(self, text: str) -> None:
104
+ self.events.append(("warn", {"text": text}))
105
+
106
+ def error(self, headline: str, *, cause: str | None, hint: str | None) -> None:
107
+ self.events.append(("error", {"headline": headline, "cause": cause, "hint": hint}))
108
+
109
+ def table(self, columns: list[str], rows: list[list[str]]) -> None:
110
+ self.events.append(("table", {"columns": columns, "rows": rows}))
@@ -0,0 +1,75 @@
1
+ """The rich renderer — the ONLY module in benchside allowed to import rich.
2
+
3
+ Same wording as PlainRenderer; adds color. No markup parsing (highlight off),
4
+ no live regions yet: every bench command is sub-second.
5
+ """
6
+
7
+ import textwrap
8
+ from typing import IO
9
+
10
+ from rich.console import Console
11
+ from rich.rule import Rule
12
+ from rich.table import Table
13
+ from rich.text import Text
14
+
15
+ from benchside.cli.ui._glyphs import default_glyphs
16
+
17
+
18
+ class RichRenderer:
19
+ def __init__(self, file: IO[str]) -> None:
20
+ self._console = Console(file=file, highlight=False)
21
+ self._glyphs = default_glyphs()
22
+
23
+ def header(self, text: str) -> None:
24
+ self._console.print(Rule(Text(text, style="bold"), align="left", style="dim"))
25
+
26
+ def section(self, title: str, *, meta: str | None = None) -> None:
27
+ grid = Table.grid(expand=True)
28
+ grid.add_column()
29
+ grid.add_column(justify="right")
30
+ grid.add_row(
31
+ Text(title.upper(), style="bold cyan"),
32
+ Text(meta or "", style="dim cyan"),
33
+ )
34
+ self._console.print()
35
+ self._console.print(grid)
36
+
37
+ def block(self, text: str, *, dim: bool = False) -> None:
38
+ width = max(24, min(self._console.width, 100) - 4)
39
+ lines = textwrap.wrap(
40
+ text, width=width, break_long_words=False, break_on_hyphens=False
41
+ ) or [""]
42
+ for line in lines:
43
+ self._console.print(
44
+ Text.assemble(("│ ", "dim cyan"), (line, "dim" if dim else "")),
45
+ soft_wrap=True,
46
+ )
47
+
48
+ def info(self, text: str) -> None:
49
+ self._console.print(text)
50
+
51
+ def detail(self, text: str) -> None:
52
+ self._console.print(Text(f" {text}", style="dim"))
53
+
54
+ def success(self, text: str) -> None:
55
+ self._console.print(Text.assemble((f"{self._glyphs.check} ", "green"), (text, "")))
56
+
57
+ def warn(self, text: str) -> None:
58
+ self._console.print(Text(f"{self._glyphs.warn} {text}", style="yellow"))
59
+
60
+ def error(self, headline: str, *, cause: str | None, hint: str | None) -> None:
61
+ self._console.print(Text.assemble((f"{self._glyphs.cross} ", "red"), (headline, "bold")))
62
+ if cause:
63
+ self._console.print(Text(f" {cause}", style="dim"))
64
+ if hint:
65
+ self._console.print(Text(f"{self._glyphs.arrow} {hint}", style="cyan"))
66
+
67
+ def table(self, columns: list[str], rows: list[list[str]]) -> None:
68
+ table = Table(
69
+ box=None, show_header=True, header_style="dim", pad_edge=False, padding=(0, 2, 0, 0)
70
+ )
71
+ for column in columns:
72
+ table.add_column(column)
73
+ for row in rows:
74
+ table.add_row(*[str(cell) for cell in row])
75
+ self._console.print(table)