benchbook 0.1.0__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 (152) hide show
  1. benchbook/__init__.py +27 -0
  2. benchbook/__main__.py +4 -0
  3. benchbook/_version.py +24 -0
  4. benchbook/checks/__init__.py +2 -0
  5. benchbook/checks/attempts.py +214 -0
  6. benchbook/checks/baseline.py +300 -0
  7. benchbook/checks/declarations.py +349 -0
  8. benchbook/checks/failures.py +226 -0
  9. benchbook/checks/gitrepo.py +167 -0
  10. benchbook/checks/guard.py +652 -0
  11. benchbook/checks/proposals.py +296 -0
  12. benchbook/checks/rerun.py +209 -0
  13. benchbook/checks/run.py +377 -0
  14. benchbook/checks/signature.py +340 -0
  15. benchbook/checks/verify.py +821 -0
  16. benchbook/checks/verify_requests.py +250 -0
  17. benchbook/cli/__init__.py +2 -0
  18. benchbook/cli/__main__.py +5 -0
  19. benchbook/cli/agent.py +65 -0
  20. benchbook/cli/check.py +211 -0
  21. benchbook/cli/check_run.py +54 -0
  22. benchbook/cli/doctor.py +782 -0
  23. benchbook/cli/exp_run.py +304 -0
  24. benchbook/cli/finding.py +93 -0
  25. benchbook/cli/install.py +353 -0
  26. benchbook/cli/main.py +905 -0
  27. benchbook/cli/piece.py +174 -0
  28. benchbook/cli/plugins.py +110 -0
  29. benchbook/cli/pr.py +105 -0
  30. benchbook/code/__init__.py +1 -0
  31. benchbook/code/findings.py +336 -0
  32. benchbook/code/pieces.py +203 -0
  33. benchbook/code/pr.py +368 -0
  34. benchbook/code/status.py +141 -0
  35. benchbook/config.py +425 -0
  36. benchbook/core/__init__.py +1 -0
  37. benchbook/core/blobs.py +37 -0
  38. benchbook/core/brief.py +334 -0
  39. benchbook/core/dedup.py +66 -0
  40. benchbook/core/globs.py +390 -0
  41. benchbook/core/identity.py +132 -0
  42. benchbook/core/ids.py +15 -0
  43. benchbook/core/ledger.py +1757 -0
  44. benchbook/core/lookup.py +135 -0
  45. benchbook/core/models.py +112 -0
  46. benchbook/core/runner.py +319 -0
  47. benchbook/core/tokens.py +9 -0
  48. benchbook/db/__init__.py +0 -0
  49. benchbook/db/alembic/env.py +38 -0
  50. benchbook/db/alembic/script.py.mako +20 -0
  51. benchbook/db/alembic/sql/0001_core.sql +221 -0
  52. benchbook/db/alembic/sql/0002_views.sql +152 -0
  53. benchbook/db/alembic/sql/0003_roles.sql +33 -0
  54. benchbook/db/alembic/sql/0004_evidence_and_notices.sql +92 -0
  55. benchbook/db/alembic/sql/0005_partitions_blobs_views.sql +221 -0
  56. benchbook/db/alembic/sql/0006_review_fixes.sql +134 -0
  57. benchbook/db/alembic/sql/0007_verified_evidence.sql +143 -0
  58. benchbook/db/alembic/sql/0008_agent_tokens.sql +313 -0
  59. benchbook/db/alembic/sql/0009_dedup_notify.sql +37 -0
  60. benchbook/db/alembic/sql/0010_environment_oracle.sql +11 -0
  61. benchbook/db/alembic/versions/0001_core.py +19 -0
  62. benchbook/db/alembic/versions/0002_views.py +19 -0
  63. benchbook/db/alembic/versions/0003_roles.py +19 -0
  64. benchbook/db/alembic/versions/0004_evidence_and_notices.py +19 -0
  65. benchbook/db/alembic/versions/0005_partitions_blobs_views.py +19 -0
  66. benchbook/db/alembic/versions/0006_review_fixes.py +19 -0
  67. benchbook/db/alembic/versions/0007_verified_evidence.py +19 -0
  68. benchbook/db/alembic/versions/0008_agent_tokens.py +19 -0
  69. benchbook/db/alembic/versions/0009_dedup_notify.py +19 -0
  70. benchbook/db/alembic/versions/0010_environment_oracle.py +19 -0
  71. benchbook/db/conn.py +190 -0
  72. benchbook/db/migrate.py +471 -0
  73. benchbook/entry.py +76 -0
  74. benchbook/errors.py +51 -0
  75. benchbook/hooks/__init__.py +2 -0
  76. benchbook/hooks/__main__.py +14 -0
  77. benchbook/hooks/boundary.py +440 -0
  78. benchbook/hooks/checks.py +500 -0
  79. benchbook/hooks/citations.py +245 -0
  80. benchbook/hooks/harnesses.py +355 -0
  81. benchbook/hooks/merge_gate.py +311 -0
  82. benchbook/hooks/session_notes.py +76 -0
  83. benchbook/hooks/spooler.py +614 -0
  84. benchbook/hooks/subagent.py +356 -0
  85. benchbook/integrations/__init__.py +1 -0
  86. benchbook/integrations/autoresearch/__init__.py +5 -0
  87. benchbook/integrations/autoresearch/brief.py +180 -0
  88. benchbook/integrations/autoresearch/checkout.py +127 -0
  89. benchbook/integrations/autoresearch/cli.py +283 -0
  90. benchbook/integrations/autoresearch/code.py +258 -0
  91. benchbook/integrations/autoresearch/gate.py +137 -0
  92. benchbook/integrations/autoresearch/hw.py +101 -0
  93. benchbook/integrations/autoresearch/ops.py +1055 -0
  94. benchbook/integrations/autoresearch/referee.py +422 -0
  95. benchbook/integrations/autoresearch/runner.py +87 -0
  96. benchbook/integrations/autoresearch/skills.py +323 -0
  97. benchbook/integrations/autoresearch/templates/program.benchbook.md +120 -0
  98. benchbook/integrations/autoresearch/templates/program.codex-autoresearch.md +33 -0
  99. benchbook/integrations/autoresearch/templates/program.pi-autoresearch.md +35 -0
  100. benchbook/integrations/autoresearch/templates/program.uditgoenka.md +36 -0
  101. benchbook/manifests/codex/hooks.json +48 -0
  102. benchbook/manifests/cursor/hooks.json +39 -0
  103. benchbook/manifests/gemini/hooks.json +39 -0
  104. benchbook/mcp_server.py +278 -0
  105. benchbook/packs/__init__.py +133 -0
  106. benchbook/packs/code/__init__.py +1 -0
  107. benchbook/packs/code/brief.py +557 -0
  108. benchbook/packs/code/pack.toml +51 -0
  109. benchbook/packs/code/schemas/claim.completion.json +59 -0
  110. benchbook/packs/code/schemas/claim.note.json +55 -0
  111. benchbook/packs/code/schemas/claim.observation.json +5 -0
  112. benchbook/packs/code/schemas/experiment.config.json +39 -0
  113. benchbook/packs/code/schemas/experiment.metrics.json +145 -0
  114. benchbook/packs/core/__init__.py +0 -0
  115. benchbook/packs/core/pack.toml +14 -0
  116. benchbook/packs/core/schemas/claim.conclusion.json +5 -0
  117. benchbook/packs/core/schemas/claim.hypothesis.json +5 -0
  118. benchbook/packs/core/schemas/claim.note.json +5 -0
  119. benchbook/packs/core/schemas/claim.observation.json +5 -0
  120. benchbook/packs/core/schemas/experiment.config.json +6 -0
  121. benchbook/packs/core/schemas/experiment.metrics.json +13 -0
  122. benchbook/packs/ml-research/pack.toml +26 -0
  123. benchbook/packs/ml-research/schemas/claim.calibration.json +34 -0
  124. benchbook/packs/ml-research/schemas/claim.conclusion.json +5 -0
  125. benchbook/packs/ml-research/schemas/claim.hypothesis.json +5 -0
  126. benchbook/packs/ml-research/schemas/claim.note.json +5 -0
  127. benchbook/packs/ml-research/schemas/claim.observation.json +5 -0
  128. benchbook/packs/ml-research/schemas/claim.result.json +72 -0
  129. benchbook/packs/ml-research/schemas/experiment.config.json +37 -0
  130. benchbook/packs/ml-research/schemas/experiment.metrics.json +9 -0
  131. benchbook/py.typed +0 -0
  132. benchbook/web/__init__.py +0 -0
  133. benchbook/web/app.py +465 -0
  134. benchbook/web/static/benchbook.css +22 -0
  135. benchbook/web/static/benchbook.js +44 -0
  136. benchbook/web/static/htmx.min.js +1 -0
  137. benchbook/web/static/uPlot.iife.min.js +2 -0
  138. benchbook/web/static/uPlot.min.css +1 -0
  139. benchbook/web/templates/ar_overview.html +36 -0
  140. benchbook/web/templates/base.html +20 -0
  141. benchbook/web/templates/claims.html +9 -0
  142. benchbook/web/templates/experiments.html +14 -0
  143. benchbook/web/templates/knobs.html +7 -0
  144. benchbook/web/templates/lineage.html +12 -0
  145. benchbook/web/templates/overview.html +23 -0
  146. benchbook/web/templates/record.html +14 -0
  147. benchbook/web/templates/tasks.html +8 -0
  148. benchbook-0.1.0.dist-info/METADATA +146 -0
  149. benchbook-0.1.0.dist-info/RECORD +152 -0
  150. benchbook-0.1.0.dist-info/WHEEL +4 -0
  151. benchbook-0.1.0.dist-info/entry_points.txt +2 -0
  152. benchbook-0.1.0.dist-info/licenses/LICENSE +202 -0
