Files
themiz/scripts/koiz_repair.py
T

402 lines
20 KiB
Python

#!/usr/bin/env python3
"""Bounded, resumable repair coordination for the native Koiz bridge."""
from __future__ import annotations
import argparse
import fcntl
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
ALLOWED = re.compile(r"^(?:scripts/.+|tests/.+|docs/.+|AGENTS\.md)$")
# Статусы gate, при которых работа по делу идет. stale значит только «код
# изменился после квитанции» — так бывает после любой посадки. Протухшая
# квитанция трижды заперла запись во все дела (21.09, 29.09, 02.10.2026):
# клиентский договор ушел мимо конвейера. Это долг обслуживания, его чинит
# автопилот. Живой ремонт (pending) и поврежденное состояние (degraded) стопорят.
CASE_WORK_OK = frozenset({"ready", "uninitialized", "stale"})
def _root(data_root):
return Path(data_root).resolve() / "cases/_logs/session-audits/cois/repairs"
def _key(value):
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9._:-]{1,160}", value):
raise ValueError("technical_key must be a short stable identifier")
return value
def _files(code_root, files):
root = Path(code_root).resolve()
result = []
for raw in files:
rel = Path(raw).as_posix()
if Path(rel).is_absolute() or ".." in Path(rel).parts or not ALLOWED.fullmatch(rel):
raise ValueError("affected file outside scripts/tests/docs/AGENTS.md")
path = (root / rel).resolve()
if (root not in path.parents or not ALLOWED.fullmatch(path.relative_to(root).as_posix())):
raise ValueError("affected file escapes code-root")
if path.exists() and not path.is_file():
raise ValueError(f"affected file missing: {rel}")
result.append(rel)
if not result:
raise ValueError("affected files required")
return sorted(set(result))
def _sha(path):
h = hashlib.sha256()
try:
with open(path, "rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
h.update(block)
except FileNotFoundError:
return None
return h.hexdigest()
def _manifest(code_root, files):
root = Path(code_root).resolve()
return {rel: _sha(root / rel) for rel in files}
def _read(path, default=None):
try:
return json.loads(Path(path).read_text(encoding="utf-8"))
except FileNotFoundError:
return default
def _write(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
try:
with os.fdopen(fd, "w", encoding="utf-8") as stream:
json.dump(value, stream, ensure_ascii=False, indent=2, sort_keys=True)
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
os.unlink(tmp)
@contextmanager
def _locked(data_root):
directory = _root(data_root)
directory.mkdir(parents=True, exist_ok=True)
with open(directory / ".lock", "a+") as stream:
try:
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
raise RuntimeError("repair state busy") from exc
try:
yield directory
finally:
fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
def _journal(directory, event):
with open(directory / "journal.jsonl", "a", encoding="utf-8") as stream:
stream.write(json.dumps({"at": datetime.now(timezone.utc).isoformat(), **event},
ensure_ascii=False, sort_keys=True) + "\n")
stream.flush()
os.fsync(stream.fileno())
def _report_path(directory, key):
return directory / "reports" / (hashlib.sha256(key.encode()).hexdigest() + ".json")
def claim(data_root, technical_key, owner_session, files, code_root):
"""Create or resume one persistent claim. Interrupted claims stay pending."""
key = _key(technical_key)
if not isinstance(owner_session, str) or not re.fullmatch(r"[A-Za-z0-9._:-]{1,120}", owner_session):
raise ValueError("owner_session must be a short stable identifier")
rels = _files(code_root, files)
before = _manifest(code_root, rels)
with _locked(data_root) as directory:
active_path = directory / "active.json"
active = _read(active_path)
if active and active.get("status") == "ready":
active = None
# Освобожденный claim передан следующему координатору: он не держит ни дом,
# ни чужой ключ. Иначе мертвая запись 20.09.2026 закрывала дом навсегда —
# снять ее можно было только тем же ключом, которого у новой сессии нет.
if active and active.get("released") and active.get("technical_key") != key:
active = None
if active and active.get("technical_key") != key:
raise RuntimeError("another repair claim is active")
report_path = _report_path(directory, key)
report = _read(report_path)
if report and report.get("status") == "ready":
if not _valid_receipt(report):
raise RuntimeError("completed repair receipt is corrupt")
if _manifest(code_root, report.get("manifest", {})) != report.get("manifest", {}):
raise RuntimeError("completed repair is stale in this code-root")
return report
if active:
if active.get("owner_session") != owner_session and not active.get("released"):
raise PermissionError("claim belongs to another session")
if not set(active.get("files", [])).issubset(rels) or active.get("code_root") != str(Path(code_root).resolve()):
raise RuntimeError("affected files or code-root changed")
added = {p: before[p] for p in rels if p not in active["files"]}
active = {**active, "owner_session": owner_session, "released": False,
"files": rels, "before": {**active["before"], **added}}
_write(active_path, active)
_journal(directory, {"event": "resume", "technical_key": key, "owner_session": owner_session})
return {**active, "status": "pending", "resumed": True}
active = {"technical_key": key, "owner_session": owner_session,
"code_root": str(Path(code_root).resolve()), "files": rels,
"before": before, "status": "pending"}
_write(active_path, active)
_write(report_path, active)
_journal(directory, {"event": "claim", **active})
return active
def _test_files(root, tests):
if not isinstance(tests, list) or not tests or any(not isinstance(x, str) for x in tests):
raise ValueError("tests must be relative pytest files")
paths = _files(root, tests)
if any(not x.startswith("tests/") or not x.endswith(".py") or not (root / x).is_file() for x in paths):
raise ValueError("tests must be existing tests/*.py files")
return paths
def _diagnostic(exc):
# Do not persist command output, paths, packet text, or arbitrary exception text.
return {"type": type(exc).__name__, "message": "repair operation failed"}
def _publish(directory, report):
ready = _read(directory / "ready.json", {}) or {}
manifest = dict(ready.get("manifest", {}))
manifest.update(report["manifest"])
_write(directory / "ready.json", {**report, "manifest": manifest})
_write(directory / "active.json", {"status": "ready", "technical_key": report["technical_key"]})
def _valid_receipt(ready):
"""A matching hash alone is not an executed verification or a Koiz receipt."""
if not isinstance(ready, dict) or ready.get("status") != "ready":
return False
try:
_key(ready["technical_key"])
if datetime.fromisoformat(ready["verified_at"]).tzinfo is None:
return False
if type(ready["collected"]) is not int or ready["collected"] <= 0:
return False
tests, manifest, receipt = ready["tests"], ready["manifest"], ready["koiz"]
if not isinstance(tests, list) or not tests or not isinstance(manifest, dict):
return False
if not all(isinstance(p, str) and p.startswith("tests/") and p in manifest for p in tests):
return False
if not isinstance(ready["code_root"], str) or not Path(ready["code_root"]).is_absolute():
return False
if not re.fullmatch(r"[0-9a-f]{64}", ready["packet_sha256"]):
return False
if receipt.get("sha256") != ready["packet_sha256"] or not receipt.get("records"):
return False
return all(isinstance(r, dict) and r.get("id") and r.get("pin") == "тест"
and not r.get("closed") and r.get("op") in {"add", "hit", "seen"}
for r in receipt["records"])
except (KeyError, TypeError, ValueError, AttributeError):
return False
def finish(data_root, code_root, technical_key, owner_session, tests, packet,
koiz_root, db=None, timeout=120):
key = _key(technical_key)
with _locked(data_root) as directory:
active = _read(directory / "active.json")
report_path = _report_path(directory, key)
report = _read(report_path)
if report and report.get("status") == "ready":
if not _valid_receipt(report):
raise RuntimeError("completed repair receipt is corrupt")
current = _manifest(code_root, report["manifest"])
if current != report["manifest"]:
raise RuntimeError("completed repair is stale in this code-root")
if active and active.get("status") == "pending" and active.get("technical_key") != key:
raise RuntimeError("another repair claim is active")
_publish(directory, report)
return report
if not active or active.get("technical_key") != key:
raise RuntimeError("repair claim not found")
if active.get("owner_session") != owner_session:
raise PermissionError("claim belongs to another session")
root = Path(code_root).resolve()
if str(root) != active.get("code_root"):
raise RuntimeError("code-root differs from claim")
try:
tests = _test_files(root, tests)
if not set(tests).issubset(active["files"]):
raise RuntimeError("executed tests must be in the claimed file manifest")
packet_path = Path(packet).resolve()
packet_sha = _sha(packet_path)
payload = _read(packet_path)
if not isinstance(payload, dict) or not payload.get("lessons"):
raise ValueError("invalid technical lesson packet")
refs = {item.get("pin_ref") for item in payload["lessons"]}
if not refs.issubset(set(tests)) or any(item.get("pin") != "тест" for item in payload["lessons"]):
raise RuntimeError("packet pin_ref must name explicitly executed pytest files")
before_tests = _manifest(root, _files(root, active["files"]))
# JUnit is created by the actual pytest invocation, never by an arbitrary
# command that merely prints 'passed'. Raw test output is not persisted.
import xml.etree.ElementTree as ET
with tempfile.TemporaryDirectory(prefix="koiz-verify-") as tmp:
junit = Path(tmp) / "results.xml"
command = [sys.executable, "-m", "pytest", "-q", "--junitxml=" + str(junit), *tests]
proc = subprocess.run(command, cwd=root, text=True, capture_output=True, check=False, timeout=timeout)
if proc.returncode != 0:
raise RuntimeError("pytest failed")
cases = ET.parse(junit).getroot().findall(".//testcase")
passed = [c for c in cases if not any(c.find(t) is not None for t in ("skipped", "failure", "error"))]
if not passed or len(passed) != len(cases):
raise RuntimeError("tests failed, skipped or no tests executed")
collected = len(cases)
after = _manifest(root, _files(root, active["files"]))
if after != before_tests or any(value is None for value in after.values()):
raise RuntimeError("affected file hashes changed during tests")
if _sha(packet_path) != packet_sha:
raise RuntimeError("lesson packet changed during tests")
command = ["node", str(Path(__file__).with_name("koiz_lessons.mjs")), str(packet_path),
"--koiz-root", str(Path(koiz_root).resolve()), "--code-root", str(root)]
if db:
command += ["--db", str(Path(db).resolve())]
imported = subprocess.run(command, cwd=root, text=True, capture_output=True, check=False,
timeout=timeout)
if imported.returncode != 0:
raise RuntimeError("Koiz import failed")
receipt = json.loads(imported.stdout)
if len(receipt.get("records", [])) != len(payload["lessons"]) or receipt.get("sha256") != packet_sha:
raise RuntimeError("Koiz receipt does not match packet")
if any(r.get("closed") or r.get("pin") != "тест" for r in receipt["records"]):
raise RuntimeError("Koiz lesson is not active and pinned")
if _manifest(root, _files(root, active["files"])) != after or _sha(packet_path) != packet_sha:
raise RuntimeError("source or packet changed during Koiz import")
ready = {"status": "ready", "technical_key": key, "owner_session": owner_session,
"verified_at": datetime.now(timezone.utc).isoformat(),
"manifest": after, "tests": tests, "code_root": str(root),
"collected": collected, "packet_sha256": packet_sha, "koiz": receipt}
_write(report_path, ready)
_journal(directory, {"event": "ready", **ready})
_publish(directory, ready)
return ready
except Exception as exc:
diagnostic = _diagnostic(exc)
pending = {**active, "status": "pending", "diagnostic": diagnostic}
_write(report_path, pending)
_journal(directory, {"event": "pending", "technical_key": key, "diagnostic": diagnostic})
raise
def release(data_root, technical_key, owner_session, reason):
try:
from .cois import safe
except ImportError:
from cois import safe
if not isinstance(reason, str) or not reason.strip() or safe(reason) != reason:
raise ValueError("safe release reason required")
key = _key(technical_key)
with _locked(data_root) as directory:
active = _read(directory / "active.json")
if not active or active.get("technical_key") != key:
raise RuntimeError("repair claim not found")
if active.get("status") == "ready":
raise RuntimeError("completed repair cannot be released")
if active.get("owner_session") != owner_session:
raise PermissionError("claim belongs to another session")
pending = {**active, "status": "pending", "released": True, "release_reason": reason}
_write(_report_path(directory, key), pending)
_write(directory / "active.json", pending)
_journal(directory, {"event": "release", "technical_key": key, "reason": reason})
return pending
def gate(data_root, code_root):
"""Read-only: a pending claim fences all consumers of the shared code."""
directory = _root(data_root)
try:
ready = _read(directory / "ready.json")
active = _read(directory / "active.json")
if any(v is not None and not isinstance(v, dict) for v in (ready, active)):
raise ValueError("invalid state")
if active and active.get("status") not in {"pending", "ready"}:
raise ValueError("invalid claim")
# Забор ставит ТОЛЬКО живой ремонт. Освобожденный claim (released) означает,
# что координатор ушел и никто не правит общий код прямо сейчас; держать на
# нем весь дом — это запрет без пути (20.09.2026: запись в дело встала
# намертво, а разгрузка контекста требует ровно этой записи).
if active and active.get("status") == "pending" and not active.get("released"):
return {"status": "pending", "technical_key": active.get("technical_key"),
"owner_session": active.get("owner_session"), "code_root": active.get("code_root"),
"message": "Общий код ремонтируется. Координатор завершает claim/finish; не повторять сбойное действие."}
if ready is None:
return {"status": "uninitialized", "message": "Квитанций общего ремонта еще нет."}
if not _valid_receipt(ready):
raise ValueError("incomplete ready receipt")
manifest = ready.get("manifest")
if ready.get("status") != "ready" or not isinstance(manifest, dict) or not manifest:
raise ValueError("invalid manifest")
_files(code_root, manifest)
if any(not isinstance(v, str) or not re.fullmatch(r"[0-9a-f]{64}", v) for v in manifest.values()):
raise ValueError("invalid digest")
current = _manifest(code_root, manifest)
mismatch = sorted(p for p, sha in manifest.items() if current[p] != sha)
if mismatch:
return {"status": "stale", "mismatch": mismatch, "code_root": ready.get("code_root"),
"message": "Используйте проверенный корень кода или перенесите адресные правки в worktree, сохранив чужие изменения."}
return {"status": "ready", "mismatch": [], "technical_key": ready.get("technical_key"),
"message": "Версия кода соответствует проверенному общему исправлению."}
except (OSError, ValueError, TypeError):
return {"status": "degraded", "message": "Состояние ремонта повреждено или недоступно; восстановить его по журналу."}
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=["claim", "finish", "release", "gate"])
parser.add_argument("--data-root", required=True)
parser.add_argument("--code-root", required=True)
parser.add_argument("--technical-key", required=False)
parser.add_argument("--owner-session", required=False)
parser.add_argument("--file", action="append", default=[])
parser.add_argument("--tests", nargs="+")
parser.add_argument("--packet")
parser.add_argument("--koiz-root")
parser.add_argument("--db")
parser.add_argument("--reason")
args = parser.parse_args(argv)
if args.command == "claim":
result = claim(args.data_root, args.technical_key, args.owner_session, args.file, args.code_root)
elif args.command == "finish":
result = finish(args.data_root, args.code_root, args.technical_key, args.owner_session,
args.tests, args.packet, args.koiz_root, args.db)
elif args.command == "release":
result = release(args.data_root, args.technical_key, args.owner_session, args.reason)
else:
result = gate(args.data_root, args.code_root)
print(json.dumps(result, ensure_ascii=False, sort_keys=True))
if args.command == "gate" and result.get("status") not in {"ready", "uninitialized"}:
raise SystemExit(2)
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(json.dumps({"status": "failed", "error": type(exc).__name__}, ensure_ascii=False), file=sys.stderr)
raise SystemExit(1)