release: Themiz на Gitea

This commit is contained in:
public-repo-gate
2026-10-19 11:10:53 +03:00
parent e52e76d4ea
commit 067c6c2414
225 changed files with 240125 additions and 26157 deletions
+338 -23
View File
@@ -45,6 +45,8 @@ import time
import unicodedata
from pathlib import Path
import cli_registry
# ── Контракт ─────────────────────────────────────────────────────────────────
AGENT_DIR = ".agent"
INTAKE = "00_intake"
@@ -62,9 +64,13 @@ READY_DOCX_NAME = "{document}.docx"
MAX_REVIEW_ROUNDS = 2
REVIEW_STOP_ROUND = MAX_REVIEW_ROUNDS + 1
# Журнал вердиктов Кони. Имя — ОДНО на систему; лежит прямо в drafts, НЕ в _working:
# сторож (claude_guard) освобождает _working/_baselines от гейта протокола, и журнал
# сторож (themiz_guard) освобождает _working/_baselines от гейта протокола, и журнал
# внутри них — слепое пятно (D03, 01.09.2026: дописанная строка открыла сборку .docx).
VERDICTS_NAME = "verdicts.jsonl"
PIPELINE_CONTRACT = Path(__file__).resolve().parent.parent / "config/pipeline_contract.json"
PIPELINE_LEVELS = ("L1", "L2", "L3")
PIPELINE_TRACKS = ("MICRO", "FAST", "FULL")
PIPELINE_STEPS = ("B", "0", "1", "2", "3", "4", "5", "6", "7")
# Что человеку видно в корне дела. Все прочее — кухня.
HUMAN_VISIBLE = ("_case.md", INTAKE, HEARINGS, READY)
@@ -95,19 +101,218 @@ def ready(case):
return _p(case) / READY
def _contract_block(*paths, **values):
def _contract_block(*paths, required=True, **values):
sources = [{"path": _p(path), "exists": _p(path).is_file()} for path in paths]
return {"sources": sources, "exists": all(s["exists"] for s in sources), **values}
present = all(s["exists"] for s in sources)
return {"sources": sources, "exists": present, "required": required,
"ready": present or not required, **values}
def document_contract(case):
def pipeline_contract_errors(data):
"""Проверить граф Б–7 без запуска LLM и без изменения дела."""
errors = []
if not isinstance(data, dict):
return ["корень контракта должен быть объектом"]
if data.get("schema") != 1:
errors.append("schema должен быть равен 1")
levels, tracks = data.get("levels"), data.get("tracks")
steps, blocks = data.get("steps"), data.get("blocks")
if not isinstance(levels, dict) or set(levels) != set(PIPELINE_LEVELS):
errors.append("уровни должны быть ровно L1, L2, L3")
if not isinstance(tracks, dict) or set(tracks) != set(PIPELINE_TRACKS):
errors.append("треки должны быть ровно MICRO, FAST, FULL")
if not isinstance(steps, dict) or tuple(steps) != PIPELINE_STEPS:
errors.append("шаги должны идти Б(B), 0, 1, 2, 3, 4, 5, 6, 7")
if not isinstance(blocks, dict) or not blocks:
errors.append("blocks должен быть непустым объектом")
if errors:
return errors
for level, spec in levels.items():
allowed = spec.get("tracks") if isinstance(spec, dict) else None
if not isinstance(allowed, list) or not allowed or any(t not in tracks for t in allowed):
errors.append(f"{level}: tracks должен быть непустым списком известных треков")
for track, spec in tracks.items():
sources = spec.get("sources") if isinstance(spec, dict) else None
if not isinstance(sources, list) or not sources:
errors.append(f"{track}: нет sources")
continue
if len(sources) != len(set(sources)):
errors.append(f"{track}: sources содержит повтор")
for name in sources:
if name not in blocks:
errors.append(f"{track}: неизвестный source-блок {name}")
fields = ("inputs", "optional_inputs", "outputs")
for step, spec in steps.items():
if not isinstance(spec, dict):
errors.append(f"шаг {step}: описание должно быть объектом")
continue
for field in fields:
by_track = spec.get(field)
if not isinstance(by_track, dict) or set(by_track) != set(PIPELINE_TRACKS):
errors.append(f"шаг {step}: {field} должен описывать три трека")
continue
for track, names in by_track.items():
if not isinstance(names, list) or any(not isinstance(n, str) for n in names):
errors.append(f"шаг {step}/{track}: {field} должен быть списком блоков")
elif any(name not in blocks for name in names):
errors.append(f"шаг {step}/{track}: {field} ссылается на неизвестный блок")
if "instrument" not in spec:
errors.append(
f"шаг {step}: не указан instrument "
"(при отсутствии нужен null + llm/stop)")
instrument = spec.get("instrument")
llm_reason = spec.get("llm")
command = spec.get("command")
command_reason = spec.get("command_reason")
if llm_reason is not None and (
not isinstance(llm_reason, str) or not llm_reason.strip()):
errors.append(f"шаг {step}: llm должен назвать причину")
if command is not None and (
not isinstance(command, str) or not command.startswith("/")
or not isinstance(command_reason, str) or not command_reason.strip()):
errors.append(
f"шаг {step}: command должен назвать /command и command_reason")
elif command is None and command_reason is not None:
errors.append(f"шаг {step}: command_reason задан без command")
command_groups = []
if instrument is None:
stop = spec.get("stop")
if not (isinstance(llm_reason, str) and llm_reason.strip()) \
and not (isinstance(stop, str) and stop.strip()) \
and not (isinstance(command, str) and command.startswith("/")
and isinstance(command_reason, str)
and command_reason.strip()):
errors.append(
f"шаг {step}: переход без прибора обязан назвать llm, stop или command")
elif not isinstance(instrument, dict) or instrument.get("llm") is not False:
errors.append(f"шаг {step}: instrument должен быть прибором без LLM")
else:
if command is not None:
errors.append(f"шаг {step}: instrument и command взаимоисключаются")
commands = instrument.get("commands")
if not isinstance(commands, list) or not commands:
errors.append(f"шаг {step}: instrument.commands должен быть непустым списком")
else:
command_groups.append(("instrument", commands))
preparation = spec.get("preparation", [])
if not isinstance(preparation, list):
errors.append(f"шаг {step}: preparation должен быть списком")
elif preparation:
command_groups.append(("preparation", preparation))
for label, commands in command_groups:
seen_commands = set()
for pos, command in enumerate(commands, 1):
if not isinstance(command, dict):
errors.append(f"шаг {step}: {label} {pos} должен быть объектом")
continue
script = command.get("script")
if not script:
errors.append(f"шаг {step}: {label} {pos} не задает script")
identity = script
if isinstance(identity, str):
if identity in seen_commands:
errors.append(f"шаг {step}: {label} {identity} привязан дважды")
seen_commands.add(identity)
if script and (not isinstance(script, str) or not script.startswith("scripts/")):
errors.append(f"шаг {step}: {label} {pos} имеет недопустимый script")
elif isinstance(script, str):
if label == "instrument" and script == "scripts/sign_and_pdf.py":
errors.append(
f"шаг {step}: {script} автоматизирует Word/AppleScript "
"владельца и не может быть прибором перехода")
script_path = Path(script)
if script_path.is_absolute() or ".." in script_path.parts:
errors.append(f"шаг {step}: {label} {pos} выходит за scripts/")
elif not (Path(__file__).resolve().parent.parent / script_path).is_file():
errors.append(f"шаг {step}: {label} {script} не найден")
if script and (not isinstance(command.get("args", []), list)
or any(not isinstance(arg, str) for arg in command.get("args", []))):
errors.append(f"шаг {step}: {label} {pos} имеет недопустимые args")
if command.get("kind", "provider") not in {"gate", "provider"}:
errors.append(f"шаг {step}: {label} {pos} имеет неизвестный kind")
if command.get("when", "always") not in {
"always", "map-ready", "document-present"}:
errors.append(f"шаг {step}: {label} {pos} имеет неизвестное when")
for name, spec in blocks.items():
if not isinstance(spec, dict):
errors.append(f"блок {name}: описание должно быть объектом")
continue
paths = spec.get("paths", [spec.get("path")])
if not isinstance(paths, list) or not paths or any(not isinstance(p, str) or not p for p in paths):
errors.append(f"блок {name}: нет path/paths")
routes = spec.get("routes")
if not isinstance(routes, dict) or set(routes) != set(PIPELINE_TRACKS):
errors.append(f"блок {name}: routes должен описывать три трека")
continue
optional = spec.get("optional") is True
for track, route in routes.items():
if not isinstance(route, dict):
errors.append(f"блок {name}/{track}: маршрут должен быть объектом")
continue
if route.get("active", True) is False:
continue
producer, consumers = route.get("producer"), route.get("consumers")
if not optional and (not isinstance(producer, str) or not producer):
errors.append(f"блок {name}/{track}: нет производителя")
if not isinstance(consumers, list) or not consumers:
errors.append(f"блок {name}/{track}: нет потребителя")
for step, spec in steps.items():
for track in PIPELINE_TRACKS:
for field in ("inputs", "optional_inputs", "outputs"):
for name in spec.get(field, {}).get(track, []):
block = blocks.get(name, {})
route = block.get("routes", {}).get(track, {})
if route.get("active", True) is False:
errors.append(f"шаг {step}/{track}: неактивный блок {name} в {field}")
continue
if field == "inputs" and not route.get("producer"):
errors.append(f"шаг {step}/{track}: вход {name} без производителя")
if field != "outputs" and step not in route.get("consumers", []):
errors.append(f"шаг {step}/{track}: блок {name} не называет шаг потребителем")
if field == "outputs" and route.get("producer") != step:
errors.append(f"шаг {step}/{track}: блок {name} называет другого производителя")
return errors
def load_pipeline_contract(path=PIPELINE_CONTRACT):
path = _p(path)
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise ValueError(f"{path}: контракт не прочитан: {exc}") from exc
errors = pipeline_contract_errors(data)
if errors:
raise ValueError("\n".join(errors))
return data
def _pipeline_source_paths(case, track, data):
root = Path(__file__).resolve().parent.parent
result = []
for name in data["tracks"][track]["sources"]:
spec = data["blocks"][name]
rels = spec["paths"] if "paths" in spec else [spec["path"]]
paths = [(root if spec.get("root") else case) / rel for rel in rels]
result.append(next((path for path in paths if path.is_file()), paths[0]))
return result
def document_contract(case, track=None, pipeline_path=PIPELINE_CONTRACT):
"""Файлы результата и шесть блоков требований с наличием источников."""
case = _p(case)
root = Path(__file__).resolve().parent.parent
council = context(case) / "_council/council_verdict.md"
legacy_council = context(case) / "_practice/council_verdict.md"
if not council.is_file() and legacy_council.is_file():
council = legacy_council
if track is None:
pipeline = run_read(case).get("pipeline", {})
track = pipeline.get("track") if isinstance(pipeline, dict) else None
track = str(track or "FULL").upper()
data = load_pipeline_contract(pipeline_path)
if track not in data["tracks"]:
raise ValueError(f"неизвестный трек: {track}")
return {
"draft_md": drafts(case) / DRAFT_NAME,
"ready_md": ready(case) / READY_MD_NAME,
@@ -115,8 +320,9 @@ def document_contract(case):
"review_rounds": MAX_REVIEW_ROUNDS,
"blocks": {
"content": _contract_block(brief(case), positions(case)),
"sources": _contract_block(practice(case), council),
"canon": _contract_block(working(case) / "canon_formulirovki.md"),
"sources": _contract_block(*_pipeline_source_paths(case, track, data)),
"canon": _contract_block(
working(case) / "canon_formulirovki.md", required=False),
"form": _contract_block(
root / "scripts/create_docx.py",
root / ".claude/skills/doc-drafter/SKILL.md"),
@@ -374,8 +580,8 @@ def case_lock_release(case, session, pid=None, now=None,
# ── Машинное состояние прогона (M01) ──────────────────────────────────────────
# ЕДИНСТВЕННЫЙ адрес файла прогона. Сторож (claude_guard) читает его, проводник
# (themiz-pipeline) и владелец пишут через CLI ниже — второго адреса не заводить.
# ЕДИНСТВЕННЫЙ адрес файла прогона. Сторож (themiz_guard) читает его, проводник
# (themiz-next/run.py) и владелец пишут через CLI ниже — второго адреса не заводить.
# Лежит в .agent/context/: сторож освобождает эту папку от гейта протокола (кроме
# практики/позиции), человеку кухня не видна. Ключи: guide (проводник запущен),
# preflight_code (последний код preflight_search), preflight_override (решение
@@ -470,14 +676,11 @@ CONTRACT_DOCS = (
".claude/commands/draft.md",
".claude/commands/finalize.md",
".claude/commands/new-case.md",
".claude/agents/doc-drafter.md",
".claude/agents/doc-reviewer.md",
".claude/skills/doc-drafter/SKILL.md",
".claude/skills/themiz-setup/SKILL.md",
)
REVIEW_CONTRACT_DOCS = (
".claude/commands/draft.md",
".claude/agents/doc-reviewer.md",
".claude/skills/doc-drafter/SKILL.md",
)
ROUND_WORDS = {
@@ -520,20 +723,77 @@ HOME_AFTER_CLAIM_RE = re.compile(
r"`?[^`\s,;)]+/",
re.IGNORECASE,
)
EXECUTOR_CLAIM_VERB_RE = (
r"(?:исполн(?:яет|яют|ит|ят)|выполн(?:яет|яют|ит|ят)|"
r"планир(?:ует|уют)|принима(?:ет|ют)|executes?)"
)
EXECUTOR_CLAIM_TOPIC_RE = r"(?:шаг\w*|рол\w*|задач\w*|steps?|roles?|tasks?)"
def executor_registry(root):
"""Имена и модели из двух канонических реестров."""
try:
return cli_registry.executor_data(Path(root))
except (OSError, ValueError, json.JSONDecodeError):
return {"cli_names": (), "model_names": (), "role_models": {},
"historical_models": (), "historical_models_by_alias": {}}
def _executor_names(root):
registry = executor_registry(root)
return tuple(dict.fromkeys(registry["model_names"] + registry["cli_names"]))
def _name_pattern(names, version_suffix=False):
patterns = []
for name in names:
tokens = re.findall(r"[A-Za-zА-Яа-я0-9]+", name)
if not tokens:
continue
pattern = r"[\s._/-]+".join(map(re.escape, tokens))
if version_suffix and any(token.isdigit() for token in tokens):
pattern += r"(?:[\s._/-]+[A-Za-z0-9]+)*"
patterns.append(pattern)
return "|".join(sorted(patterns, key=len, reverse=True)) or r"(?!)"
def _executor_claim_errors(path, text, registry):
"""Конкретный CLI/модель не объявляется исполнителем шага."""
model = rf"(?<![\w])(?:{_name_pattern(registry['model_names'], True)})(?![\w])"
cli = rf"(?<![\w./-])(?:{_name_pattern(registry['cli_names'])})(?![\w./-])"
claim = re.compile(
rf"(?:\b{EXECUTOR_CLAIM_TOPIC_RE}\b[^\n]{{0,60}}\b{EXECUTOR_CLAIM_VERB_RE}\b[^\n]{{0,60}}{cli}|"
rf"{cli}[^\n]{{0,60}}\b{EXECUTOR_CLAIM_VERB_RE}\b[^\n]{{0,60}}\b{EXECUTOR_CLAIM_TOPIC_RE}\b|"
rf"\b(?:исполнитель|executor)\b\s*[:=][^\n]{{0,60}}{cli})",
re.IGNORECASE,
)
return [f"{path}:{number}: исполнитель шага должен называться LLM"
for number, line in enumerate(text.splitlines(), 1)
if re.search(model, line, re.IGNORECASE) or claim.search(line)]
def _instruction_files(root):
"""Живые инструкции; исторические разборы и очередь намеренно не входят."""
root = Path(root)
files = {root / "AGENTS.md", root / "CLAUDE.md", root / ".claude/CLAUDE.md"}
# `.agents/` и `.codex/` — механическое производное `sync_prompts.py`;
# здесь проверяется канон, а побайтовый дрейф производного держит его --check.
for pattern in (".claude/commands/*.md", ".claude/agents/*.md",
".claude/skills/*/*.md"):
files.update(root.glob(pattern))
return sorted(p for p in files if p.is_file())
def _without_reviewer_remarks(text):
"""Машинный блок тикета цитирует враждебные строки, но не инструктирует."""
out, skip = [], False
for line in text.splitlines():
if "<!-- remont-zamechaniya -->" in line:
skip = True
out.append("" if skip else line)
if "<!-- /remont-zamechaniya -->" in line:
skip = False
return "\n".join(out)
def _contract_text_errors(path, text):
errors = []
for number, line in enumerate(text.splitlines(), 1):
@@ -563,9 +823,24 @@ def instruction_contract_errors(root):
text = path.read_text(encoding="utf-8")
if "case_paths.py" not in text:
errors.append(f"{rel}: нет ссылки на scripts/case_paths.py")
for path in _instruction_files(root):
errors.extend(_contract_text_errors(path.relative_to(root),
path.read_text(encoding="utf-8")))
registry = executor_registry(root)
instruction_files = _instruction_files(root)
for path in instruction_files:
rel = path.relative_to(root)
text = path.read_text(encoding="utf-8")
errors.extend(_contract_text_errors(rel, text))
executor_files = {root / "AGENTS.md", root / "CLAUDE.md",
root / ".claude/CLAUDE.md"}
for path in sorted(path for path in executor_files if path.is_file()):
rel = path.relative_to(root)
text = path.read_text(encoding="utf-8")
errors.extend(_executor_claim_errors(rel, _without_reviewer_remarks(text), registry))
for path in sorted((root / "scripts").rglob("*")):
if (not path.is_file() or path.name == "cli_registry.json"
or path.suffix not in {".py", ".sh", ".js", ".mjs"}):
continue
errors.extend(_executor_claim_errors(
path.relative_to(root), path.read_text(encoding="utf-8", errors="replace"), registry))
for rel in REVIEW_CONTRACT_DOCS:
path = root / rel
if not path.is_file():
@@ -606,6 +881,8 @@ def selftest():
assert blocks["form"]["exists"] and blocks["admission"]["exists"] \
and blocks["home"]["exists"], "системный источник контракта не найден"
assert not blocks["canon"]["exists"], "несуществующий источник объявлен существующим"
assert not blocks["canon"]["required"] and blocks["canon"]["ready"], \
"необязательный canon заблокировал контракт"
assert blocks["canon"]["sources"][0] == {
"path": Path("cases/x/y/.agent/context/_working/canon_formulirovki.md"),
"exists": False,
@@ -631,6 +908,26 @@ def selftest():
hostile = _contract_text_errors(
"hostile.md", "Готовый документ в tmp/out, см. scripts/case_paths.py")
assert hostile, "ссылка на case_paths.py замаскировала чужой дом"
executor_registry_data = executor_registry(root)
provider = executor_registry_data["cli_names"][0]
hostile_lines = tuple(
f'MODEL = "{name}"' for name in executor_registry_data["model_names"]
) + (
f'# {executor_registry_data["historical_models_by_alias"]["fable"].replace("-", " ")}.1',
f'# {provider.title()} исполняет шаг',
f'шаг исполняет {provider}',
)
assert all(_executor_claim_errors("hostile.py", line, executor_registry_data)
for line in hostile_lines), \
"таблица возврата имени исполнителя прошла линт"
assert not _executor_claim_errors(
"clean.py", "шаг исполняет LLM по реестру", executor_registry_data), \
"LLM ошибочно принят за конкретного исполнителя"
instruction_paths = {path.relative_to(root).as_posix()
for path in _instruction_files(root)}
assert {".claude/commands/draft.md", ".claude/agents/archivist.md",
".claude/skills/doc-drafter/SKILL.md"} <= instruction_paths, \
"линт не обходит команды, канон агентов и навыки"
round_match = ROUND_LIMIT_RE.search("До 5 раундов")
assert round_match
raw_rounds = (round_match.group("leading") or round_match.group("trailing")).lower()
@@ -700,10 +997,10 @@ def selftest():
# Файл прогона (M01): один адрес в .agent/context, аддитивная запись
assert run_state(case) == case / ".agent/context/run.json"
assert run_read(case) == {}, "пустое состояние не пусто"
run_write(case, guide="themiz-pipeline")
run_write(case, guide="run")
run_write(case, preflight_code=0)
st = run_read(case)
assert st == {"guide": "themiz-pipeline", "preflight_code": 0}, \
assert st == {"guide": "run", "preflight_code": 0}, \
f"аддитивная запись прогона сломана: {st}"
# REQ-10: лок меняет только .lock; живой владелец назван, старый/мертвый снят.
@@ -765,6 +1062,11 @@ def main():
ap.add_argument("--show", metavar="CASE", help="показать пути конкретного дела")
ap.add_argument("--document-contract", nargs="?", const="cases/{client}/{case}",
metavar="CASE", help="показать дом, имена файлов и лимит рецензии")
ap.add_argument("--track", choices=PIPELINE_TRACKS,
help="трек для document-contract (по умолчанию из run.json, затем FULL)")
ap.add_argument("--validate-pipeline-contract", nargs="?",
const=str(PIPELINE_CONTRACT), metavar="JSON",
help="проверить исполняемый контракт Б–7")
ap.add_argument("--run-get", nargs="+", metavar=("CASE", "KEY"),
help="прочитать файл прогона (CASE [KEY])")
ap.add_argument("--run-set", nargs=3, metavar=("CASE", "KEY", "VALUE"),
@@ -773,8 +1075,21 @@ def main():
a = ap.parse_args()
if a.selftest:
return selftest()
if a.validate_pipeline_contract is not None:
try:
load_pipeline_contract(a.validate_pipeline_contract)
except ValueError as exc:
print(f"контракт конвейера: ОШИБКА\n{exc}", file=sys.stderr)
return 1
print("контракт конвейера: ок")
return 0
if a.document_contract is not None:
for key, value in document_contract(a.document_contract).items():
try:
contract = document_contract(a.document_contract, a.track)
except ValueError as exc:
print(f"document-contract: ОШИБКА\n{exc}", file=sys.stderr)
return 1
for key, value in contract.items():
if key == "blocks":
value = json.dumps(value, ensure_ascii=False, default=str,
separators=(",", ":"))