benchbook/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """benchbook: a Postgres ledger for agent swarms.
2
+
3
+ Subagents write results to the ledger instead of the lead's context, and the lead reads them back by SQL.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from .errors import BenchbookError, LeaseLost, NotFound, PermissionDenied, ValidationFailed
10
+
11
+ if TYPE_CHECKING:
12
+ from .core.ledger import Ledger
13
+
14
+ try:
15
+ from ._version import __version__ # written from git by the build (hatch-vcs)
16
+ except ImportError: # a source tree that was never built
17
+ __version__ = "0+unknown"
18
+ __all__ = ["__version__", "Ledger", "BenchbookError", "ValidationFailed", "NotFound", "PermissionDenied", "LeaseLost"]
19
+
20
+
21
+ def __getattr__(name: str) -> Any:
22
+ # Lazy: `benchbook hook` must start fast and never needs the SDK's heavier imports.
23
+ if name == "Ledger":
24
+ from .core.ledger import Ledger
25
+
26
+ return Ledger
27
+ raise AttributeError(name)
benchbook/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ """`python -m benchbook` runs the CLI."""
2
+ from benchbook.entry import main
3
+
4
+ main()
benchbook/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,2 @@
1
+ """Declared checks: running one, recording its attempts and failure signatures, and the independent re-run that
2
+ verifies a completion. Kept import-light: the Bash hook loads modules from here."""
@@ -0,0 +1,214 @@
1
+ """Check attempts that reach the ledger through the hook spool: `benchbook check run` (the wrapper) and the
2
+ Bash hook (`benchbook hook bash-result`) queue them, the spool's processor records them here, and the completion gate
3
+ (`benchbook hook task-completed`) reads them back.
4
+
5
+ An attempt has the shape `check verify` writes (checks.Verification: config piece and checks, code_ref the commit, the
6
+ same metrics, recorded through checks._record) plus two metrics that say what it is not:
7
+
8
+ - `via`: "check-run" or "bash-hook". These are the implementer's own runs in its own checkout, never an independent
9
+ re-run, whoever the author turns out to be.
10
+ - `worktree_dirty`: the checkout had uncommitted (or untracked) paths, so the run tested something that is not the
11
+ commit in code_ref. The gate does not count such a run.
12
+
13
+ guard_touched, guard_files and checks_changed are computed here, at replay, against the merge-base of the guard base
14
+ and the commit (as check verify does: declarations.guard_base_ref, the piece's recorded base when the run's agent and
15
+ the piece's other implementers did not record it). When they cannot be (the base ref is missing, no declarations at the
16
+ merge-base, the checkout is gone) they are left out and the notes say why; a missing guard_touched is not "false".
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Collection
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING, Any
24
+ from uuid import UUID
25
+
26
+ from ..errors import BenchbookError
27
+ from . import declarations, gitrepo, guard
28
+ from . import verify as checks
29
+ from .declarations import Base
30
+ from .guard import Integrity
31
+ from .rerun import CheckResult
32
+ from .verify import Verification
33
+
34
+ if TYPE_CHECKING:
35
+ from ..core.ledger import Ledger
36
+
37
+ GUARD_KEYS = ("guard_touched", "guard_files", "checks_changed", "guard_weakened", "guard_weakened_files",
38
+ "guard_added_files", "tests_before", "tests_after", "fewer_tests_checks", "guard_base_source",
39
+ "guard_base_sha")
40
+ STATUSES = {"ok": "ok", "fail": "fail", "timeout": "timeout", "interrupted": "not_run"}
41
+ SOURCES = {"check-run": "check run", "bash-result": "Bash hook"}
42
+ CONNECT_TIMEOUT = 5 # seconds; the gate fails open after that
43
+ STATEMENT_TIMEOUT_MS = 5000
44
+
45
+
46
+ @dataclass
47
+ class LocalRun(Verification):
48
+ """One check run in the implementer's checkout, recorded in check verify's shape."""
49
+ via: str = "check-run"
50
+ dirty: bool = False
51
+ changed: int = 0
52
+ integrity_note: str | None = None # why the guard columns are missing; None when they were computed
53
+ source_note: str = ""
54
+ # What check verify needs to count this run as the implementer's own pass (checks.passed_elsewhere): the hash of
55
+ # the definition that ran (CheckSpec.definition) and, for the Bash hook, the agent type that ran it.
56
+ definition: str | None = None
57
+ run_by: str | None = None
58
+
59
+ def definitions(self) -> dict[str, str]:
60
+ """What ran in the checkout, not what the merge-base declares under the name."""
61
+ return {r.name: self.definition for r in self.results} if self.definition else {}
62
+
63
+ def metrics(self) -> dict[str, Any]:
64
+ m = super().metrics()
65
+ if self.integrity_note is not None:
66
+ for k in GUARD_KEYS:
67
+ m.pop(k, None)
68
+ m["via"] = self.via
69
+ m["worktree_dirty"] = self.dirty
70
+ if self.run_by:
71
+ m["run_by"] = self.run_by
72
+ return m
73
+
74
+ def notes(self) -> str:
75
+ n = self.source_note
76
+ if self.dirty:
77
+ n += f"; {self.changed} uncommitted path(s) in the checkout: this run is not a run of {self.commit[:12]}"
78
+ if self.integrity_note is not None:
79
+ n += f"; guard not computed: {self.integrity_note}"
80
+ else:
81
+ n += f"; guard against {self.base.ref} (merge-base {self.base.merge_base[:12]})"
82
+ if self.interrupted:
83
+ n += f"; interrupted ({self.interrupted})"
84
+ return n[:2000]
85
+
86
+
87
+ def _integrity(repo: Path, sha: str, lg: Ledger | None = None, piece: str | None = None,
88
+ exclude: set[str] | frozenset[str] = frozenset()) -> tuple[Base, Integrity] | str:
89
+ """The guard of a run against the piece's base (declarations.guard_base_ref; the recorded base needs lg)."""
90
+ try:
91
+ if not repo.is_dir():
92
+ return f"{repo} no longer exists"
93
+ gb = declarations.guard_base_ref(repo, None, lg, piece, exclude, sha)
94
+ b = declarations.read_base(repo, gb.ref, sha, source=gb.source, label=gb.label)
95
+ return b, guard.integrity(repo, b, sha)
96
+ except (BenchbookError, OSError, ValueError) as e:
97
+ return str(e).splitlines()[0] if str(e) else type(e).__name__
98
+
99
+
100
+ def build(event: str, data: dict[str, Any], lg: Ledger | None = None) -> LocalRun:
101
+ """The attempt a spool entry describes. KeyError/TypeError/ValueError on a malformed entry (the spool moves it to
102
+ dead/). With lg the guard uses the piece's recorded base, leaving out records by its implementers: the run's
103
+ agent (a check run is its implementer's own) and the reporters of its completion claims at the commit, as check
104
+ verify finds them; without lg, [guard] base or origin/main."""
105
+ name, status, sha = str(data["check"]), STATUSES[str(data["status"])], str(data["sha"])
106
+ failed = [(str(t[0]), None if t[1] is None else str(t[1])) for t in data.get("failed_tests") or []]
107
+ part = data.get("signature") # check run signs where the output was; the Bash hook leaves it to check_part
108
+ result = CheckResult(name, status, data.get("exit_code"), int(data.get("duration_ms") or 0), failed,
109
+ data.get("last_line_hash"), signature=part if isinstance(part, str) and part else None)
110
+ piece = str(data["piece"])
111
+ exclude: set[str] = set()
112
+ if lg is not None:
113
+ # the agent the attempt is recorded under: its name, or under BENCHBOOK_TOKEN the token's agent
114
+ runner = str(data["agent"]) if data.get("agent") else lg.agent if lg.token is not None else None
115
+ exclude = checks.implementers_of(lg, piece, sha, runner)
116
+ found = _integrity(Path(str(data["repo"])), sha, lg, piece, exclude)
117
+ paths: list[str] = []
118
+ if isinstance(found, str):
119
+ base, integ, note = Base("", "", "", "", {}, [], False), Integrity([], False), found
120
+ else:
121
+ (base, integ), note = found, None
122
+ try: # T06: the directories the commit changed, as check verify records them
123
+ paths = gitrepo.path_prefixes(gitrepo.changed_paths(Path(str(data["repo"])), base.merge_base, sha))
124
+ except BenchbookError:
125
+ paths = []
126
+ source = f"{SOURCES[event]}: {name} in {data['repo']}"
127
+ if event == "bash-result":
128
+ ids = {k: data.get(k) for k in ("harness", "session_id", "tool_use_id", "agent_type") if data.get(k)}
129
+ if ids:
130
+ source += " (" + ", ".join(f"{k} {v}" for k, v in ids.items()) + ")"
131
+ approach = str(data["approach"]) if data.get("approach") else None
132
+ definition = data.get("definition")
133
+ run_by = data.get("agent") or data.get("agent_type")
134
+ return LocalRun(piece, sha, base, integ, [result], result.duration_ms, data.get("interrupted"),
135
+ approach, declared=list(base.checks),
136
+ via=str(data.get("via") or ("bash-hook" if event == "bash-result" else "check-run")),
137
+ paths=paths, dirty=bool(data.get("dirty")), changed=int(data.get("changed") or 0),
138
+ integrity_note=note, source_note=source,
139
+ definition=definition if isinstance(definition, str) and definition else None,
140
+ run_by=str(run_by)[:100] if run_by else None)
141
+
142
+
143
+ def record_spooled(event: str, data: dict[str, Any], project: str, receipt_id: UUID) -> str:
144
+ """The spool processor's step for an attempt entry: 'recorded:e:<id>'. Raises like any ledger write; the spool
145
+ keeps transient failures queued and moves permanent ones to dead/."""
146
+ from ..config import default_agent
147
+ from ..core.ids import short
148
+ from ..core.ledger import Ledger
149
+
150
+ str(data["check"]), STATUSES[str(data["status"])], str(data["sha"]), str(data["piece"]), str(data["repo"]) # noqa: B018 - a malformed entry goes to dead/ before any connection
151
+ agent = data.get("agent") or None
152
+ # Without a name the attempt is the harness's (the hook's), or under BENCHBOOK_TOKEN the token's agent.
153
+ lg = Ledger.open(project=project, agent=agent or default_agent("hook"), role=None if agent else "harness")
154
+ if lg.token is not None:
155
+ from ..hooks.spooler import remember_writer
156
+
157
+ remember_writer(lg.project_id, lg.agent)
158
+ if "completion" not in lg.pack.claim_kinds:
159
+ raise BenchbookError(f"check attempts need the code pack (benchbook init --pack code); {project} uses "
160
+ f"{lg.pack.name}")
161
+ run = build(event, data, lg) # after the ledger: the guard base the lead recorded for the piece is in it
162
+ rec = checks._record(lg, run, None, None, receipt_id=receipt_id)
163
+ out = f"recorded:{short('experiment', rec.experiment_id)}"
164
+ if rec.discarded_id is not None:
165
+ out += f" discarded:{short('claim', rec.discarded_id)}{'' if rec.discarded_new else ' (seen before)'}"
166
+ elif rec.discarded_error:
167
+ out += f" (discarded-approach claim not recorded: {rec.discarded_error})"
168
+ return out
169
+
170
+
171
+ # ---------------------------------------------------------------------------------------------- the gate
172
+
173
+
174
+ def live_piece(project: str, piece: str) -> bool:
175
+ """Whether piece has a live `piece start` intent (v_inflight: claimed and its lease not expired). The gate's
176
+ test for "this branch is a piece" when only the branch name says so. A plain connection, as check_states."""
177
+ import psycopg
178
+
179
+ from ..db.conn import database_url
180
+
181
+ with psycopg.connect(database_url(), connect_timeout=CONNECT_TIMEOUT, autocommit=True) as conn:
182
+ conn.execute(f"SET statement_timeout = {STATEMENT_TIMEOUT_MS}")
183
+ row = conn.execute("SELECT 1 FROM benchbook.v_inflight WHERE project_id = %s AND is_intent"
184
+ " AND 'piece' = ANY(tags) AND spec ->> 'piece' = %s LIMIT 1", (project, piece)).fetchone()
185
+ return row is not None
186
+
187
+
188
+ def check_states(project: str, piece: str, sha: str,
189
+ junit_checks: Collection[str] = ()) -> tuple[str | None, dict[str, bool]]:
190
+ """(the project's pack, or None when the project does not exist; {check name: passed}) over the valid,
191
+ finished attempts of piece at sha whose checkout was clean. A check is passed when at least one such attempt
192
+ passed it. Raw Bash records made by older versions cannot identify which run produced a JUnit report.
193
+ Read with a plain connection (no migration, no agent registration): the gate only reads, and must
194
+ answer within the hook's timeout or fail open."""
195
+ import psycopg
196
+
197
+ from ..db.conn import database_url
198
+
199
+ with psycopg.connect(database_url(), connect_timeout=CONNECT_TIMEOUT, autocommit=True) as conn:
200
+ conn.execute(f"SET statement_timeout = {STATEMENT_TIMEOUT_MS}")
201
+ row = conn.execute("SELECT pack FROM benchbook.projects WHERE id = %s", (project,)).fetchone()
202
+ if row is None:
203
+ return None, {}
204
+ rows = conn.execute(
205
+ """SELECT c.key, bool_or(c.value = 'ok') AS passed
206
+ FROM benchbook.experiments_valid e,
207
+ jsonb_each_text(CASE WHEN jsonb_typeof(e.metrics -> 'checks') = 'object'
208
+ THEN e.metrics -> 'checks' ELSE '{}'::jsonb END) AS c(key, value)
209
+ WHERE e.project_id = %s AND e.config ->> 'piece' = %s AND e.code_ref = %s AND e.run_status = 'ok'
210
+ AND e.metrics -> 'worktree_dirty' IS DISTINCT FROM 'true'::jsonb
211
+ AND (c.value <> 'ok' OR c.key <> ALL(%s::text[])
212
+ OR e.metrics ->> 'via' IS DISTINCT FROM 'bash-hook')
213
+ GROUP BY c.key""", (project, piece, sha, list(junit_checks))).fetchall()
214
+ return str(row[0]), {str(k): bool(v) for k, v in rows}
@@ -0,0 +1,300 @@
1
+ """The merge-base as a control: run its checks to tell a failure the commit introduced from one that was already there,
2
+ count the tests on both sides, and find passing runs of the piece elsewhere."""
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import json
7
+ import posixpath
8
+ import re
9
+ import threading
10
+ from collections.abc import Callable, Collection, Sequence
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ from ..config import CheckSpec
16
+ from ..core.runner import Interrupted, forget_stopped, stop_commands
17
+ from . import rerun, signature
18
+ from .declarations import Base
19
+ from .gitrepo import _git
20
+ from .guard import Integrity
21
+ from .rerun import MAX_FAILED_SHOWN, CheckResult, Prepared, _signals_held
22
+
23
+ if TYPE_CHECKING:
24
+ from ..core.ledger import Ledger
25
+
26
+ # ---------------------------------------------------------------------------------------------------- baseline (T03)
27
+
28
+ @dataclass
29
+ class BaseRun:
30
+ """One check's result at the merge-base."""
31
+ status: str
32
+ signature: str | None
33
+ failed: list[str]
34
+ tests: int | None
35
+ tsc_output: tuple[str, ...] = ()
36
+
37
+
38
+ def baseline(repo: Path, b: Base, specs: Sequence[CheckSpec],
39
+ env: dict[str, str] | None = None) -> tuple[dict[str, BaseRun], BaseException | None]:
40
+ """Run the reference checks now, using the same environment as the candidate."""
41
+ prepared = Prepared()
42
+ results, interrupted = rerun.run_checks(repo, b.merge_base, specs, env, b.prep, prepared)
43
+ if interrupted is not None or prepared.error is not None:
44
+ return {}, interrupted
45
+ return {r.name: BaseRun(r.status, r.signature, [t for t, _ in r.failed_tests], r.tests, r.tsc_output)
46
+ for r in results}, None
47
+
48
+
49
+ class EarlyBaseline:
50
+ """[verify] parallel_baseline: count_tests's merge-base run, started in a thread beside the commit's checks. Its
51
+ result is used only when count_tests would have run exactly these checks; otherwise it runs them as before."""
52
+
53
+ def __init__(self, repo: Path, b: Base, specs: list[CheckSpec], env: dict[str, str] | None) -> None:
54
+ self.names = [s.name for s in specs]
55
+ self._box: dict[str, Any] = {}
56
+ # Set when the run (and its worktree's removal) is over. Waiting on it, not on Thread.join or is_alive: before
57
+ # Python 3.12 a signal that interrupts join can leave is_alive() False while the thread still runs.
58
+ self._done = threading.Event()
59
+ self._thread = threading.Thread(target=self._run, args=(repo, b, specs, env), daemon=True,
60
+ name="benchbook-merge-base")
61
+ self._thread.start()
62
+
63
+ def _run(self, repo: Path, b: Base, specs: list[CheckSpec], env: dict[str, str] | None) -> None:
64
+ try:
65
+ self._box["value"] = baseline(repo, b, specs, env)
66
+ except BaseException as e: # noqa: BLE001 - handed to the caller
67
+ self._box["error"] = e
68
+ finally:
69
+ self._done.set()
70
+
71
+ def result(self) -> tuple[dict[str, BaseRun], BaseException | None]:
72
+ """The run's result; an interruption while waiting for it (verify traps SIGTERM and SIGHUP while the run
73
+ lives) stops the run and comes back as the run's interruption, as a sequential baseline's would."""
74
+ try:
75
+ while not self._done.wait(0.1):
76
+ pass
77
+ except (Interrupted, KeyboardInterrupt) as e:
78
+ with _signals_held():
79
+ self.stop()
80
+ return {}, e
81
+ if "error" in self._box:
82
+ raise self._box["error"]
83
+ return self._box["value"] # type: ignore[no-any-return]
84
+
85
+ def stop(self) -> None:
86
+ """End the run if it is still going (its check's process group is killed) and wait for its cleanup."""
87
+ ident = self._thread.ident
88
+ if ident is not None and not self._done.is_set():
89
+ stop_commands(ident)
90
+ self._done.wait()
91
+ forget_stopped(ident)
92
+
93
+
94
+ def count_tests(repo: Path, b: Base, results: list[CheckResult], integ: Integrity,
95
+ env: dict[str, str] | None, early: EarlyBaseline | None = None) -> BaseException | None:
96
+ """T04: the JUnit testcases that ran here and at the merge-base. Each JUnit check that reported a count is
97
+ compared with its own merge-base run (integ.fewer_tests_in names those that ran fewer); tests_before and
98
+ tests_after are the sums, for the record. Run only when guarded files changed; the merge-base runs come from
99
+ the current environment. Returns an interruption of that run."""
100
+ counted = [r for r in results if b.checks[r.name].junit and r.tests is not None]
101
+ if not counted:
102
+ return None
103
+ if early is not None and early.names == [r.name for r in counted]:
104
+ runs, interrupted = early.result()
105
+ else:
106
+ runs, interrupted = baseline(repo, b, [b.checks[r.name] for r in counted], env)
107
+ if interrupted is not None:
108
+ return interrupted
109
+ before = after = 0
110
+ seen = False
111
+ fewer = []
112
+ for r in counted:
113
+ was = runs[r.name].tests if r.name in runs else None
114
+ if isinstance(was, int) and r.tests is not None:
115
+ before, after, seen = before + was, after + r.tests, True
116
+ if r.tests < was:
117
+ fewer.append(r.name)
118
+ if seen:
119
+ integ.tests_before, integ.tests_after, integ.fewer_tests_in = before, after, fewer
120
+ return None
121
+
122
+
123
+ def same_failure(r: CheckResult, base: BaseRun) -> bool:
124
+ """Whether a failing check fails the same way at the merge-base: an equal signature element, or (JUnit) every
125
+ test failing here fails there too."""
126
+ if base.status not in ("fail", "timeout"):
127
+ return False
128
+ if r.signature and base.signature and r.signature == base.signature:
129
+ return True
130
+ mine = {t for t, _ in r.failed_tests}
131
+ return bool(mine) and len(r.failed_tests) < MAX_FAILED_SHOWN and mine <= set(base.failed)
132
+
133
+
134
+ # The checks an implementer's own clean run of PIECE at COMMIT passed (check run, the Bash hook: metrics.via): run
135
+ # by one of the piece's implementers (the attempt's author, or metrics.run_by, the agent type the Bash hook saw) and
136
+ # of the definition verify runs (metrics.check_definitions, CheckSpec.definition). A run without either says nothing
137
+ # about this check. A raw Bash pass of a JUnit check proves nothing (docs/claude-code.md) and is left out, as the
138
+ # completion gate does.
139
+ _PASSED_ELSEWHERE = (
140
+ "SELECT DISTINCT c.key FROM benchbook.experiments_valid e,"
141
+ " jsonb_each_text(CASE WHEN jsonb_typeof(e.metrics -> 'checks') = 'object' THEN e.metrics -> 'checks'"
142
+ " ELSE '{}'::jsonb END) AS c(key, value)"
143
+ " WHERE e.project_id = %s AND e.config ->> 'piece' = %s AND e.code_ref = %s AND e.run_status = 'ok'"
144
+ " AND e.metrics ->> 'via' IS NOT NULL AND e.metrics -> 'worktree_dirty' IS DISTINCT FROM 'true'::jsonb"
145
+ " AND c.value = 'ok' AND (c.key <> ALL(%s::text[]) OR e.metrics ->> 'via' IS DISTINCT FROM 'bash-hook')"
146
+ " AND (e.author = ANY(%s::text[]) OR e.metrics ->> 'run_by' = ANY(%s::text[]))"
147
+ " AND jsonb_typeof(e.metrics -> 'check_definitions') = 'object'"
148
+ " AND e.metrics -> 'check_definitions' ->> c.key = %s::jsonb ->> c.key")
149
+
150
+
151
+ def passed_elsewhere(lg: Ledger, piece: str, commit: str, b: Base, implementers: Collection[str]) -> set[str]:
152
+ """The checks of b that an implementer's own clean run of piece at commit passed, under b's definition."""
153
+ if not implementers:
154
+ return set()
155
+ junit = [n for n, s in b.checks.items() if s.junit]
156
+ who = sorted(implementers)
157
+ defs = json.dumps({n: s.definition for n, s in b.checks.items()})
158
+ return {str(r["key"]) for r in lg.sql_internal(_PASSED_ELSEWHERE, (lg.project_id, piece, commit, junit, who, who,
159
+ defs))}
160
+
161
+
162
+ # tsc on an import of an image or a CSS module that nothing declares. Their types come from a .d.ts, which a framework
163
+ # may generate and git ignore (Next.js: next-env.d.ts): a clean worktree lacks them although the file itself is there.
164
+ # Not any stylesheet: ./button.css can be the module button.css.ts, which the piece may have to write.
165
+ _UNDECLARED = re.compile(r"(?P<file>\S.*?)\(\d+,\d+\): error TS2307: Cannot find module '(?P<asset>[^']+\."
166
+ r"(?:png|jpe?g|gif|svg|webp|avif|ico|bmp|module\.(?:css|scss|sass)))'"
167
+ r"(?: or its corresponding type declarations)?\.")
168
+ _BANNER = re.compile(r"[>$] (.*)") # npm, pnpm, yarn and bun print the script's command
169
+ # The other lines such an output may have: script runners, and linters that found no error.
170
+ _HARMLESS = re.compile(r"yarn run v[\d.]+|info Visit https://yarnpkg\.com/\S* for documentation about this command\."
171
+ r"|error Command failed with exit code \d+\.|error: script \"[^\"]*\" exited with code \d+"
172
+ r"|ELIFECYCLE\s+Command failed with exit code \d+\.|Done in <time>\.?"
173
+ r"|[^\s:]+\.[cm]?[jt]sx?|\d+:\d+\s+[Ww]arning:?\s.*" # eslint: a file, then its warnings
174
+ r"|✖ \d+ problems? \(0 errors, \d+ warnings?\)|✔ No ESLint warnings or errors"
175
+ r"|Checking formatting\.\.\.|All matched files use Prettier code style!")
176
+ _TSC_STEP = re.compile(r"(?:(?:npx|bunx|yarn|pnpm(?: exec)?) )?tsc(?: .*)?")
177
+ # What runs the rest after a step failed: other shell operators than &&, and runners of several packages or scripts.
178
+ _GOES_ON = re.compile(r"[;|&\n]|\s(?:-ws|-r|-w|--(?:workspaces?|recursive|filter|parallel|continue|no-bail))\b|"
179
+ r"\b(?:run-[ps]|npm-run-all|concurrently|turbo|nx|lerna|workspaces)\b")
180
+ # Files that decide what an import finds, whatever file the error is in (typescript-config/base.json is one).
181
+ _RESOLUTION = re.compile(r"config|\.d\.(?:[^/]+\.)?[cm]?ts$|(?:^|/)(?:package(?:-lock)?\.json|npm-shrinkwrap\.json|"
182
+ r"pnpm-(?:lock|workspace)\.yaml|yarn\.lock|bun\.lockb?|\.npmrc|\.yarnrc\.yml)$", re.IGNORECASE)
183
+
184
+
185
+ # A tsc command known to use the tsconfig.json of its folder: another option, a file or a variable can change the paths.
186
+ _OWN_TSCONFIG = re.compile(r"(?:[a-z]+ )*tsc(?: --?(?:noemit|pretty|incremental|skiplibcheck)(?: (?:true|false))?"
187
+ r"| (?:-p|--?project) (?:\./?|(?:\./)?tsconfig\.json))*", re.IGNORECASE)
188
+
189
+
190
+ def _aliased(asset: str, folder: str, read: Callable[[str], str | None]) -> set[str]:
191
+ """The files that compilerOptions.paths gives for a non-relative import, in the tsconfig.json that tsc finds from
192
+ folder ("" or "web/"). Empty when that file does not settle it: the import may then be a package's, and a package
193
+ that is not installed is work for the piece. read: a file's text at the merge-base, None when it has none."""
194
+ while (text := read(folder + "tsconfig.json")) is None:
195
+ if not folder:
196
+ return set()
197
+ folder = folder[:folder.rstrip("/").rfind("/") + 1]
198
+ strings = r'("(?:\\.|[^"\\])*")' # kept as they are: "@/*" opens no comment
199
+ text = text.removeprefix(chr(0xFEFF)) # a byte order mark
200
+ text = re.sub(strings + r"|//[^\n]*|/\*.*?\*/", lambda m: m[1] or "", text, flags=re.DOTALL)
201
+ try:
202
+ config = json.loads(re.sub(strings + r"|,(?=\s*[}\]])", lambda m: m[1] or "", text))
203
+ options = config["compilerOptions"]
204
+ if "extends" in config and "baseUrl" not in options: # an inherited baseUrl moves the paths
205
+ return set()
206
+ base = posixpath.join(folder, options.get("baseUrl", "."))
207
+ fits: dict[tuple[bool, int], list[str]] = {}
208
+ for pattern, targets in options["paths"].items():
209
+ before, star, after = pattern.partition("*")
210
+ if asset == pattern or (star and len(asset) >= len(before + after) and asset.startswith(before)
211
+ and asset.endswith(after)):
212
+ middle = asset[len(before):len(asset) - len(after)] if star else ""
213
+ fits.setdefault((not star, len(before)), [t.replace("*", middle, 1) if star else t for t in targets])
214
+ # tsc takes one pattern: the exact one, else the first with the longest text before its *
215
+ return {posixpath.normpath(posixpath.join(base, t)) for t in fits[max(fits)]} if fits else set()
216
+ except (ValueError, KeyError, TypeError, AttributeError): # not the shape of a tsconfig.json
217
+ return set()
218
+
219
+
220
+ def _stopped_at_tsc(cmd: str, output: Collection[str]) -> str | None:
221
+ """The tsc command, when tsc, which printed errors, is the step that failed the check: it is a step of its own, and
222
+ the command and every script it ran join their steps with && alone, so a step that failed without a word stopped it
223
+ before."""
224
+ commands = [cmd, *(m[1] for line in output if (m := _BANNER.fullmatch(line)))]
225
+ if any(_GOES_ON.search(c.replace("&&", " ")) for c in commands):
226
+ return None
227
+ steps = [step.strip() for c in commands for step in c.split("&&") if _TSC_STEP.fullmatch(step.strip())]
228
+ return steps[0] if len(steps) == 1 else None
229
+
230
+
231
+ def lacks_only_declarations(r: CheckResult, cmd: str, own: Collection[str], tracked: Collection[str],
232
+ read: Callable[[str], str | None]) -> bool:
233
+ """Whether a check failed at tsc, and only on imports of images and CSS modules that the merge-base has (tracked;
234
+ read gives a file's text there), by a relative path or an alias of tsconfig.json: their type declarations are
235
+ missing, so there is no file left for the piece to write. Every line of the output is
236
+ accounted for, and the piece (own, the files it changed) touched neither the importing file, nor the imported one,
237
+ nor one that decides what an import finds."""
238
+ errors = []
239
+ for line in r.tsc_output:
240
+ if m := _UNDECLARED.fullmatch(line):
241
+ errors.append((m["file"].replace("\\", "/"), m["asset"]))
242
+ elif not _BANNER.fullmatch(line) and not _HARMLESS.fullmatch(line):
243
+ return False
244
+ tsc = _stopped_at_tsc(cmd, r.tsc_output)
245
+ if not errors or not own or any(_RESOLUTION.search(p) for p in own) or tsc is None:
246
+ return False
247
+ for printed, asset in errors:
248
+ seen = re.sub(r"^(?:\.\.?/)+", "", printed) # tsc prints paths from its own folder
249
+ importers = [p for p in tracked if p == seen or p.endswith("/" + seen)]
250
+ if not importers:
251
+ return False
252
+ for importer in importers: # several when packages have the same file: it has to hold for each
253
+ if asset.startswith(("./", "../")):
254
+ found = {posixpath.normpath(posixpath.join(posixpath.dirname(importer), asset))}
255
+ elif not _OWN_TSCONFIG.fullmatch(tsc) or seen != printed:
256
+ return False
257
+ else: # the rest of the importer's path is the folder tsc ran in
258
+ found = _aliased(asset, importer.removesuffix(seen), read)
259
+ if found.isdisjoint(tracked) or importer in own or not found.isdisjoint(own):
260
+ return False
261
+ return True
262
+
263
+
264
+ def classify_environment(repo: Path, b: Base, results: list[CheckResult], env: dict[str, str] | None,
265
+ elsewhere: set[str], own: Collection[str] = ()
266
+ ) -> tuple[str | None, str | None, BaseException | None]:
267
+ """T03: a failing check is an environment failure when it fails the same way at the merge-base, which is then
268
+ re-run, and something says the piece did not cause or have to fix it: the implementer's own clean run of this
269
+ commit passed it (elsewhere), or only type declarations are missing (lacks_only_declarations) and the whole output
270
+ is the merge-base's, line numbers included. Any other check that fails at the merge-base can do so by design (the
271
+ piece's goal), whichever file its failure is in, and stays the piece's failure. Returns (the reason when every
272
+ failing check is an environment failure, the merge-base's signature of those checks, an interruption of the
273
+ baseline run)."""
274
+ failing = [r for r in results if r.status in ("fail", "timeout")]
275
+ undeclared = [r for r in failing if r.name not in elsewhere]
276
+ if not failing or not all(r.tsc_output for r in undeclared):
277
+ return None, None, None
278
+ if undeclared:
279
+ tree = set(_git(repo, "ls-tree", "-r", "-z", "--name-only", "--full-tree", b.merge_base).stdout.split("\0"))
280
+
281
+ @functools.cache # asked for each error
282
+ def read(path: str) -> str | None:
283
+ return _git(repo, "show", f"{b.merge_base}:{path}").stdout if path in tree else None
284
+
285
+ if not all(lacks_only_declarations(r, b.checks[r.name].cmd, own, tree, read) for r in undeclared):
286
+ return None, None, None
287
+ runs, interrupted = baseline(repo, b, [b.checks[r.name] for r in failing], env)
288
+ for r in failing:
289
+ r.environment = r.name in runs and same_failure(r, runs[r.name]) and (
290
+ r.name in elsewhere or r.tsc_output == runs[r.name].tsc_output)
291
+ if interrupted is not None or not all(r.environment for r in failing):
292
+ return None, None, interrupted
293
+ names = ", ".join(r.name for r in failing)
294
+ sig = signature.combine((r.name, runs[r.name].signature) for r in failing)
295
+ why = (f" ({', '.join(r.name for r in undeclared)}: image or CSS module imports without type declarations, in "
296
+ "files the piece did not change; have [verify] copy or prepare provide the .d.ts, such as Next.js's "
297
+ "next-env.d.ts)"
298
+ if undeclared else "")
299
+ return (f"{names} {'fails' if len(failing) == 1 else 'fail'} the same way at the merge-base "
300
+ f"{b.merge_base[:12]}{why}", sig, None)