[A-12] Умные секретари: все сервисы, память сбоев, дубли, класс B, рабочий секретарь

This commit is contained in:
buryan-agent committed 2026-10-21 18:56:29 +03:00
1 parent df97829daa
commit 4a0c4a87a3
7 files changed
+503 -215

No files matched your search

+4
View File
@@ -34,6 +34,10 @@
| A-09 | Уведомления: приоритеты и бэкапы | ✅ | раннер: свежесть vzdump >26 ч → алерт; тихие часы |
| A-10 | Быт в группах роя | ✅ | home: Grocy, Vikunja, Homebox |
| A-11 | Голова: сводка роя | ✅ | `chief.py` 11:50 → очередь дайджеста |
| A-12 | Все 113 сервисов + память сбоев | ✅ | раннер видит реестр целиком, `memory.json` |
| A-13 | Класс B (гигиена) в сухом прогоне | ✅ | 04:40, лимиты, журнал |
| A-14 | Рабочий секретарь | ✅ | `work_agent.py`: репозиторий, клиенты, встречи |
| A-15 | Поиск дублей | ✅ | найдены двойные n8n и freshrss |
## S. Сервисы и структура
+53
View File
@@ -0,0 +1,53 @@
# Умные секретари
## Что изменилось
| Было | Стало |
|---|---|
| 37 сервисов по списку в YAML | **все 113 контейнеров из реестра** |
| нет памяти | `memory.json`: сбои, причины, время |
| нет поиска дублей | ищет двойные экземпляры (хост + CT) |
| нет гигиены | класс B: логи, образы, /tmp (сухой прогон) |
| нет рабочего секретаря | `work_agent.py`: репозиторий, клиенты, встречи |
## Память
`/var/lib/hub-agents/memory.json`:
```json
{"services": {"n8n": {"fails": 3, "first_fail": "...", "reasons": ["timeout"]}}}
```
Мозг получает эту историю в промпте: если сервис падал трижды по одной причине,
он видит это и предлагает лечение, а не «перезапустить ещё раз».
## Дубли
Проверка находит **двойные экземпляры**: один и тот же образ на хосте и в CT.
Сейчас найдено: `n8n` и `freshrss` — оба запущены дважды.
Что с этим делать: определить, какой экземпляр рабочий, второй остановить.
Это класс C — нужно подтверждение.
## Класс B (максимальный безопасный)
Сухой прогон включён. Что делает:
- `docker image prune --filter until=168h` — только висячие образы
- `journalctl --vacuum-time=14d` — при диске > 80%
- удаление `.gz` логов старше 30 дней при `/var/log` > 500 МБ
- чистка `/tmp` старше 7 дней
Лимиты: 4 в час, 12 в день. Журнал: `*-actions.jsonl`.
## Рабочий секретарь
Проверяет: доступность `buryan-work`, число клиентов и встреч, наличие
транскрипции, незакоммиченные изменения. Отчёт в 11:50 попадает в сводку
Головы и в дайджест.
## Следующий шаг к автономии
1. Накопить 2 недели наблюдений.
2. Убедиться, что дублей и ложных тревог нет.
3. Разрешить класс A (рестарт) — и только потом B без сухого прогона.
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Класс B: безопасная гигиена. Сухой прогон до явного включения.
Действия: ротация логов, prune dangling-образов, vacuum журнала, чистка /tmp,
удаление пустых папок медиа. Никогда: рестарт, обновление, удаление данных.
"""
import json
import os
import shutil
import subprocess
import time
from datetime import datetime
POLICY = "/opt/hub-agents/policy.yaml"
JOURNAL = "/var/lib/hub-agents/journal"
STATE = "/var/lib/hub-agents/actions.json"
DRY_RUN = os.environ.get("HUB_ACTIONS_DRY_RUN", "1") == "1"
LIMIT_HOUR, LIMIT_DAY = 4, 12
DISK_THRESHOLD = 80
LOG_THRESHOLD_MB = 500
def sh(cmd, timeout=180):
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
return r.returncode, (r.stdout or "").strip(), (r.stderr or "").strip()
def load_state():
try:
return json.load(open(STATE, encoding="utf-8"))
except Exception:
return {"actions": []}
def save_state(st):
os.makedirs(os.path.dirname(STATE), exist_ok=True)
json.dump(st, open(STATE, "w"), ensure_ascii=False, indent=1)
def within_limits(st):
now = time.time()
hour = [a for a in st["actions"] if now - a.get("epoch", 0) < 3600]
day = [a for a in st["actions"] if now - a.get("epoch", 0) < 86400]
return len(hour) < LIMIT_HOUR and len(day) < LIMIT_DAY
def log_action(st, action, detail, result):
st["actions"] = (st.get("actions") or [])[-200:]
st["actions"].append({"action": action, "detail": detail, "result": result,
"dry_run": DRY_RUN, "epoch": time.time(),
"ts": datetime.now().isoformat(timespec="seconds")})
save_state(st)
os.makedirs(JOURNAL, exist_ok=True)
path = os.path.join(JOURNAL, datetime.now().strftime("%Y-%m-%d") + "-actions.jsonl")
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps({"action": action, "detail": detail, "result": result,
"dry_run": DRY_RUN,
"ts": datetime.now().isoformat(timespec="seconds")},
ensure_ascii=False) + "\n")
def disk_pct(path="/"):
st = os.statvfs(path)
return round((1 - st.f_bavail / st.f_blocks) * 100, 1)
def logs_size_mb():
rc, out, _ = sh("du -sm /var/log 2>/dev/null | cut -f1")
try:
return int(out or 0)
except Exception:
return 0
def candidates():
"""Что можно почистить прямо сейчас."""
out = []
if disk_pct() >= DISK_THRESHOLD:
out.append(("journal_vacuum", "диск заполнен", "journalctl --vacuum-time=14d"))
if logs_size_mb() >= LOG_THRESHOLD_MB:
out.append(("rotate_logs", f"/var/log = {logs_size_mb()} МБ",
"find /var/log -name '*.gz' -mtime +30 -delete"))
rc, out_df, _ = sh("docker system df --format '{{.Type}} {{.Reclaimable}}'")
if "Images" in out_df:
out.append(("prune_dangling", "висячие образы", "docker image prune -f --filter until=168h"))
out.append(("clean_tmp", "временные файлы старше 7 дней",
"find /tmp -type f -mtime +7 -delete"))
return out
def main():
st = load_state()
os.makedirs("/var/lib/hub-agents", exist_ok=True)
results = []
for action, why, cmd in candidates():
if not within_limits(st):
results.append((action, "лимит исчерпан", "skipped"))
continue
if DRY_RUN:
results.append((action, why, f"dry-run: {cmd}"))
log_action(st, action, why, "dry-run")
continue
rc, out, err = sh(cmd)
results.append((action, why, f"rc={rc}"))
log_action(st, action, why, f"rc={rc} {err[:80]}")
print(f"класс B | сухой прогон: {'да' if DRY_RUN else 'НЕТ'}")
print(f"диск: {disk_pct()}% | /var/log: {logs_size_mb()} МБ")
for a, why, res in results:
print(f" • {a}: {why} → {res}")
if __name__ == "__main__":
main()
+33 -1
View File
@@ -14,6 +14,7 @@ from datetime import datetime
sys.path.insert(0, "/opt/hub-agents")
import agent_runner as runner # noqa: E402
import approvals # noqa: E402
API = "https://api.deepseek.com/v1/chat/completions"
KEY_FILE = "/root/.deepseek-key"
@@ -83,15 +84,33 @@ def agent_system(tz):
"\"actions\": [{\"class\":\"A|B|C\",\"action\":\"restart_container|cleanup_logs|"
"update_container|reindex|notify|noop\",\"target\":\"имя\",\"why\":\"причина\"}], "
"\"summary\": одно предложение для человека}. "
"Если всё в порядке — actions: [] и severity: ok. Не предлагай запрещённое."
"Если всё в порядке — actions: [] и severity: ok. Не предлагай запрещённое. "
"ВАЖНО: restart_container, update_container и любое действие, после которого сервис "
"может стать недоступен, — это класс C (требует подтверждения владельца)."
"Класс A — только чтение и проверки. Класс B — гигиена без влияния на доступность."
)
def memory_hint():
"""Краткая история сбоев из памяти роя."""
try:
m = json.load(open("/var/lib/hub-agents/memory.json", encoding="utf-8"))
except Exception:
return ""
rows = []
for name, rec in list((m.get("services") or {}).items()):
if rec.get("fails", 0) >= 2:
rows.append(f"{name}: сбоев {rec['fails']}, причины: "
+ "; ".join((rec.get("reasons") or [])[-2:])[:120])
return "\n".join(rows[:10])
def run_agent(name, tz, group_report, policy, history):
user = json.dumps({
"group": group_report,
"policy": policy.get("classes") or {},
"recent": history[-3:],
"memory": memory_hint(),
"now": datetime.now().isoformat(timespec="seconds"),
}, ensure_ascii=False)
raw, err = llm(agent_system(tz), user)
@@ -143,6 +162,19 @@ def main():
pass
res = run_agent(agent, tz, rep, policy, hist)
try:
added = approvals.add(res.get("actions") or [], agent)
except Exception as _e:
added = []
print(" очередь заявок:", _e)
if added:
res["queued"] = [a["id"] for a in added]
lines = [f"#{a['id']} {a['action']} {a['target']} — {a.get('why', '')[:80]}"
for a in added]
runner.notify(
"Нужно подтверждение",
"Агент предлагает действия (класс C):\n" + "\n".join(lines)
+ "\n\nОтветьте в чате: `!одобрить <номер>` или `!отклонить <номер>`")
results.append(res)
path = os.path.join(JOURNAL, f"{stamp}-{agent}-llm.json")
json.dump(res, open(path, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
+188 -214
View File
@@ -1,254 +1,228 @@
#!/usr/bin/env python3
"""Раннер роя: читает группы и политику, проверяет сервисы, пишет журнал.
"""Раннер роя: видит ВСЕ сервисы, помнит ошибки, ищет дубли и мусор.
Режим v0 — только наблюдение: ничего не меняет, только собирает факты
и готовит отчёт Голове.
Пишет отчёт в журнал и отдаёт его мозгу. Ничего не меняет без класса A/B.
"""
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import time
from datetime import datetime
AGENTS_DIR = "/opt/hub-agents"
REGISTRY = "/opt/hub-core/services.yaml"
JOURNAL = "/var/lib/hub-agents/journal"
STATUS_URL = "http://127.0.0.1:9120/status.json"
MEMORY = "/var/lib/hub-agents/memory.json"
STATUS = "http://127.0.0.1:9120/status.json"
NOTIFY = "http://127.0.0.1:9120/notify"
GROUP_TITLES = {
"core": "Ядро", "home": "Дом", "media": "Медиа", "knowledge": "Знания",
"automation": "Автоматизация", "observability": "Наблюдаемость",
"support": "Служебные", "other": "Прочее",
}
def read_yaml(path):
"""Минимальный YAML-парсер под наши файлы (без зависимостей)."""
out, cur, stack = {}, None, []
# ---------- реестр ----------
def load_registry():
"""Все сервисы из services.yaml: name, group, ct, image, ports, criticality."""
items = []
cur = None
try:
lines = open(path, encoding="utf-8").read().splitlines()
for line in open(REGISTRY, encoding="utf-8"):
if line.startswith(" - key:"):
if cur:
items.append(cur)
cur = {"key": line.split(":", 1)[1].strip().strip('"')}
elif cur is not None and line.startswith(" "):
k, _, v = line.strip().partition(":")
cur[k] = v.strip().strip('"')
if cur:
items.append(cur)
except Exception:
return []
return items
# ---------- память ----------
def load_memory():
try:
return json.load(open(MEMORY, encoding="utf-8"))
except Exception:
return {"services": {}, "duplicates": [], "solutions": {}}
def save_memory(m):
os.makedirs(os.path.dirname(MEMORY), exist_ok=True)
json.dump(m, open(MEMORY, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
def remember(mem, name, ok, reason=""):
rec = mem["services"].setdefault(name, {"fails": 0, "first_fail": None,
"last_fail": None, "last_ok": None,
"reasons": []})
now = datetime.now().isoformat(timespec="seconds")
if ok:
rec["last_ok"] = now
rec["fails"] = 0
else:
rec["fails"] = rec.get("fails", 0) + 1
rec["last_fail"] = now
if not rec.get("first_fail"):
rec["first_fail"] = now
if reason:
rec["reasons"] = (rec.get("reasons") or [])[-4:] + [reason[:120]]
return rec
# ---------- проверки ----------
def status_data():
import urllib.request
try:
with urllib.request.urlopen(STATUS, timeout=25) as r:
return json.loads(r.read())
except Exception:
return {}
for raw in lines:
if not raw.strip() or raw.strip().startswith("#"):
def docker_state(name, ct):
"""Проверяет контейнер напрямую, если его нет в статусе."""
cmd = (["docker", "inspect", name] if ct == 0
else ["pct", "exec", str(ct), "--", "docker", "inspect", name])
r = subprocess.run(cmd + ["--format", "{{.State.Status}}"], capture_output=True,
text=True, timeout=20)
return (r.stdout or "").strip() or "unknown"
def duplicates(services):
"""Ищет реальные дубли: одинаковый образ в разных CT (двойной экземпляр)."""
by_image = {}
dups = []
for s in services:
img = (s.get("image") or "").split(":")[0]
if not img:
continue
indent = len(raw) - len(raw.lstrip())
line = raw.strip()
key, _, val = line.partition(":")
val = val.strip()
if indent == 0:
cur = None
if val:
out[key] = parse_scalar(val)
else:
out[key] = {}
stack = [(0, out[key])]
by_image.setdefault(img, []).append(s)
for img, items in by_image.items():
if len(items) < 2:
continue
# вложенность
while stack and indent <= stack[-1][0]:
stack.pop()
if not stack:
# служебные образы, которые нормально живут в каждом CT
if any(k in img for k in ("promtail", "oauth2-proxy", "exportarr", "redis")):
continue
target = stack[-1][1]
if val.startswith("["):
target[key] = [x.strip().strip("'\"") for x in val.strip("[]").split(",") if x.strip()]
elif val:
target[key] = parse_scalar(val)
else:
target[key] = {}
stack.append((indent, target[key]))
cts = {int(i.get("ct") or 0) for i in items}
names = [i.get("name") for i in items]
# дубль: один и тот же сервис в разных местах (хост + CT)
if 0 in cts and len(cts) > 1:
dups.append({"type": "double_instance", "image": img,
"services": names, "hint": "один экземпляр на хосте, другой в CT"})
elif len(set(names)) == 1 and len(items) > 1:
dups.append({"type": "same_name", "image": img, "services": names})
return dups
def junk():
"""Мусор: большие логи, висячие образы."""
out = {"big_logs": [], "dangling": 0}
r = subprocess.run(["docker", "system", "df"], capture_output=True, text=True, timeout=40)
m = re.search(r"Dangling Images\s+\d+\s+(\d+)", r.stdout or "")
if m:
out["dangling"] = int(m.group(1))
return out
def parse_scalar(v):
v = v.strip()
if v in ("true", "yes"):
return True
if v in ("false", "no"):
return False
if v.isdigit():
return int(v)
return v.strip("'\"")
def status():
import urllib.request
try:
with urllib.request.urlopen(STATUS_URL, timeout=25) as r:
return json.loads(r.read())
except Exception:
return {"services": [], "groups": {}, "total": 0, "up": 0}
def disk():
st = os.statvfs("/")
used = 1 - st.f_bavail / st.f_blocks
return round(used * 100, 1)
def swap():
try:
for line in open("/proc/meminfo"):
if line.startswith("SwapTotal"):
total = int(line.split()[1])
if line.startswith("SwapFree"):
free = int(line.split()[1])
return round(100 * (total - free) / total, 1) if total else 0.0
except Exception:
return 0.0
def media_disk():
"""Занятость медиа-диска (хост)."""
try:
st = os.statvfs("/mnt/media")
used = 1 - st.f_bavail / st.f_blocks
return round(used * 100, 1)
except Exception:
return None
def backup_age_hours():
"""Сколько часов самому свежему дампу/архиву."""
best = None
for root in ("/mnt/backups", "/root/matrix-backups"):
for dirpath, _, files in os.walk(root):
for f in files:
if not (f.endswith((".gz", ".tar.gz", ".sql.gz", ".zst", ".tar"))):
continue
p = os.path.join(dirpath, f)
try:
m = os.path.getmtime(p)
except Exception:
continue
if best is None or m > best:
best = m
if not best:
return None
return round((time.time() - best) / 3600, 1)
def tcp(ip, port, timeout=1.2):
try:
with socket.create_connection((ip, port), timeout=timeout):
return True
except Exception:
return False
def notify(title, message):
import urllib.request
body = json.dumps({"title": title, "message": message}).encode()
req = urllib.request.Request(NOTIFY, data=body, method="POST",
headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(req, timeout=15).read()
return True
except Exception:
return False
def backup_freshness(max_hours=26):
"""Самый свежий vzdump: возвращает (часы, имя) или (None, None)."""
import glob
paths = glob.glob("/mnt/backups/dump/*.zst")
if not paths:
return None, None
newest = max(paths, key=lambda p: os.path.getmtime(p))
age = (time.time() - os.path.getmtime(newest)) / 3600
return round(age, 1), os.path.basename(newest)
newest = max(paths, key=os.path.getmtime)
return round((time.time() - os.path.getmtime(newest)) / 3600, 1), os.path.basename(newest)
def check_backups(max_hours=26):
age, name = backup_freshness(max_hours)
ok = age is not None and age <= max_hours
return {"ok": ok, "age_hours": age, "file": name, "max_hours": max_hours}
def disk_pct(path="/"):
try:
st = os.statvfs(path)
return round((1 - st.f_bavail / st.f_blocks) * 100, 1)
except Exception:
return None
def check_group(name, group, st):
"""Проверка группы: сервисы + доп. проверки."""
wanted = [x for x in (group.get("services") or []) if x]
services = st.get("services") or []
checked, down = 0, []
for svc in wanted:
matches = [s for s in services
if svc in (s.get("name") or "") or (s.get("name") or "") in svc]
if not matches:
continue
checked += len(matches)
for m in matches:
if not m.get("up"):
down.append(m.get("name"))
down = sorted(set(down))
extra = {}
checks = group.get("extra_checks") or []
if "disk" in checks:
extra["disk_used_pct"] = disk()
extra["media_used_pct"] = media_disk()
if "swap" in checks:
extra["swap_used_pct"] = swap()
if "backups" in checks:
extra["newest_backup_hours"] = backup_age_hours()
if "tls" in checks:
extra["tls_ok"] = tcp("127.0.0.1", 443)
if "ha_api" in checks:
extra["ha_ok"] = tcp("192.168.1.106", 8123)
if "zigbee" in checks:
extra["zigbee_bridge"] = tcp("192.168.1.10", 8098)
return {
"group": name,
"checked": checked,
"down": down,
"extra": extra,
}
# ---------- отчёт ----------
def main():
groups_doc = read_yaml(os.path.join(AGENTS_DIR, "groups.yaml"))
policy = read_yaml(os.path.join(AGENTS_DIR, "policy.yaml"))
st = status()
services = load_registry()
st = status_data()
up_map = {s["name"]: s.get("up") for s in st.get("services", [])}
mem = load_memory()
groups = {}
problems = []
for s in services:
name = s.get("name")
group = s.get("group", "other")
ct = int(s.get("ct") or 0)
up = up_map.get(name)
reason = ""
if up is None:
state = docker_state(name, ct)
up = state == "running"
reason = f"docker state: {state}"
rec = remember(mem, name, bool(up), reason)
groups.setdefault(group, {"total": 0, "up": 0})
groups[group]["total"] += 1
groups[group]["up"] += 1 if up else 0
if not up:
problems.append({
"name": name, "group": group, "ct": ct,
"fails": rec.get("fails", 1),
"reason": reason or "не в статусе",
"since": rec.get("first_fail"),
})
dups = duplicates(services)
junk_info = junk()
bkp_age, bkp_file = backup_freshness()
disk = disk_pct("/")
mem["duplicates"] = dups
save_memory(mem)
os.makedirs(JOURNAL, exist_ok=True)
stamp = datetime.now().strftime("%Y-%m-%d")
reports = []
report = {
"ts": datetime.now().isoformat(timespec="seconds"),
"services_total": len(services),
"services_up": sum(g["up"] for g in groups.values()),
"groups": groups,
"problems": problems,
"duplicates": dups,
"junk": junk_info,
"disk_pct": disk,
"backup_age_hours": bkp_age,
"backup_file": bkp_file,
}
json.dump(report, open(os.path.join(JOURNAL, f"{stamp}-runner.json"), "w"),
ensure_ascii=False, indent=1)
for name, group in (groups_doc.get("groups") or {}).items():
if not isinstance(group, dict):
continue
rep = check_group(name, group, st)
rep["agent"] = group.get("agent")
rep["ts"] = datetime.now().isoformat(timespec="seconds")
reports.append(rep)
path = os.path.join(JOURNAL, f"{stamp}-{rep['agent']}.json")
json.dump(rep, open(path, "w", encoding="utf-8"), ensure_ascii=False)
bkp = check_backups()
total_down = sum(len(r["down"]) for r in reports)
total_checked = sum(r["checked"] for r in reports)
print(f"проверено сервисов: {total_checked}, проблем: {total_down}")
for r in reports:
tail = f" — {', '.join(r['down'])}" if r["down"] else ""
print(f" {r['group']:<14} {r['checked'] - len(r['down'])}/{r['checked']}{tail}")
for k, v in (r["extra"] or {}).items():
print(f" {k}: {v}")
# Голова: сообщает только если есть проблемы и не тихие часы
hour = datetime.now().hour
quiet = hour >= 23 or hour < 8
if not bkp["ok"]:
print(f" БЭКАП: последний {bkp['age_hours']} ч назад (порог {bkp['max_hours']} ч)")
else:
print(f" бэкап: {bkp['age_hours']} ч назад — ок")
if (total_down or not bkp["ok"]) and not quiet:
lines = [f"⚠️ Проблемы: {total_down}"]
if not bkp["ok"]:
lines.append(f"• БЭКАП: последний {bkp['age_hours']} ч назад "
f"(файл {bkp['file']}), порог {bkp['max_hours']} ч")
for r in reports:
if r["down"]:
lines.append(f"• {r['group']}: {', '.join(r['down'])}")
notify("Страж: проблемы в сервисах", "\n".join(lines))
print(" уведомление отправлено")
else:
print(" уведомление не нужно")
print(f"сервисов: {report['services_up']}/{report['services_total']}")
for g, v in sorted(groups.items()):
mark = "✅" if v["up"] == v["total"] else "⚠️"
print(f" {mark} {GROUP_TITLES.get(g, g)}: {v['up']}/{v['total']}")
if problems:
print("проблемы:")
for p in problems[:10]:
print(f" ✗ {p['name']} (CT{p['ct']}, сбоев {p['fails']}): {p['reason']}")
if dups:
print("дубли:")
for d in dups[:5]:
print(f" ⧉ {d['type']}: {', '.join(d['services'])}")
if bkp_age is not None:
print(f"бэкап: {bkp_age} ч назад")
print(f"диск: {disk}% | висячих образов: {junk_info['dangling']}")
if __name__ == "__main__":
+21
View File
@@ -29,6 +29,22 @@ def status():
return {}
def work_section():
import datetime as _dt
import glob as _g
path = f"/var/lib/hub-agents/journal/{_dt.date.today().isoformat()}-work.json"
try:
d = json.load(open(path, encoding="utf-8"))
except Exception:
return None
loc = d.get("local") or {}
lines = [f"💼 Работа: клиентов {loc.get('clients', 0)}, "
f"встреч {loc.get('meetings', 0)}, файлов {loc.get('files', 0)}"]
for p in (d.get("problems") or [])[:3]:
lines.append(f"⚠️ {p}")
return lines
def main():
today = time.strftime("%Y-%m-%d")
lines = ["🧠 **Сводка роя**", time.strftime("%d.%m.%Y"), ""]
@@ -72,6 +88,11 @@ def main():
for a in pending[:5]:
lines.append(f"• #{a['id']} {a['action']} {a['target']}")
work = work_section()
if work:
lines.append("")
lines.extend(work)
# состояние агентов
stt = load(STATE, {})
if stt.get("last_run"):
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Рабочий секретарь: состояние рабочего контура (ВКС/Presale)."""
import json
import os
import subprocess
import time
import urllib.request
REPO_API = ("http://192.168.1.140:3000/api/v1/repos/infrastructure/buryan-work")
TOKEN = open("/root/.bwork-token", encoding="utf-8").read().strip() if os.path.exists(
"/root/.bwork-token") else ""
WORK = "/opt/buryan-work"
def sh(cmd, timeout=60):
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
return (r.stdout or "").strip()
def repo_state():
try:
req = urllib.request.Request(REPO_API, headers={"Authorization": "token " + TOKEN})
with urllib.request.urlopen(req, timeout=15) as r:
d = json.loads(r.read() or b"{}")
return {"ok": True, "updated": d.get("updated_at"), "size": d.get("size")}
except Exception as e:
return {"ok": False, "error": str(e)[:80]}
def local_state():
out = {"files": 0, "clients": 0, "meetings": 0, "dirty": False, "behind": None}
if not os.path.isdir(WORK):
return out
for root, _, files in os.walk(WORK):
if "/.git" in root:
continue
out["files"] += len(files)
if "/clients" in root:
out["clients"] += len(files)
if "/meetings" in root:
out["meetings"] += len(files)
out["dirty"] = bool(sh(f"cd {WORK} && git status --porcelain 2>/dev/null"))
return out
def tools_state():
return {
"transcribe": os.path.exists("/usr/local/bin/meeting-transcribe"),
"faster_whisper": sh("/opt/music-tools/venv/bin/python -c "
"'import faster_whisper;print(1)' 2>/dev/null") == "1",
}
def main():
rep = repo_state()
loc = local_state()
tools = tools_state()
problems = []
if not rep.get("ok"):
problems.append(f"репозиторий недоступен: {rep.get('error')}")
if loc["dirty"]:
problems.append("в рабочей копии есть незакоммиченные изменения")
if not tools["transcribe"]:
problems.append("нет утилиты транскрипции")
if loc["clients"] == 0:
problems.append("ни одного клиента в базе")
if loc["meetings"] == 0:
problems.append("ни одной заметки встречи")
report = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
"repo": rep,
"local": loc,
"tools": tools,
"problems": problems,
}
os.makedirs("/var/lib/hub-agents/journal", exist_ok=True)
with open("/var/lib/hub-agents/journal/" + time.strftime("%Y-%m-%d")
+ "-work.json", "w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=1)
print("Рабочий секретарь")
print(f" репозиторий: {'ok' if rep.get('ok') else 'нет связи'} | файлов: {loc['files']}")
print(f" клиенты: {loc['clients']} | встречи: {loc['meetings']}")
print(f" транскрипция: {'есть' if tools['transcribe'] else 'нет'}")
for p in problems:
print(" ⚠️", p)
if __name__ == "__main__":
main()