acceptbox 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.
@@ -0,0 +1,265 @@
1
+ """Прогон одного коммита через ``witnessbox gate`` с fail-closed проверкой схемы (L21).
2
+
3
+ Импорт внутренних модулей witnessbox запрещён: используется только CLI
4
+ ``witnessbox gate <ebt-dir> <clone> <run-dir>`` и его файлы gate.json/report.json.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import time
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ from .command import run_process_group
19
+ from .git import strip_local_env_vars
20
+ from .verdict import RunOutcome
21
+
22
+ WITNESSBOX_MIN_VERSION = (0, 10, 0)
23
+ WITNESSBOX_SUPPORTED_TEXT = ">=0.10.0"
24
+
25
+ # reasons, означающие сбой окружения/гейта, а не осмысленный красный.
26
+ ERROR_REASONS = frozenset({"gate_error", "checker_error", "tests_error"})
27
+ # reasons, при которых красный не засчитывается как «по нужной причине».
28
+ RED_OTHER_REASONS = frozenset({"gate_error", "checker_error", "pinned_drift",
29
+ "protected_paths_changed"})
30
+ # Находки, подтверждающие нарушение инварианта (L9); CHECKER_DISAGREES не засчитывается.
31
+ TARGET_KINDS = frozenset({"FALSE_PROOF", "CONFIRMED_VIOLATION"})
32
+
33
+ # Финальный выпуск PEP 440 (возможны post/local); pre-release разбирается как ошибка.
34
+ _VERSION_RE = re.compile(r"(\d+)\.(\d+)\.(\d+)(?:\.post\d+)?(?:\+[0-9A-Za-z._-]+)?\Z")
35
+
36
+ LOG_NAME = "witnessbox.log"
37
+
38
+
39
+ @dataclass
40
+ class WitnessboxStatus:
41
+ """Диагностика установленного witnessbox для --installation и стадии 3."""
42
+
43
+ status: str # "compatible" | "missing" | "incompatible" | "error"
44
+ path: str | None
45
+ version: str | None
46
+ message: str
47
+ info: dict | None = None # валидный JSON --installation при совместимости
48
+
49
+
50
+ def parse_version_tuple(value: str) -> tuple[int, int, int] | None:
51
+ """(major, minor, patch) финального выпуска; иначе None (fail-closed)."""
52
+ if not isinstance(value, str):
53
+ return None
54
+ match = _VERSION_RE.fullmatch(value)
55
+ if match is None:
56
+ return None
57
+ return int(match.group(1)), int(match.group(2)), int(match.group(3))
58
+
59
+
60
+ def check_witnessbox_installation(env: dict[str, str] | None = None) -> WitnessboxStatus:
61
+ """Наличие и совместимость witnessbox: ``>=0.10.0`` без верхней границы (L21)."""
62
+ executable = shutil.which("witnessbox", path=env.get("PATH") if env else None)
63
+ if executable is None:
64
+ return WitnessboxStatus("missing", None, None, "команда witnessbox не найдена в PATH")
65
+ run_env = strip_local_env_vars(env) if env is not None else None
66
+ try:
67
+ completed = subprocess.run(
68
+ [executable, "--installation"], env=run_env,
69
+ capture_output=True, timeout=15, check=False,
70
+ )
71
+ except (OSError, subprocess.SubprocessError) as run_error:
72
+ return WitnessboxStatus(
73
+ "error", executable, None, f"сбой witnessbox --installation: {run_error}")
74
+ if completed.returncode != 0:
75
+ detail = completed.stderr.decode("utf-8", "replace").strip()
76
+ message = f"witnessbox --installation завершился с кодом {completed.returncode}"
77
+ return WitnessboxStatus("error", executable, None,
78
+ f"{message}: {detail}" if detail else message)
79
+ try:
80
+ info = json.loads(completed.stdout.decode("utf-8", "replace"))
81
+ except (UnicodeDecodeError, json.JSONDecodeError):
82
+ return WitnessboxStatus("error", executable, None,
83
+ "witnessbox --installation вывел некорректный JSON")
84
+ if not isinstance(info, dict) or info.get("distribution") != "witnessbox":
85
+ return WitnessboxStatus(
86
+ "error", executable, None,
87
+ 'схема --installation не совпадает: distribution != "witnessbox"')
88
+ for key in ("version", "gate_sha256", "checker_sha256"):
89
+ if not isinstance(info.get(key), str) or not info[key]:
90
+ return WitnessboxStatus(
91
+ "error", executable, None, f"схема --installation: ключ {key} отсутствует или пуст")
92
+ parsed = parse_version_tuple(info["version"])
93
+ if parsed is None:
94
+ return WitnessboxStatus(
95
+ "error", executable, info["version"],
96
+ f"не удалось разобрать версию witnessbox: {info['version']!r}")
97
+ if parsed < WITNESSBOX_MIN_VERSION:
98
+ return WitnessboxStatus(
99
+ "incompatible", executable, info["version"],
100
+ f"witnessbox {info['version']} ниже поддерживаемой версии {WITNESSBOX_SUPPORTED_TEXT}")
101
+ return WitnessboxStatus("compatible", executable, info["version"],
102
+ f"witnessbox {info['version']} совместим", info=info)
103
+
104
+
105
+ def _read_json(path: Path) -> dict | None:
106
+ """JSON-объект или None при любой проблеме чтения/разбора (fail-closed)."""
107
+ try:
108
+ value = json.loads(path.read_text(encoding="utf-8", errors="replace"))
109
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
110
+ return None
111
+ return value if isinstance(value, dict) else None
112
+
113
+
114
+ def _sha256_file(path: Path) -> str:
115
+ return hashlib.sha256(path.read_bytes()).hexdigest()
116
+
117
+
118
+ def read_findings_inv(run_dir: Path) -> list[str]:
119
+ """``inv`` целевых находок report.json прогона — для coverage.accept.json."""
120
+ report = _read_json(Path(run_dir) / "report.json")
121
+ if report is None:
122
+ return []
123
+ findings = report.get("findings")
124
+ if not isinstance(findings, list):
125
+ return []
126
+ return [entry["inv"] for entry in findings if _is_target_finding(entry)]
127
+
128
+
129
+ def _is_target_finding(entry: object, invariants: set[str] | None = None) -> bool:
130
+ """Целевая находка L9; нестроковые kind/inv (сломанная схема) не засчитываются."""
131
+ if not isinstance(entry, dict):
132
+ return False
133
+ kind, inv = entry.get("kind"), entry.get("inv")
134
+ if not isinstance(kind, str) or not isinstance(inv, str) or kind not in TARGET_KINDS:
135
+ return False
136
+ return invariants is None or inv in invariants
137
+
138
+
139
+ def classify_gate_run(run_dir: Path, commit_sha: str, approved_spec_sha256: str,
140
+ expected_invariants, installation_info: dict, *,
141
+ gate_exit_code: int | None, failure_message: str | None,
142
+ duration_ms: int, log_path: str | None) -> RunOutcome:
143
+ """Классификация одного прогона по gate.json/report.json (L9, L21).
144
+
145
+ Чистая функция от run_dir: тестируется на файлах без subprocess.
146
+ """
147
+ run_dir = Path(run_dir)
148
+ expected = set(expected_invariants or ())
149
+ gate_path = run_dir / "gate.json"
150
+ report_path = run_dir / "report.json"
151
+
152
+ def outcome(status: str, reason: str, artifacts: dict | None = None) -> RunOutcome:
153
+ return RunOutcome(status=status, exit_code=gate_exit_code, reason=reason,
154
+ duration_ms=duration_ms, log_path=log_path, artifacts=artifacts)
155
+
156
+ # Сбой запуска гейта: OSError, таймаут, сигнал.
157
+ if failure_message is not None:
158
+ return outcome("error", failure_message)
159
+ if gate_exit_code is None:
160
+ return outcome("error", "witnessbox gate не вернул код выхода")
161
+ if gate_exit_code < 0:
162
+ return outcome("error", f"witnessbox gate завершён сигналом {-gate_exit_code}")
163
+
164
+ # Fail-closed проверка схемы gate.json (формат 1) и перекрёстных полей.
165
+ gate = _read_json(gate_path)
166
+ if gate is None:
167
+ return outcome("error", "gate.json отсутствует или не является корректным JSON-объектом")
168
+ if type(gate.get("format")) is not int or gate["format"] != 1:
169
+ return outcome("error",
170
+ f"несовместимая схема gate.json: format={gate.get('format')!r}, ожидается 1")
171
+ reasons = gate.get("reasons")
172
+ if type(gate.get("exit_code")) is not int \
173
+ or not isinstance(reasons, list) \
174
+ or not all(isinstance(item, str) for item in reasons) \
175
+ or not isinstance(gate.get("commit"), str) \
176
+ or not isinstance(gate.get("spec_sha256"), str):
177
+ return outcome("error", "несовместимая схема gate.json: некорректные ключи или типы")
178
+ verifier = gate.get("verifier")
179
+ if not isinstance(verifier, dict) or verifier.get("distribution") != "witnessbox" \
180
+ or not isinstance(verifier.get("version"), str) or not verifier["version"] \
181
+ or not isinstance(verifier.get("gate_sha256"), str) or not verifier["gate_sha256"]:
182
+ return outcome("error", "несовместимая схема gate.json: блок verifier некорректен")
183
+ if gate["commit"].lower() != commit_sha.lower():
184
+ return outcome("error", "gate.json: commit не совпадает с прогоняемым коммитом")
185
+ if gate["spec_sha256"].lower() != approved_spec_sha256.lower():
186
+ return outcome("error", "gate.json: spec_sha256 не совпадает с ebt/spec.toml")
187
+ if verifier["version"] != installation_info.get("version") \
188
+ or verifier["gate_sha256"] != installation_info.get("gate_sha256"):
189
+ return outcome("error",
190
+ "gate.json: verifier не совпадает с установленным witnessbox --installation")
191
+ if gate["exit_code"] != gate_exit_code:
192
+ return outcome("error",
193
+ f"gate.json: exit_code ({gate['exit_code']}) не совпадает с кодом процесса ({gate_exit_code})")
194
+
195
+ reason_set = set(reasons)
196
+ if gate_exit_code == 2 or ERROR_REASONS & reason_set:
197
+ return outcome("error", f"witnessbox gate сообщил об ошибке: reasons={reasons}")
198
+
199
+ artifacts = {"gate.json": {"path": gate_path.name, "sha256": _sha256_file(gate_path)},
200
+ "spec_sha256": gate["spec_sha256"]}
201
+ if report_path.is_file():
202
+ artifacts["report.json"] = {"path": report_path.name, "sha256": _sha256_file(report_path)}
203
+
204
+ if gate_exit_code == 0:
205
+ report = _read_json(report_path)
206
+ if report is None or not isinstance(report.get("findings"), list) \
207
+ or not all(isinstance(entry, dict) for entry in report["findings"]):
208
+ return outcome("error", "exit_code 0, но report.json отсутствует или некорректен")
209
+ return outcome("green", "witnessbox gate: PASS (exit_code 0)", artifacts)
210
+
211
+ if gate_exit_code == 1:
212
+ if "checker_failed" not in reason_set or RED_OTHER_REASONS & reason_set:
213
+ return outcome("red-other",
214
+ f"witnessbox gate красный не по нужной причине: reasons={reasons}",
215
+ artifacts)
216
+ report = _read_json(report_path)
217
+ if report is None or not isinstance(report.get("findings"), list) \
218
+ or not all(isinstance(entry, dict) for entry in report["findings"]):
219
+ return outcome("invalid-report",
220
+ "красный без валидного report.json: findings недоступны", artifacts)
221
+ matched = [entry for entry in report["findings"]
222
+ if _is_target_finding(entry, expected)]
223
+ if matched:
224
+ kinds = ", ".join(sorted({str(entry.get("kind")) for entry in matched}))
225
+ return outcome("red", f"witnessbox gate красный по нужной причине: {kinds}", artifacts)
226
+ return outcome("red-other",
227
+ "красный без целевой находки (FALSE_PROOF/CONFIRMED_VIOLATION по --inv)",
228
+ artifacts)
229
+
230
+ return outcome("error", f"неожидаемый код выхода witnessbox gate: {gate_exit_code}")
231
+
232
+
233
+ def run_commit(worktree: Path, commit_sha: str, run_dir: Path, env: dict[str, str],
234
+ timeout: float, *, ebt_dir: Path, approved_spec_sha256: str,
235
+ expected_invariants: list[str], installation_info: dict,
236
+ witnessbox_bin: str = "witnessbox") -> RunOutcome:
237
+ """Прогон одного коммита: ``witnessbox gate <ebt_dir> <worktree> <run_dir>``."""
238
+ run_dir = Path(run_dir)
239
+ run_dir.mkdir(parents=True, exist_ok=True)
240
+ clean_env = strip_local_env_vars(env)
241
+ argv = [witnessbox_bin, "gate", str(ebt_dir), str(worktree), str(run_dir)]
242
+ started = time.monotonic()
243
+ gate_exit_code: int | None = None
244
+ failure_message: str | None = None
245
+ stdout = stderr = b""
246
+ try:
247
+ completed = run_process_group(argv, cwd=str(run_dir), env=clean_env,
248
+ timeout=timeout)
249
+ except subprocess.TimeoutExpired as expired:
250
+ stdout, stderr = expired.stdout or b"", expired.stderr or b""
251
+ failure_message = f"witnessbox gate превысил таймаут {timeout:g} с"
252
+ except OSError as run_error:
253
+ failure_message = f"не удалось запустить witnessbox gate: {run_error}"
254
+ else:
255
+ stdout, stderr = completed.stdout, completed.stderr
256
+ gate_exit_code = completed.returncode
257
+ if completed.returncode < 0:
258
+ failure_message = f"witnessbox gate завершён сигналом {-completed.returncode}"
259
+ duration_ms = int((time.monotonic() - started) * 1000)
260
+ (run_dir / LOG_NAME).write_bytes(stdout + stderr)
261
+ return classify_gate_run(
262
+ run_dir, commit_sha, approved_spec_sha256, expected_invariants, installation_info,
263
+ gate_exit_code=gate_exit_code, failure_message=failure_message,
264
+ duration_ms=duration_ms, log_path=LOG_NAME,
265
+ )
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.5
2
+ Name: acceptbox
3
+ Version: 0.1.0
4
+ Summary: Независимая приёмка коммитов base → repro → head в режимах command и WitnessBox
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Environment :: Console
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Software Development :: Testing
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+
18
+ # AcceptBox
19
+
20
+ Инструмент независимой приёмки цепочки коммитов `base → repro → head` в изолированных Git worktree с атомарным машиночитаемым отчётом `accept.json` (формат 1). Runtime использует только стандартную библиотеку Python (`>=3.11`).
21
+
22
+ AcceptBox поддерживает два режима приёмки:
23
+ - **`--mode command`** (по умолчанию, L19, L22) — приёмка по обычной тестовой команде без `witnessbox`: `repro` меняет только пути внутри `--tests`, `head` не имеет права менять/переименовывать/удалять файлы репро-теста, `repro` должен завершиться кодом `1` (`red`), `head` — кодом `0` (`green`);
24
+ - **`--mode witnessbox`** — приёмка через внешний CLI [WitnessBox](https://github.com/kaufd/witnessbox) (`>=0.10.0`, без верхней границы, правила L9, L10, L17, L21): проверка доверенного дерева `ebt/`, красная `base` и красный `repro` по целевому инварианту `--inv` (`FALSE_PROOF` / `CONFIRMED_VIOLATION`), зелёный `head`.
25
+
26
+ ## Область применимости (L24)
27
+
28
+ Цепочка `base → repro → head` с красным репро-коммитом предназначена для **багфиксов** (а также для инвариантов, утверждённых человеком до реализации в `--mode witnessbox`).
29
+ Для **новых фич** красный репро-тест, написанный той же моделью, не даёт полезной гарантии, так как модель может подогнать тест и реализацию друг под друга — приёмка фич строится на утверждённой человеком спецификации (D4/L10) и/или независимом ревью и проверке поведения. Политика для **рефакторингов** (`base` зелёный → `head` зелёный без `repro`) ортогональна `--mode` и остаётся отдельной задачей.
30
+
31
+ ## Установка
32
+
33
+ ```sh
34
+ uv tool install acceptbox==0.1.0
35
+ ```
36
+
37
+ Для режима `--mode witnessbox` дополнительно установите WitnessBox (опционально):
38
+
39
+ ```sh
40
+ uv tool install 'witnessbox>=0.10.0'
41
+ ```
42
+
43
+ ## Проверка установки (`--installation`)
44
+
45
+ ```sh
46
+ acceptbox --installation
47
+ ```
48
+
49
+ Выводит JSON формата `1` (`format`, `report_format`, `distribution`, `version`, блоки `git` и `witnessbox` с `supported: ">=0.10.0"`). Возвращает код `0`, если доступны `git` и `acceptbox`, независимо от того, установлен ли `witnessbox`; код `2` — только при отсутствии/сбое `git` или ошибке диагностики `acceptbox`.
50
+
51
+ ## Проектный конфиг (`.acceptbox.toml`, L23, L25, L26)
52
+
53
+ Чтобы не повторять параметры проекта при каждом запуске, добавьте в корень репозитория `.acceptbox.toml`:
54
+
55
+ ```toml
56
+ format = 1
57
+ mode = "command" # опционально: "command" | "witnessbox" (по умолчанию "command")
58
+ timeout = 600 # опционально: положительное число секунд
59
+ protect = ["pyproject.toml"] # опционально: объединяется с --protect из CLI
60
+ env = ["PYTHONPATH=src"] # опционально: KEY или KEY=VAL (BASE, EBT_* и git local-env-vars запрещены)
61
+
62
+ [command]
63
+ tests = ["tests/"]
64
+ argv = ["python3", "-m", "unittest", "discover", "-s", "tests"]
65
+
66
+ [witnessbox]
67
+ ebt_ref = "main"
68
+ # ebt_repo указывать не нужно, если ebt/ живёт в том же репозитории (по умолчанию --repo);
69
+ # если указан — только URL или абсолютный путь (L27)
70
+ ```
71
+
72
+ **Правила доверия (fail-closed):**
73
+ - `.acceptbox.toml` читается строго из объектов Git базового коммита `base` (в `calibrate` — только при переданном `--base`), а не из рабочего дерева или веток `repro`/`head`;
74
+ - `.acceptbox.toml` автоматически защищается от изменений, удаления и переименования в `base..repro` и `base..head` (как `--protect`);
75
+ - **граница доверия `--base` (L26):** конфигу можно доверять ровно настолько, насколько можно доверять `--base`. AcceptBox не проверяет принадлежность `--base` основной ветке — `--base` должна задавать принимающая сторона (человек, CI или внешний оркестратор, например через `git merge-base main HEAD`), а не проверяемый агент;
76
+ - все присутствующие секции валидируются строго: неизвестные ключи, пер-задачные поля (`inv`, `ebt_sha`, `approved_tree`, `base`, `repro`, `head`, `repo`, `out`), относительный локальный путь `[witnessbox].ebt_repo`, симлинки и ошибки TOML завершаются с `ERROR` (`config-invalid`, код `2`); блок `inputs.config` такого отчёта содержит `commit` и `sha256` отклонённого файла;
77
+ - `env` допускает обычные переменные (включая `GIT_SSH_COMMAND` или `GIT_AUTHOR_NAME`), но запрещает `BASE`, любые `EBT_*` и переменные git-изоляции из `git rev-parse --local-env-vars`;
78
+ - `protect` из конфига и CLI суммируются (CLI не может ослабить защиту из `base`), `env` сливается с приоритетом CLI по ключу (`--env KEY` без значения при отсутствии `KEY` в окружении снимает значение из конфига), остальные параметры переопределяются явными флагами CLI.
79
+
80
+ ## Фиксация дерева проверок (`pin`)
81
+
82
+ ```sh
83
+ acceptbox pin --ebt-repo /path/to/project --ebt-sha "$(git -C /path/to/project rev-parse HEAD)"
84
+ ```
85
+
86
+ Читает дерево `ebt/` напрямую из объектов Git (без незакоммиченных правок) и печатает 64-символьный SHA-256. Флаг `--ebt-repo` в `pin` обязателен.
87
+
88
+ ## Приёмка коммитов (`accept`)
89
+
90
+ Эргономичные значения по умолчанию (L22):
91
+ - `--mode` по умолчанию берётся из `.acceptbox.toml` или равен `command`;
92
+ - `--repo` по умолчанию `.`;
93
+ - `--head` по умолчанию `HEAD` из `--repo`; резолв в полный SHA выполняется сразу после проверки `git`, его сбой даёт `gate-error` с отчётом (явно переданный `--head` по-прежнему принимается только как полный 40/64-hex SHA). **Важно:** незакоммиченные правки рабочего дерева не проверяются, а если `--repo` указан как URL, через `git ls-remote` берётся удалённый `HEAD` (обычно ветка по умолчанию, а не ветка с фиксом — для URL передавайте `--head` явно);
94
+ - `--ebt-repo` в `witnessbox` по умолчанию берётся из `.acceptbox.toml` или равен `--repo`. Если это локальный checkout, проверка «`--ebt-sha` — предок `--ebt-ref`» идёт по локальной ветке, которую может сдвинуть любой, кто пишет в этот checkout: опорой доверия остаётся только `--approved-tree`. Для полной проверки L10 передайте в `--ebt-repo` URL основного репозитория (L27);
95
+ - `--out` по умолчанию атомарно создаётся как новый пустой каталог в системном `TMPDIR`, а путь к `accept.json` выводится в итоговое сообщение.
96
+
97
+ ### Режим `command`
98
+
99
+ Минимальный запуск (при наличии `.acceptbox.toml` в `base`, из корня репозитория):
100
+
101
+ ```sh
102
+ acceptbox accept --base "$(git merge-base main HEAD)" --repro <40-hex-sha>
103
+ ```
104
+
105
+ Полный запуск с явными флагами (без `.acceptbox.toml`):
106
+
107
+ ```sh
108
+ acceptbox accept \
109
+ --mode command \
110
+ --repo /path/to/project \
111
+ --base <40-hex-sha> \
112
+ --repro <40-hex-sha> \
113
+ --head <40-hex-sha> \
114
+ --tests tests/ \
115
+ [--protect path/to/protect ...] \
116
+ [--timeout 600] \
117
+ [--env KEY[=VAL] ...] \
118
+ [--out /tmp/accept-run] \
119
+ -- python3 -m unittest discover -s tests
120
+ ```
121
+
122
+ Команда после `--` (или `[command].argv` в `.acceptbox.toml`) запускается без shell (`shell=False`) с очищенным окружением. Автоопределение тестовой команды не выполняется. Код `0` трактуется как `green`, код `1` — как `red`, любой другой код (`>= 2`), сигнал или таймаут — как `gate-error` (код `2`).
123
+
124
+ ### Режим `witnessbox`
125
+
126
+ ```sh
127
+ acceptbox accept \
128
+ --mode witnessbox \
129
+ --base <40-hex-sha> \
130
+ --repro <40-hex-sha> \
131
+ --inv INV-1,INV-2 \
132
+ --ebt-ref main \
133
+ --ebt-sha <40-hex-sha> \
134
+ --approved-tree <64-hex-sha256> \
135
+ [--repo /path/to/project] \
136
+ [--head <40-hex-sha>] \
137
+ [--ebt-repo /path/to/ebt-repo] \
138
+ [--protect path/to/protect ...] \
139
+ [--timeout 600] \
140
+ [--env KEY[=VAL] ...] \
141
+ [--out /tmp/accept-ebt-run]
142
+ ```
143
+
144
+ ## Калибровка чувствительности (`calibrate`)
145
+
146
+ Режим `command`:
147
+
148
+ ```sh
149
+ acceptbox calibrate \
150
+ --green <sha> \
151
+ --red <sha> \
152
+ [--repo /path/to/project] \
153
+ [--base <base_sha>] \
154
+ [--timeout 600] \
155
+ [--env KEY[=VAL] ...] \
156
+ [--out /tmp/calibrate-run] \
157
+ -- python3 -m unittest discover -s tests
158
+ ```
159
+
160
+ Режим `witnessbox`:
161
+
162
+ ```sh
163
+ acceptbox calibrate \
164
+ --mode witnessbox \
165
+ --green <sha> \
166
+ --red <sha> \
167
+ --inv INV-1 \
168
+ --ebt-ref main \
169
+ --ebt-sha <40-hex-sha> \
170
+ --approved-tree <64-hex-sha256> \
171
+ [--repo /path/to/project] \
172
+ [--ebt-repo /path/to/ebt-repo] \
173
+ [--base <base_sha>] \
174
+ [--timeout 600] \
175
+ [--env KEY[=VAL] ...] \
176
+ [--out /tmp/calibrate-ebt-run]
177
+ ```
178
+
179
+ Калибровка проверяет набор `--green` / `--red` коммитов и записывает `<out>/calibrate.json` (`accept.json` не создаётся). Проверки `ancestry`, `--protect` и диффа `base..repro` / `repro..head` в калибровке **не применяются**. Если передан `--base`, настройки могут подгружаться из `.acceptbox.toml` этого коммита (и в `witnessbox` передаётся `BASE`).
180
+
181
+ ## Коды выхода и отчёты
182
+
183
+ - `0` — `ACCEPTED` (для `accept`) / `CALIBRATED` (для `calibrate`);
184
+ - `1` — `REJECTED` / `FAILED` (отказ по правилам приёмки или калибровки);
185
+ - `2` — `ERROR` (ошибка аргументов CLI, непустой `--out`, некорректный `.acceptbox.toml` `config-invalid`, сбой `git`, отсутствующий/несовместимый `witnessbox`, нарушение схемы отчёта, ошибка прогона `gate-error`).
186
+
187
+ **Правило записи отчёта при коде `2` (L26):**
188
+ - `accept.json` / `calibrate.json` **не создаётся** при ошибках синтаксиса CLI, при `out-not-empty`, а также при нехватке обязательных аргументов (`--tests`, команды после `--`, `--inv`, `--ebt-ref`, `--ebt-sha`, `--approved-tree`) или смешивании флагов режимов, обнаруженных после чтения `base:.acceptbox.toml`; если пустой каталог `--out` был создан текущим запуском, он удаляется;
189
+ - во всех остальных случаях кода `2` после захвата `--out` (включая `config-invalid`, `witnessbox-missing`, `witnessbox-incompatible`, `gate-error`) отчёт записывается атомарно, а путь к нему печатается в `stderr`.
190
+
191
+ Подробнее о подключении проекта см. [docs/onboarding.md](docs/onboarding.md) и журнал решений [docs/decisions.md](docs/decisions.md).
192
+
193
+ ## Разработка и сборка
194
+
195
+ ```sh
196
+ python3 -m unittest discover -s tests
197
+ uv build
198
+ ```
@@ -0,0 +1,15 @@
1
+ acceptbox/__init__.py,sha256=kPUr2FhlRdUuBom7Ufd6iMMDiK9zpijKOi8fTjM1Jcw,367
2
+ acceptbox/cli.py,sha256=XA6Co0vWij9CgWy1RKLdNztFwgoRZcdRrJ2U0beFTZA,55448
3
+ acceptbox/command.py,sha256=jFFYWkGSj5KwVGijx1dUCGfyDeSOC8jVkfhLwgM_rGg,4344
4
+ acceptbox/config.py,sha256=xnUVHWRjMigJnmELheDG7ol4P5QWynwwu55yYUAanF4,11005
5
+ acceptbox/git.py,sha256=ikBoPnWSqqPLRZ3rG88xCP8CrVMSq3DxO66EiQrnYgw,12244
6
+ acceptbox/inputs.py,sha256=xNQ1qo6koPOoriQNU8Yt47BKmVmrIV_gaqxyi85LIW4,8843
7
+ acceptbox/pin.py,sha256=nJa79YTEyVltBXybENZLwshIPePrJFe7FM4ZqYtPxHo,3547
8
+ acceptbox/report.py,sha256=rlyPQBvyysdPZ2wEBTbB3AXut49XxAjpgb-Y2pyf4ig,4673
9
+ acceptbox/verdict.py,sha256=onQ9Q0-3tR4PK2vpDR5MrNYOEa_-crXynvCOE0X2wY8,7221
10
+ acceptbox/witnessbox.py,sha256=rQv5_bpupn5-rJ_DQlatxcIeQCn86yjpnI3GlpJcI28,14222
11
+ acceptbox-0.1.0.dist-info/METADATA,sha256=ItoVwCSE7wotr6UpivUEiX7159J4EaK7X5jCczP4jd0,13950
12
+ acceptbox-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ acceptbox-0.1.0.dist-info/entry_points.txt,sha256=vG27dZw4ZUQipHbYimOWjl7_aYqJaNwzBqsbyze63dE,49
14
+ acceptbox-0.1.0.dist-info/licenses/LICENSE,sha256=KeS3KKE86P7AQjiKxjgKNSe796fkWNz0mPdSkH26pIE,1062
15
+ acceptbox-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ acceptbox = acceptbox.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kaufd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.