Compare commits

..
Author SHA1 Message Date
architect 235e7b829c [STAGE5] Migrate DigestBot to gateway read tools
standard / check (push) Successful in 11s
lint / hygiene (pull_request) Failing after 30s
standard / check (pull_request) Successful in 12s
lint / hygiene (push) Failing after 24s
2026-11-29 22:15:23 +03:00
architect 7e30c8df13 [STAGE5] Migrate HomeBot to gateway local-tools
lint / hygiene (pull_request) Failing after 27s
standard / check (pull_request) Successful in 10s
lint / hygiene (push) Failing after 30s
standard / check (push) Successful in 11s
2026-11-29 22:08:55 +03:00
architect c7be3583e1 [STAGE5] Migrate BookBot to gateway local-tools
standard / check (pull_request) Successful in 11s
lint / hygiene (pull_request) Failing after 24s
lint / hygiene (push) Failing after 31s
standard / check (push) Successful in 11s
2026-11-29 22:07:37 +03:00
architect 8844dabf94 [STAGE5] Migrate PhotoBot to Tool Gateway with local tools
lint / hygiene (pull_request) Failing after 25s
standard / check (pull_request) Successful in 11s
lint / hygiene (push) Failing after 33s
standard / check (push) Successful in 12s
2026-11-29 22:05:34 +03:00
architect c0ec0d2d3d [STAGE5] Add status.json.read tool for legacy migration
lint / hygiene (pull_request) Failing after 29s
standard / check (pull_request) Successful in 13s
standard / check (push) Successful in 11s
lint / hygiene (push) Failing after 26s
2026-11-29 18:14:46 +03:00
architect 2c182a96ef [STAGE5] G5 migration plan; legacy agents remain
lint / hygiene (push) Failing after 29s
lint / hygiene (pull_request) Failing after 24s
standard / check (pull_request) Successful in 11s
2026-11-29 18:13:29 +03:00
architect ceb716ada7 [STAGE5] Model lease limits + tests
lint / hygiene (push) Failing after 25s
lint / hygiene (pull_request) Failing after 25s
standard / check (pull_request) Successful in 11s
2026-11-29 18:12:09 +03:00
architect 259ba878d7 [STAGE5] Approval queue for gateway write tools
lint / hygiene (push) Failing after 25s
lint / hygiene (pull_request) Failing after 23s
standard / check (pull_request) Successful in 14s
2026-11-29 18:10:39 +03:00
architect 15ed2067e8 [STAGE5] Gateway-only production agent service
lint / hygiene (push) Failing after 24s
lint / hygiene (pull_request) Failing after 24s
standard / check (pull_request) Successful in 11s
2026-11-29 18:08:37 +03:00
architect 32f23ed184 [STAGE5] Restore accurate stage status after enforcement
lint / hygiene (push) Failing after 23s
lint / hygiene (pull_request) Failing after 33s
standard / check (pull_request) Successful in 10s
2026-11-29 18:06:49 +03:00
architect e6bac6ae2e [STAGE5] Reference Tool Gateway enforcement (UID agent-gw)
lint / hygiene (push) Failing after 25s
lint / hygiene (pull_request) Failing after 20s
standard / check (pull_request) Successful in 10s
2026-11-29 18:06:03 +03:00
architect 6df90ee853 [STAGE5] Night Shift verified + memory/evals status
lint / hygiene (pull_request) Failing after 24s
standard / check (pull_request) Successful in 12s
lint / hygiene (push) Failing after 22s
2026-11-29 18:04:21 +03:00
architect f2bdccc45b [STAGE5] Agent memory store + TTL/search tests
lint / hygiene (push) Failing after 23s
lint / hygiene (pull_request) Failing after 26s
standard / check (pull_request) Successful in 12s
2026-11-29 18:03:36 +03:00
architect 6cd7984910 [STAGE5] Golden set + eval runner baseline 1/10
lint / hygiene (pull_request) Failing after 23s
standard / check (pull_request) Successful in 12s
lint / hygiene (push) Failing after 24s
2026-11-29 18:02:40 +03:00
architect 7e372641bd [CAMERA] Note Wi-Fi instability + Frigate setup
lint / hygiene (pull_request) Failing after 24s
lint / hygiene (push) Failing after 23s
standard / check (pull_request) Successful in 11s
2026-11-29 18:00:58 +03:00
buryan-agent 13fa7ba5ce [A-38] Снимок состояния 2026-11-29
lint / hygiene (push) Failing after 22s
standard / check (push) Successful in 10s
standard / check (pull_request) Successful in 10s
lint / hygiene (pull_request) Failing after 25s
2026-11-29 09:00:28 +03:00
root b6c9643198 [STANDARD] Ночной пересчёт соответствия 2026-11-29 2026-11-29 04:40:00 +03:00
buryan-agent 8c16e9c552 [A-38] Снимок состояния 2026-11-28
lint / hygiene (push) Failing after 17s
standard / check (push) Successful in 8s
lint / hygiene (pull_request) Failing after 20s
standard / check (pull_request) Successful in 8s
2026-11-28 09:00:26 +03:00
root ef706a3c25 [STANDARD] Ночной пересчёт соответствия 2026-11-28 2026-11-28 04:40:00 +03:00
architect c5c802ce6c [PRISM] Fix missing requirements/matrix-db functions
lint / hygiene (push) Failing after 20s
standard / check (pull_request) Successful in 7s
lint / hygiene (pull_request) Failing after 16s
2026-11-27 23:23:27 +03:00
architect 87cc382376 [STAGE5] Gateway-only smoke agent
lint / hygiene (push) Failing after 16s
lint / hygiene (pull_request) Failing after 21s
standard / check (pull_request) Successful in 8s
2026-11-27 22:21:22 +03:00
architect 3045cedf62 [STAGE5] Model lease runtime via Tool Gateway
lint / hygiene (push) Failing after 17s
standard / check (push) Successful in 10s
lint / hygiene (pull_request) Failing after 16s
standard / check (pull_request) Successful in 8s
2026-11-27 22:20:32 +03:00
architect 7735ddff28 [STAGE5] Tool Gateway runtime + hub-tools service
lint / hygiene (pull_request) Failing after 27s
standard / check (push) Successful in 8s
standard / check (pull_request) Successful in 7s
lint / hygiene (push) Failing after 19s
2026-11-27 21:13:08 +03:00
architect 649386f0b8 [STAGE5] Tool Gateway policy registry + test
lint / hygiene (push) Failing after 22s
standard / check (pull_request) Successful in 8s
lint / hygiene (pull_request) Failing after 1m3s
2026-11-27 21:09:53 +03:00
architect 457f95d3b1 [STAGE5] Model Registry v0 + health
lint / hygiene (push) Failing after 18s
lint / hygiene (pull_request) Failing after 20s
standard / check (pull_request) Successful in 7s
2026-11-27 21:08:39 +03:00
architect ae5ab904fd [STAGE4] Gate G4 evidence: 4 adapters, contract tests green
lint / hygiene (push) Failing after 58s
lint / hygiene (pull_request) Failing after 21s
standard / check (pull_request) Successful in 7s
2026-11-27 20:41:47 +03:00
architect 506ae58410 [STAGE4] Adapter SDK, 4 adapters, contract tests, preview
lint / hygiene (pull_request) Failing after 17s
standard / check (pull_request) Successful in 7s
lint / hygiene (push) Failing after 1m11s
standard / check (push) Successful in 8s
2026-11-27 20:40:19 +03:00
architect 7ef5b02698 [STAGE4] Mission Control v0 + Matrix internal homeserver
lint / hygiene (pull_request) Failing after 22s
lint / hygiene (push) Failing after 19s
standard / check (pull_request) Successful in 7s
2026-11-27 20:36:54 +03:00
architect 0f41d71a0b [STAGE3] Tracker: OpenSubtitles creds, TLS block
lint / hygiene (push) Failing after 25s
standard / check (pull_request) Successful in 19s
lint / hygiene (pull_request) Failing after 28s
2026-11-27 17:07:47 +03:00
architect 7099d402a0 [STAGE3] OpenSubtitles creds configured; Bazarr TLS/login blocked
lint / hygiene (push) Failing after 44s
standard / check (pull_request) Successful in 9s
lint / hygiene (pull_request) Failing after 23s
2026-11-27 17:07:07 +03:00
architect b7b5c36c55 [STAGE3] Tracker: OpenSubtitles download blocked
lint / hygiene (push) Failing after 27s
lint / hygiene (pull_request) Failing after 30s
standard / check (pull_request) Successful in 14s
2026-11-27 15:55:15 +03:00
architect 54905cccab [STAGE3] OpenSubtitles API: RU search works, download incomplete
lint / hygiene (pull_request) Failing after 1m36s
lint / hygiene (push) Failing after 32s
standard / check (push) Successful in 13s
standard / check (pull_request) Successful in 12s
2026-11-27 15:54:36 +03:00
architect 64f0f05200 [STAGE3] S3-04 done: Matrix-only requests
lint / hygiene (push) Failing after 30s
lint / hygiene (pull_request) Failing after 26s
standard / check (pull_request) Successful in 13s
2026-11-27 15:39:38 +03:00
architect 84834e40af [STAGE3] Matrix-only request scope; Telegram excluded
standard / check (pull_request) Successful in 14s
lint / hygiene (push) Failing after 38s
lint / hygiene (pull_request) Failing after 1m30s
2026-11-27 15:39:00 +03:00
architect c9eddc0eda [STAGE3] Tracker: Bazarr RU provider blocked
lint / hygiene (push) Failing after 2m33s
lint / hygiene (pull_request) Failing after 29s
standard / check (pull_request) Successful in 15s
2026-11-27 11:58:56 +03:00
architect eb070b7be5 [STAGE3] Bazarr RU path attempted; subf2m no file
lint / hygiene (push) Failing after 2m50s
lint / hygiene (pull_request) Failing after 40s
standard / check (pull_request) Successful in 13s
2026-11-27 11:58:14 +03:00
architect 13d14b13a7 [STAGE3] Tracker: RU/Telegram blockers
lint / hygiene (push) Failing after 27s
standard / check (pull_request) Successful in 14s
lint / hygiene (pull_request) Failing after 35s
2026-11-27 11:36:49 +03:00
architect 060bb8f276 [STAGE3] Evidence: no RU files on disk; Telegram absent
lint / hygiene (pull_request) Failing after 34s
standard / check (pull_request) Successful in 15s
lint / hygiene (push) Failing after 28s
2026-11-27 11:36:10 +03:00
architect ff34b72f9a [STAGE3] Tracker: duplicate guard
lint / hygiene (push) Failing after 1m25s
lint / hygiene (pull_request) Failing after 34s
standard / check (pull_request) Successful in 19s
2026-11-27 11:35:21 +03:00
architect 8273956058 [STAGE3] Duplicate check before Seerr request
lint / hygiene (pull_request) Failing after 43s
standard / check (push) Successful in 17s
lint / hygiene (push) Failing after 28s
standard / check (pull_request) Successful in 14s
2026-11-27 11:34:55 +03:00
architect a7b1a90e9c [STAGE3] Tracker: Alpha/Matrix request paths
standard / check (pull_request) Successful in 14s
lint / hygiene (push) Failing after 28s
lint / hygiene (pull_request) Failing after 40s
2026-11-27 11:33:15 +03:00
architect 2fbe23476c [STAGE3] Matrix/Alpha request paths documented
lint / hygiene (push) Failing after 26s
lint / hygiene (pull_request) Failing after 35s
standard / check (pull_request) Successful in 18s
2026-11-27 11:32:56 +03:00
architect 8b78cd9a61 [STAGE3] Matrix !request link to Seerr
lint / hygiene (pull_request) Failing after 31s
lint / hygiene (push) Failing after 1m26s
standard / check (pull_request) Successful in 13s
standard / check (push) Successful in 14s
2026-11-27 11:32:13 +03:00
architect e6a29a5cda [STAGE3] Tracker: Alpha request path
lint / hygiene (push) Failing after 33s
lint / hygiene (pull_request) Failing after 27s
standard / check (pull_request) Successful in 13s
2026-11-27 11:30:49 +03:00
architect 3636be5ddd [STAGE3] Alpha request handoff to Seerr
standard / check (pull_request) Successful in 17s
standard / check (push) Successful in 17s
lint / hygiene (pull_request) Failing after 30s
lint / hygiene (push) Failing after 34s
2026-11-27 11:30:11 +03:00
architect 2be898d584 [STAGE3] Tracker: direct 6/6 done
lint / hygiene (push) Failing after 35s
lint / hygiene (pull_request) Failing after 41s
standard / check (pull_request) Successful in 14s
2026-11-27 11:29:13 +03:00
architect 304db34ac2 [STAGE3] Direct-play 6/6 playable media
lint / hygiene (push) Failing after 36s
standard / check (pull_request) Successful in 27s
standard / check (push) Successful in 17s
lint / hygiene (pull_request) Failing after 33s
2026-11-27 11:28:35 +03:00
architect 6ab94962ac [STAGE3] Tracker: direct 6/7, RU blocked by source
lint / hygiene (push) Failing after 49s
lint / hygiene (pull_request) Failing after 47s
standard / check (pull_request) Successful in 16s
2026-11-27 11:27:42 +03:00
architect 8940671aa3 [STAGE3] Direct-play 6/7 via episode inspection
lint / hygiene (pull_request) Failing after 29s
standard / check (pull_request) Successful in 29s
lint / hygiene (push) Failing after 27s
2026-11-27 11:27:01 +03:00
architect f57684399c [STAGE3] Tracker: Stage3 tasks
lint / hygiene (push) Failing after 1m42s
standard / check (pull_request) Successful in 16s
lint / hygiene (pull_request) Failing after 1m18s
2026-11-27 11:26:14 +03:00
architect 64e3c95667 [STAGE3] RU/direct-play coverage audit + tasks
standard / check (pull_request) Successful in 24s
lint / hygiene (push) Failing after 32s
standard / check (push) Successful in 16s
lint / hygiene (pull_request) Failing after 49s
2026-11-27 11:25:37 +03:00
architect 5ff027fc42 [STAGE2] S2-05 done: adapters live
lint / hygiene (push) Failing after 1m55s
standard / check (pull_request) Successful in 20s
lint / hygiene (pull_request) Failing after 26s
2026-11-27 11:20:28 +03:00
architect e6fc2cb3aa [STAGE2] Adapters: Audit360 + Jellyfin + Seerr
standard / check (push) Successful in 29s
lint / hygiene (pull_request) Failing after 42s
standard / check (pull_request) Successful in 21s
lint / hygiene (push) Failing after 37s
2026-11-27 11:20:05 +03:00
architect 2f0017a663 [STAGE2] Tracker: durable pipeline active
lint / hygiene (push) Failing after 1m42s
lint / hygiene (pull_request) Failing after 46s
standard / check (pull_request) Successful in 23s
2026-11-27 11:18:22 +03:00
architect 46761c0142 [STAGE2] Durable events pipeline + Audit360 adapter
lint / hygiene (push) Failing after 2m3s
standard / check (push) Successful in 27s
lint / hygiene (pull_request) Failing after 28s
standard / check (pull_request) Successful in 12s
2026-11-27 11:17:39 +03:00
architect a221d71971 [STAGE2] Tracker: S2-06 pgvector done
lint / hygiene (push) Failing after 29s
lint / hygiene (pull_request) Failing after 1m53s
standard / check (pull_request) Successful in 13s
2026-11-27 11:14:59 +03:00
architect 50c31091b2 [STAGE2] pgvector infrastructure pilot
lint / hygiene (pull_request) Failing after 29s
standard / check (pull_request) Successful in 12s
standard / check (push) Successful in 14s
lint / hygiene (push) Failing after 29s
2026-11-27 11:14:20 +03:00
architect 9340263940 [STAGE2] Tracker: G2 done, ownership in progress
lint / hygiene (push) Failing after 25s
lint / hygiene (pull_request) Failing after 2m48s
standard / check (pull_request) Successful in 17s
2026-11-27 11:13:41 +03:00
architect d6ee44f0e7 [STAGE2] Gate G2 proof: 100 duplicates→1 effect, loss recovered
standard / check (pull_request) Successful in 9s
lint / hygiene (push) Failing after 20s
standard / check (push) Successful in 10s
lint / hygiene (pull_request) Failing after 1m27s
2026-11-27 11:13:22 +03:00
architect fca442c5da [ARCH] Service acceptance questionnaire with auto-checks
lint / hygiene (push) Failing after 28s
standard / check (pull_request) Successful in 13s
standard / check (push) Successful in 12s
lint / hygiene (pull_request) Failing after 1m22s
2026-11-27 10:53:31 +03:00
architect 2a1393def5 [STAGE2] S2-04 done: JetStream relay e2e
lint / hygiene (push) Failing after 58s
lint / hygiene (pull_request) Failing after 1m21s
standard / check (pull_request) Successful in 14s
2026-11-27 10:48:20 +03:00
architect 8657ce5e55 [STAGE2] NATS JetStream relay e2e (outbox→consumer→effect)
lint / hygiene (pull_request) Failing after 1m22s
lint / hygiene (push) Failing after 38s
standard / check (pull_request) Successful in 14s
standard / check (push) Successful in 12s
2026-11-27 10:47:33 +03:00
architect 8f8ee4186e [STAGE2] Event envelope + outbox/inbox idempotency (100→1)
lint / hygiene (pull_request) Failing after 41s
lint / hygiene (push) Failing after 39s
standard / check (pull_request) Successful in 13s
standard / check (push) Successful in 15s
2026-11-27 10:45:37 +03:00
architect c1f9136bbe [ARCH] Gates accepted: sprint closed, handoff updated
lint / hygiene (pull_request) Failing after 38s
standard / check (pull_request) Successful in 13s
lint / hygiene (push) Failing after 27s
2026-11-27 10:41:56 +03:00
architect 544b9fd248 [ARCH] Gate G0/G1 accepted by owner
lint / hygiene (push) Failing after 1m26s
lint / hygiene (pull_request) Failing after 30s
standard / check (pull_request) Successful in 12s
2026-11-27 10:40:57 +03:00
architect f7bbb41c76 [ARCH] Clickable Owner console + linked search results
lint / hygiene (pull_request) Failing after 35s
standard / check (pull_request) Successful in 16s
lint / hygiene (push) Failing after 36s
standard / check (push) Successful in 12s
2026-11-27 10:35:05 +03:00
architect c1dadbfd03 [ARCH] Owner guide: G1 review_pending, second-owner access
lint / hygiene (push) Failing after 32s
lint / hygiene (pull_request) Failing after 33s
standard / check (pull_request) Successful in 14s
2026-11-27 10:28:56 +03:00
architect 580b8786ff [ARCH] Gate G1 review_pending
lint / hygiene (push) Failing after 33s
lint / hygiene (pull_request) Failing after 40s
standard / check (pull_request) Successful in 13s
2026-11-27 10:28:29 +03:00
architect 0a7da2079a [ARCH] Owner click guide + final handoff: Media 10/10, FIT accepted
lint / hygiene (pull_request) Failing after 1m16s
standard / check (pull_request) Successful in 14s
lint / hygiene (push) Failing after 34s
2026-11-27 10:27:43 +03:00
architect 3b668767d6 [ARCH] S1-07 done: FIT 4/18 accepted until Stage 2
lint / hygiene (push) Failing after 26s
lint / hygiene (pull_request) Failing after 20s
standard / check (pull_request) Successful in 15s
2026-11-27 10:26:49 +03:00
architect 18650448cb [ARCH] S1-05 done: Media API 10/10
lint / hygiene (push) Failing after 33s
lint / hygiene (pull_request) Failing after 2m3s
standard / check (pull_request) Successful in 14s
2026-11-27 10:26:24 +03:00
architect 38011b5c2f [ARCH] Media API 10/10: recommendations via Jellyfin Similar
lint / hygiene (push) Failing after 30s
standard / check (push) Successful in 12s
lint / hygiene (pull_request) Failing after 28s
standard / check (pull_request) Successful in 16s
2026-11-27 10:26:05 +03:00
architect 7b4a944fa3 [ARCH] Handoff: media 9/10; Seerr discover 500
lint / hygiene (push) Failing after 1m33s
lint / hygiene (pull_request) Failing after 41s
standard / check (pull_request) Successful in 17s
2026-11-27 10:17:01 +03:00
architect 0b0df30544 [ARCH] Tracker: Media API 9/10
lint / hygiene (push) Failing after 43s
lint / hygiene (pull_request) Failing after 31s
standard / check (pull_request) Successful in 16s
2026-11-27 10:16:35 +03:00
architect e4735e7323 [ARCH] Media releases from Radarr; 9/10 functional
lint / hygiene (pull_request) Failing after 38s
standard / check (pull_request) Successful in 15s
lint / hygiene (push) Failing after 33s
standard / check (push) Successful in 15s
2026-11-27 10:15:58 +03:00
architect fb9af77c9d [ARCH] Handoff: media API 8/10
lint / hygiene (pull_request) Failing after 26s
lint / hygiene (push) Failing after 25s
standard / check (pull_request) Successful in 12s
2026-11-27 10:14:50 +03:00
architect d0d36e8503 [ARCH] Tracker: Media API 8/10 functional
lint / hygiene (push) Failing after 28s
lint / hygiene (pull_request) Failing after 1m19s
standard / check (pull_request) Successful in 16s
2026-11-27 10:14:29 +03:00
architect 9db514f7e2 [ARCH] Media continue + stable requests retry
lint / hygiene (pull_request) Failing after 32s
lint / hygiene (push) Failing after 30s
standard / check (pull_request) Successful in 15s
standard / check (push) Successful in 14s
2026-11-27 10:13:47 +03:00
architect ec33f4a010 [ARCH] Handoff: fitness 4/18 final snapshot
lint / hygiene (push) Failing after 36s
lint / hygiene (pull_request) Failing after 1m28s
standard / check (pull_request) Successful in 16s
2026-11-27 10:12:48 +03:00
architect 4a0765189a [ARCH] Tracker: fitness 4/18
lint / hygiene (push) Failing after 29s
lint / hygiene (pull_request) Failing after 27s
standard / check (pull_request) Successful in 13s
2026-11-27 10:12:31 +03:00
architect d45c8d3273 [ARCH] FIT-01 pass: media works without LLM
lint / hygiene (pull_request) Failing after 27s
standard / check (pull_request) Successful in 14s
lint / hygiene (push) Failing after 36s
standard / check (push) Successful in 14s
2026-11-27 10:11:51 +03:00
architect ffbc203e53 [ARCH] Handoff: Prism queue complete, PC unloaded, requests 200
lint / hygiene (push) Failing after 28s
standard / check (pull_request) Successful in 14s
lint / hygiene (pull_request) Failing after 43s
2026-11-27 10:11:22 +03:00
architect ff37c0aa97 [ARCH] Tracker: Seerr requests 200
lint / hygiene (push) Failing after 37s
lint / hygiene (pull_request) Failing after 33s
standard / check (pull_request) Successful in 14s
2026-11-27 10:10:52 +03:00
architect bb2c594cbf [ARCH] Seerr session cache: requests stable 200
lint / hygiene (push) Failing after 43s
lint / hygiene (pull_request) Failing after 34s
standard / check (pull_request) Successful in 15s
standard / check (push) Successful in 14s
2026-11-27 10:10:15 +03:00
architect dc7a21ea24 [ARCH] Refresh morning handoff: dashboard, Prism fallback, S1-08
standard / check (pull_request) Successful in 14s
lint / hygiene (push) Failing after 29s
lint / hygiene (pull_request) Failing after 27s
2026-11-27 10:07:49 +03:00
architect 0b0dcc56c6 [ARCH] Dashboard: Fitness 3/18 card
lint / hygiene (pull_request) Failing after 29s
standard / check (pull_request) Successful in 11s
standard / check (push) Successful in 15s
lint / hygiene (push) Failing after 30s
2026-11-27 10:07:11 +03:00
architect dc802ae289 [PRISM] DeepSeek fallback on malformed JSON
lint / hygiene (pull_request) Failing after 1m9s
standard / check (pull_request) Successful in 12s
lint / hygiene (push) Failing after 33s
standard / check (push) Successful in 14s
2026-11-27 10:04:46 +03:00
98 changed files with 5232 additions and 243 deletions

No files matched your search

+8
View File
@@ -1,4 +1,12 @@
# 📝 CHANGELOG
## [2026-11-29] - 09:00
- 📸 Авто-снимок: 30/30 LXC запущено, 0 алертов за 24ч.
- 💻 Последний коммит: b6c9643 [STANDARD] Ночной пересчёт соответствия 2026-11-29
## [2026-11-28] - 09:00
- 📸 Авто-снимок: 30/30 LXC запущено, 0 алертов за 24ч.
- 💻 Последний коммит: ef706a3 [STANDARD] Ночной пересчёт соответствия 2026-11-28
## [2026-11-27] - 09:00
- 📸 Авто-снимок: 30/30 LXC запущено, 0 алертов за 24ч.
- 💻 Последний коммит: efad961 [STANDARD] Ночной пересчёт соответствия 2026-11-27
+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://buryans.ru/contracts/events/envelope-v1.json",
"title": "Buryans CloudEvent envelope v1",
"type": "object",
"additionalProperties": false,
"required": ["specversion", "id", "source", "type", "time", "idempotency_key", "data"],
"properties": {
"specversion": {"const": "1.0"},
"id": {"type": "string", "minLength": 1, "maxLength": 128},
"source": {"type": "string", "minLength": 1, "maxLength": 256},
"type": {"type": "string", "minLength": 1, "maxLength": 128},
"subject": {"type": "string", "maxLength": 256},
"time": {"type": "string", "format": "date-time"},
"datacontenttype": {"const": "application/json"},
"idempotency_key": {"type": "string", "minLength": 1, "maxLength": 256},
"correlation_id": {"type": "string", "maxLength": 128},
"causation_id": {"type": "string", "maxLength": 128},
"data": {"type": "object"}
}
}
+55
View File
@@ -0,0 +1,55 @@
events:
- event_type: media.request.created
owner: roman/media
producer: seerr-adapter
consumers: [notify-bot, audit360]
retention_days: 90
pii: false
- event_type: media.request.approved
owner: roman/media
producer: seerr-adapter
consumers: [notify-bot]
retention_days: 90
pii: false
- event_type: media.playback.started
owner: roman/media
producer: jellyfin-adapter
consumers: [audit360, analytics]
retention_days: 30
pii: true
- event_type: media.work.added
owner: roman/media
producer: jellyfin-adapter
consumers: [buryans-one, search]
retention_days: 365
pii: false
- event_type: audit.finding.opened
owner: roman/audit
producer: audit360
consumers: [nexus]
retention_days: 365
pii: false
- event_type: identity.user.created
owner: roman/sso
producer: authentik-adapter
consumers: [audit360, buryans-one]
retention_days: 365
pii: true
- event_type: home.state.changed
owner: roman/home
producer: homeassistant-adapter
consumers: [buryans-one]
retention_days: 30
pii: false
- event_type: agent.task.requested
owner: roman/agents
producer: bot-adapter
consumers: [agent-runner]
retention_days: 30
pii: false
- event_type: system.service.down
owner: roman/sre
producer: monitor-adapter
consumers: [notify-bot]
retention_days: 90
pii: false
+3
View File
@@ -0,0 +1,3 @@
# dialog
записей: 0
+3
View File
@@ -0,0 +1,3 @@
# dialog
записей: 0
+3
View File
@@ -0,0 +1,3 @@
# events
записей: 0
+3
View File
@@ -0,0 +1,3 @@
# events
записей: 0
+35
View File
@@ -0,0 +1,35 @@
{
"at": "2026-11-28T04:30:01+00:00",
"jellyfin": {
"Movie": 6,
"Series": 1,
"Episode": 24,
"Audio": 0
},
"navidrome": {
"albums": 28,
"tracks": 943,
"artists": 7
},
"calibre": {
"books": 41,
"authors": 32
},
"immich": {
"assets": 3286,
"albums": 24,
"users": 1
},
"paperless": {
"documents": 0
},
"sonarr": {
"items": 7
},
"radarr": {
"items": 30
},
"frigate": {
"cameras": 0
}
}
+16
View File
@@ -0,0 +1,16 @@
# Инвентаризация
на 2026-11-28T04:30:01+00:00
| Сервис | Что есть |
|---|---|
| Jellyfin | фильмы 6, сериалы 1, серии 24, треки 0 |
| Navidrome | альбомы 28, треки 943, исполнители 7 |
| Calibre | книги 41, авторы 32 |
| Immich | снимки 3286, альбомы 24 |
| Paperless | документы 0 |
| Sonarr | сериалов в базе 7 |
| Radarr | фильмов в базе 30 |
| Frigate | камер 0 |
_Нули означают, что библиотека пуста, а не что сервис не работает._
+35
View File
@@ -0,0 +1,35 @@
{
"at": "2026-11-29T04:30:02+00:00",
"jellyfin": {
"Movie": 6,
"Series": 1,
"Episode": 24,
"Audio": 0
},
"navidrome": {
"albums": 28,
"tracks": 943,
"artists": 7
},
"calibre": {
"books": 41,
"authors": 32
},
"immich": {
"assets": 3286,
"albums": 24,
"users": 1
},
"paperless": {
"documents": 0
},
"sonarr": {
"items": 7
},
"radarr": {
"items": 30
},
"frigate": {
"cameras": 1
}
}
+16
View File
@@ -0,0 +1,16 @@
# Инвентаризация
на 2026-11-29T04:30:02+00:00
| Сервис | Что есть |
|---|---|
| Jellyfin | фильмы 6, сериалы 1, серии 24, треки 0 |
| Navidrome | альбомы 28, треки 943, исполнители 7 |
| Calibre | книги 41, авторы 32 |
| Immich | снимки 3286, альбомы 24 |
| Paperless | документы 0 |
| Sonarr | сериалов в базе 7 |
| Radarr | фильмов в базе 30 |
| Frigate | камер 1 |
_Нули означают, что библиотека пуста, а не что сервис не работает._
+120
View File
@@ -0,0 +1,120 @@
# wishes
записей: 17
## 6142b62696f75e5f
обновлено: 2026-10-23 19:28:30.340791+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 3
* **текст**: Эти не интересные подскажи тупую американскую комедию типо очень страшного кино
## bfcc2b4db98ec7d8
обновлено: 2026-10-23 19:24:18.456461+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 2
* **текст**: Эти не интересные подскажи тупую американскую комедию типо очень страшного кино
## f0085c5bb1791665
обновлено: 2026-10-23 19:23:09.587491+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 1
* **текст**: Эти не интересные подскажи тупую американскую комедию типо очень страшного кино
## 912c925de49dcfd5
обновлено: 2026-10-21 21:15:53.853541+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 4
* **текст**: Ок
## 58be02cd2c676000
обновлено: 2026-10-21 21:14:43.197072+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 3
* **текст**: Скачай
## 14f8cf062dc523a1
обновлено: 2026-10-21 21:13:07.795455+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 2
* **текст**: Можешь ли ты скачать ферму кларксона
## 6b1116496ff50806
обновлено: 2026-10-21 21:12:56.695974+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: infra
* **номер**: 1
* **текст**: Посмотри есть ли критические проблемы
## 665bc3b1b8096a07
обновлено: 2026-10-20 08:36:04.886173+00:00
* **от**: неизвестно
* **бот**: media
* **номер**: 3
* **текст**: посоветуй фильм про космос
## d1449144fbb41ec4
обновлено: 2026-10-20 08:35:19.767909+00:00
* **от**: неизвестно
* **бот**: media
* **номер**: 2
* **текст**: посоветуй фильм про космос
## d3c1cb8c6803de58
обновлено: 2026-10-20 08:30:35.819843+00:00
* **от**: неизвестно
* **бот**: media
* **номер**: 1
* **текст**: граф
## 6438d460b153a934
обновлено: 2026-10-19 18:29:42.601848+00:00
* **от**: неизвестно
* **бот**: infra
* **номер**: 9
* **текст**: входящие
## 4c399eb8d186a040
обновлено: 2026-10-19 18:28:03.538302+00:00
* **от**: неизвестно
* **бот**: infra
* **номер**: 8
* **текст**: входящие
## 206625a9dc2ef302
обновлено: 2026-10-19 18:26:35.573683+00:00
* **от**: неизвестно
* **бот**: infra
* **номер**: 7
* **текст**: входящие
## 7c71ec9ef6710266
обновлено: 2026-10-19 18:26:07.531245+00:00
* **от**: неизвестно
* **бот**: infra
* **номер**: 6
* **текст**: входящие
## 7bd8e6589111cdcf
обновлено: 2026-10-19 17:13:05.235512+00:00
* **от**: @polina:matrix.buryans.ru
* **бот**: media
* **номер**: 5
* **текст**: хочу сериал про космос
## wish-002
обновлено: 2026-10-19 17:11:24.853757+00:00
* **от**: Сергей
* **бот**: cam
* **текст**: добавить камеры во двор
## wish-001
обновлено: 2026-10-19 17:11:24.834397+00:00
* **от**: Полина
* **бот**: media
* **текст**: хочу мультфильмы про кота
+120
View File
@@ -0,0 +1,120 @@
# wishes
записей: 17
## 6142b62696f75e5f
обновлено: 2026-10-23 19:28:30.340791+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 3
* **текст**: Эти не интересные подскажи тупую американскую комедию типо очень страшного кино
## bfcc2b4db98ec7d8
обновлено: 2026-10-23 19:24:18.456461+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 2
* **текст**: Эти не интересные подскажи тупую американскую комедию типо очень страшного кино
## f0085c5bb1791665
обновлено: 2026-10-23 19:23:09.587491+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 1
* **текст**: Эти не интересные подскажи тупую американскую комедию типо очень страшного кино
## 912c925de49dcfd5
обновлено: 2026-10-21 21:15:53.853541+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 4
* **текст**: Ок
## 58be02cd2c676000
обновлено: 2026-10-21 21:14:43.197072+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 3
* **текст**: Скачай
## 14f8cf062dc523a1
обновлено: 2026-10-21 21:13:07.795455+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: media
* **номер**: 2
* **текст**: Можешь ли ты скачать ферму кларксона
## 6b1116496ff50806
обновлено: 2026-10-21 21:12:56.695974+00:00
* **от**: @akadmin:matrix.buryans.ru
* **бот**: infra
* **номер**: 1
* **текст**: Посмотри есть ли критические проблемы
## 665bc3b1b8096a07
обновлено: 2026-10-20 08:36:04.886173+00:00
* **от**: неизвестно
* **бот**: media
* **номер**: 3
* **текст**: посоветуй фильм про космос
## d1449144fbb41ec4
обновлено: 2026-10-20 08:35:19.767909+00:00
* **от**: неизвестно
* **бот**: media
* **номер**: 2
* **текст**: посоветуй фильм про космос
## d3c1cb8c6803de58
обновлено: 2026-10-20 08:30:35.819843+00:00
* **от**: неизвестно
* **бот**: media
* **номер**: 1
* **текст**: граф
## 6438d460b153a934
обновлено: 2026-10-19 18:29:42.601848+00:00
* **от**: неизвестно
* **бот**: infra
* **номер**: 9
* **текст**: входящие
## 4c399eb8d186a040
обновлено: 2026-10-19 18:28:03.538302+00:00
* **от**: неизвестно
* **бот**: infra
* **номер**: 8
* **текст**: входящие
## 206625a9dc2ef302
обновлено: 2026-10-19 18:26:35.573683+00:00
* **от**: неизвестно
* **бот**: infra
* **номер**: 7
* **текст**: входящие
## 7c71ec9ef6710266
обновлено: 2026-10-19 18:26:07.531245+00:00
* **от**: неизвестно
* **бот**: infra
* **номер**: 6
* **текст**: входящие
## 7bd8e6589111cdcf
обновлено: 2026-10-19 17:13:05.235512+00:00
* **от**: @polina:matrix.buryans.ru
* **бот**: media
* **номер**: 5
* **текст**: хочу сериал про космос
## wish-002
обновлено: 2026-10-19 17:11:24.853757+00:00
* **от**: Сергей
* **бот**: cam
* **текст**: добавить камеры во двор
## wish-001
обновлено: 2026-10-19 17:11:24.834397+00:00
* **от**: Полина
* **бот**: media
* **текст**: хочу мультфильмы про кота
+63 -129
View File
@@ -1,155 +1,89 @@
# Agent handoff — Buryans Hybrid night sprint
# Agent handoff — 2026-11-27 morning
Дата: 2026-11-26
Ветка: `arch/hybrid-v1`
PR: `http://192.168.1.140:3000/infrastructure/buryan-infra/pulls/192`
Последний коммит на момент handoff: `ea53c2d`
PR: `http://192.168.1.140:3000/infrastructure/buryan-infra/pulls/192`
## 1. Главное
## 1. Что сделано
Сделано без ожидания approvals:
- Buryans One Alpha: `http://192.168.1.10:9161/alpha/`
- Jellyfin status;
- Prism pending/errors;
- Audit counts;
- Fitness 4/18;
- search/recent/work/availability/editions/playback.
- SSO/Jellyfin: кнопка Authentik, вход подтверждён.
- Breakglass: login 200, ACL/revocation 3→0→3.
- Media API: 11/11 путей; 10/10 функциональны.
- `recommendations` → 200 из Jellyfin Similar (без Seerr/TMDB).
- Dashboard test: 3/3.
- Fitness: 4/18 pass (FIT-01/08/11/16), owner accepted.
- Audit 360: 29 done / 0 in_progress / 0 review_pending / 0 waiting / 2 deferred / 3 dropped.
- Gate G0 and Gate G1 accepted by owner (2026-11-27).
- Owner click guide: `docs/architecture/OWNER-CLICK-GUIDE.md`.
- Restore: Gitea/Audit/Authentik/n8n/Matrix/Prism; Seerr integrity.
- Prism: retry ошибок, DeepSeek fallback при битом JSON.
- Audit 360 tracker;
- Buryans One Alpha;
- SSO/Jellyfin кнопка;
- breakglass;
- ACL/revocation;
- Media API 11/11 путей;
- restore matrix;
- daily Seerr/Prism backups.
## 2. Prism
Не закрыто:
Причины ошибок:
- S1-05 idempotency;
- S1-07 FIT-01..18;
- S1-10 Gate G1;
- Seerr requests (403).
- 3b-модель отдаёт неполный JSON;
- часть задач без source/specs/matrix;
- таймауты 229.
**S0-10 Gate G0** → `review_pending`, ждёт утреннего клика.
Сделано:
## 2. Где смотреть
- 89 error-задач возвращены в pending;
- воркер переключён на ПК 194;
- DeepSeek fallback на malformed JSON.
Итог:
```text
http://192.168.1.10:9161/alpha/
http://192.168.1.10:9161/
https://media.buryans.ru
done 2547
error 42
pending 0
running 0
```
Alpha — read-only: SSO, поиск, новинки, work, availability, editions, playback resolve.
ПК: `models []` — модель выгружена.
Ошибки не зациклены, очередь завершена.
## 3. Секреты
## 3. Не закрыто
Не выводить в чат/JSON/Gitea.
- `S1-05`: **done** — Media API 10/10;
- `S1-07`: **done** — FIT 4/18 accepted until Stage 2;
- `S0-10`: Gate G0 **accepted**;
- `S1-10`: Gate G1 **accepted**.
- Second owner access: pending email.
## 4. Откат
```text
/root/.jellyfin-key
/root/.jellyfin-breakglass
/root/.seerr-key
/root/.pg-superuser-pass
/root/.gitea-admin-token
/root/.authentik-api-token
night-sprint-2026-11-27-morning
night-sprint-2026-11-26-latest
prism-deepseek-fallback-20261127
prism-parser-20261127
```
## 4. Доказательства
### Jellyfin
- SSO login подтверждён владельцем;
- `Authorization: MediaBrowser Token="..."` — рабочий способ;
- `X-Emby-Token`/`api_key` → 401;
- breakglass login 200;
- ACL/revocation: views 3 → 0 → 3.
### Media API
`test_media_paths.py`: 11/11 путей.
Функциональны:
- search;
- recent;
- me;
- work;
- availability;
- editions;
- playback/resolve.
Явно недоступны:
- requests → 503 (Seerr 403);
- continue/releases/recommendations → 501.
### Restore
- Gitea 117 таблиц / 5 репо;
- Audit 14;
- Authentik 230 / 9s;
- n8n 136 / 6s;
- Matrix 176 / 3s;
- Prism 21;
- Seerr SQLite integrity ok.
### Backups
Плюс:
```text
service-backups.timer 03:50
/mnt/archive/backups/prism
/mnt/archive/backups/seerr
/mnt/archive/backups/prism/tasks-before-retry-20261126-*.dump
/etc/nginx/conf.d/audit360-local.conf.bak-20261126
```
## 5. Статус трекера
## 5. Что проверить утром
| Статус | Кол-во |
|---|---:|
| done | 25 |
| in_progress | 2 |
| review_pending | 1 |
| waiting_user | 1 |
| deferred | 2 |
| dropped | 3 |
| **Всего** | 34 |
1. `/alpha/` — dashboard.
2. Jellyfin SSO-кнопка.
3. `breakglass`.
4. Audit 360 → S0-10.
5. Fitness endpoint `/v1/fitness`.
Открытые технические:
## 6. Правила
- `S1-05`;
- `S1-07`.
Gate:
- `S0-10` review_pending;
- `S1-10` waiting, не готов.
## 6. Что не трогать без снапшота
- Jellyfin DB/users/policy;
- Seerr config;
- nginx `/alpha/`;
- Authentik/Gitea/Audit БД;
- медиатеку.
## 7. Как проверять
```bash
systemctl is-active media-alpha audit360-svc
curl -s http://127.0.0.1:9180/health
curl -s 'http://127.0.0.1:9180/v1/media/search?q=the'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:9161/alpha/
```
Ожидаемо: active/active, health ok, search items > 0, alpha 302 (SSO).
## 8. Известные дефекты/риски
1. Seerr requests 403 — нужен рабочий admin key/session.
2. continue/releases/recommendations не имеют источника.
3. idempotency не проверена.
4. FIT-01..18 не все.
5. Jellyfin metadata restore не проверялся.
6. breakglass требует client `Authorization: MediaBrowser Client=...`; иначе login 400/401.
## 9. Следующий безопасный шаг
1. Утром прокликать Alpha/Jellyfin/Audit.
2. Закрыть S0-10.
3. Дать обратную связь по дефектам.
4. Только после этого — S1-05/S1-07 и G1.
- не трогать Jellyfin DB/policy без снапшота;
- не трогать Seerr config;
- после Prism выгрузить модель;
- секреты не выводить.
+57
View File
@@ -0,0 +1,57 @@
# Camera Wi-Fi — отдельная история
Дата: 2026-11-28/29.
## Камера
```text
OEM: Macro-Video / V380
Ethernet MAC: 68:E6:04:A3:73:F0
Wi-Fi MAC: 66:F6:8C:88:AF:19
RTSP: H.264, 1920×2160, 14 fps, AAC
```
## Сеть
```text
SSID: BuryansCam
2.4 GHz, WPA2-PSK
Bridge2 192.168.30.0/24
DHCP reservation: 66:F6:8C:88:AF:19 → 192.168.30.166
```
## Frigate
```text
camera: test_ignnatech
rtsp://192.168.30.166:554/
detect 640×360, 1 fps
record continuous 3 days
SHM 256 MB
```
## Проблема
Камера в Wi-Fi-режиме:
- периодически пропадает из ARP/ping;
- RTSP отдаёт `No route to host`;
- Frigate делает reconnect;
- LED и V380 при этом не показывают отвал — камера остаётся online в P2P/cloud.
Причина не в HA/MQTT/Frigate. Это Wi-Fi-модуль/питание/сигнал дешёвой камеры.
## Решение
Для стабильного Frigate:
- Ethernet; или
- Wi-Fi-мост: камера Ethernet → travel-router в режиме клиента → Wi-Fi.
Встроенный Wi-Fi камеры для постоянного RTSP не подходит.
## Что не трогать
- существующие Bridge0/Bridge1;
- HA, mosquitto, MQTT Frigate;
- камеру в Frigate без подтверждения стабильного IP.
+32
View File
@@ -0,0 +1,32 @@
# Event Ownership Matrix — Stage 2
Правило: у каждого типа события есть **один owner**, один producer и явные consumers.
Событие без owner не публикуется в production.
| event_type | owner | producer | consumers | retention | PII |
|---|---|---|---|---|---|
| media.request.created | Roman / Media | Seerr adapter | notification bot, Audit | 90d | no |
| media.request.approved | Roman / Media | Seerr adapter | notification bot | 90d | no |
| media.playback.started | Roman / Media | Jellyfin adapter | Audit, analytics | 30d | user id |
| media.work.added | Roman / Media | Jellyfin adapter | Buryans One, search | 365d | no |
| media.work.updated | Roman / Media | Jellyfin adapter | Buryans One | 365d | no |
| audit.finding.opened | Roman / Audit | Audit 360 | Nexus | 365d | no |
| audit.finding.closed | Roman / Audit | Audit 360 | Nexus | 365d | no |
| identity.user.created | Roman / SSO | Authentik adapter | Audit, Buryans One | 365d | email |
| identity.user.disabled | Roman / SSO | Authentik adapter | Audit, access | 365d | email |
| home.state.changed | Roman / Home | Home Assistant adapter | Buryans One | 30d | no |
| agent.task.requested | Roman / Agents | bot adapter | runner | 30d | no |
| system.service.down | Roman / SRE | monitor adapter | notification bot | 90d | no |
| system.service.up | Roman / SRE | monitor adapter | notification bot | 90d | no |
## Adapter contract
Adapter:
1. validates the CloudEvents envelope;
2. supplies a stable `idempotency_key`;
3. writes to `events.outbox` in the same transaction as its local change;
4. never publishes directly to NATS;
5. declares one event type from this matrix.
Relay owns JetStream publish. Consumer owns inbox/effect idempotency.
+59
View File
@@ -0,0 +1,59 @@
# Gate G5 — migration plan
Дата: 2026-11-29.
## Почему G5 открыт
`agent-gw` уже ходит только через Tool Gateway:
```text
agent-gw.service → 127.0.0.1:9137
direct 127.0.0.1:9120 → blocked
```
Но legacy-агенты всё ещё вызывают production напрямую:
- `hub-bots` — 9 ботов, Jellyfin/Seerr/Home/Paperless/Immich;
- `hub-agents` — `/opt/hub-agents`, status/notify;
- `hub-chief` — `/status.json`, `/notify`;
- `hub-actions` — hygiene actions.
Поэтому Gate G5 «агент не имеет production-доступа вне Tool Gateway» **не доказан для всего флота**.
## Прогресс
- `PhotoBot` мигрирован на gateway local-tools (`photo.stats`, `photo.space`);
- feature flag `HUB_GATEWAY_PHOTO=1` включён;
- `BookBot` мигрирован на gateway (`book.stats`, `book.recent`, `book.search`);
- feature flag `HUB_GATEWAY_BOOK=1` включён;
- `book.stats` через gateway: 41 книга;
- `book.recent/search` падают на `/opt/books/...` — путь сломан и в прямом режиме;
- `HomeBot` мигрирован на gateway (`home.stats`, `home.status`);
- feature flag `HUB_GATEWAY_HOME=1` включён;
- `home.stats` 646 сущностей, `home.status` 77 states;
- `DigestBot` мигрирован на gateway (`catalog.content`, `digest.index`, `prometheus.*`, `seerr.counts`);
- feature flag `HUB_GATEWAY_DIGEST=1` включён;
- digest: индекс 93, targets 35, тревоги 2; Seerr 401 — отдельная auth-проблема;
- hub-bots active, 9 ботов на связи.
## Порядок миграции
1. Добавить в Tool Gateway недостающие tools:
- `status.json.read`;
- `media.search`, `media.request`;
- `notify.send` только через approval.
2. Перевести `hub-chief`/`hub-actions` (inactive) первыми.
3. Перевести `hub-bots` по одному: MEDIA → HOME → остальные.
4. Для каждого — UID `agent-gw`/отдельный UID и firewall.
5. Контрактный тест: gateway 200, direct 000.
6. После всех — G5.
## Ограничение
`hub-bots` нельзя перевести одним изменением URL: у них разные источники и payload. Нужны отдельные tools и тесты.
## Что не делать
- не выключать MQTT/HA;
- не менять Bridge0/Bridge1;
- не трогать камеру C-01.
+32 -32
View File
@@ -1,11 +1,11 @@
# Gate readiness — G0/G1
Дата: 2026-11-26
Статус: **not ready** for blind approval
Дата: 2026-11-27
Статус: **G0 accepted, G1 accepted** (owner click, 2026-11-27)
## G0 — Stage 0
## G0 — Stage 0 — accepted
### Готово
Подтверждено:
- ADR-001 source of truth;
- service registry Tier0/1;
@@ -21,46 +21,46 @@
- restore evidence:
- Gitea 117 tables / 5 repos;
- Audit 14 tables;
- Authentik 230 tables / 9s.
- Authentik 230 tables / 9s;
- n8n 136 / 6s;
- Matrix 176 / 3s;
- Prism 21;
- Seerr integrity ok.
- Audit 360 tracker;
- secrets inventory;
- redaction.
### Не готово
Caveat:
- Gate G0 не подписан (user approval);
- caveat: Jellyfin metadata restore не выполнялся;
- S0-04 закрыт, но полный media restore drill — отдельная задача.
- Jellyfin metadata restore отдельно не проверялся.
**Решение:** G0 evidence готов; нужен только твой approve.
## G1 — Stage 1 Media Alpha — accepted
## G1 — Stage 1 Media Alpha
Подтверждено:
### Готово
- Jellyfin SSO button + login confirmed;
- Jellyfin SSO button + login;
- local non-root breakglass;
- API key via Authorization;
- Media Alpha `/alpha/`;
- search q=the → 6 items;
- recent → 6 items;
- current SSO user;
- access: Roman 200, other 403;
- breakglass ACL/revocation 3→0→3;
- 5/5 alpha live tests.
- Owner console `/alpha/owner`;
- search/recent/work/availability/editions/playback;
- requests/continue/releases/recommendations;
- **Media API 10/10**;
- ACL/revocation 3→0→3;
- idempotency 2/2;
- dashboard tests 3/3;
- Fitness 4/18 accepted until Stage 2.
### Не готово
## Что осталось
- Media API: live search/recent/me/work/availability/editions/playback; остальные 4 path не готовы;
- idempotency/duplicate effects not tested;
- Seerr requests 403;
- Gate G1 не подписан.
- `M-07` RAM — deferred;
- `M-08` интервью — deferred;
- Stage 2: события/outbox/lease/projection/cancel;
- второй Owner: нужен email для allowlist.
**Решение:** G1 не закрывать.
## Owner approval
## Что нужно Роману
- S0-10 Gate G0 — после S0-04.
- S1-10 Gate G1 — после реализации Media API.
- M-07 RAM — deferred.
- M-08 интервью — deferred.
```text
S0-10 Gate G0: done
S1-10 Gate G1: done
```
+240
View File
@@ -0,0 +1,240 @@
# Buryans Hub — Owner click guide
Для Романа и второго Owner.
Цель: за 15–20 минут понять, что работает, что нет и где подписать Gate.
**Главный экран приёмки:**
```text
http://192.168.1.10:9161/alpha/acceptance
```
Там по каждому сервису написано:
- что это;
- что открыть;
- что должно быть;
- результат автоматической проверки.
Если авто-проверка зелёная — этого достаточно, не нужно повторять всё вручную.
**Owner-пульт:**
```text
http://192.168.1.10:9161/alpha/owner
```
Крупные кнопки: Jellyfin, SSO, Audit 360, Fitness, Gitea, опросник приёмки.
---
## 1. За что отвечает каждый экран
| Экран | Адрес | За что отвечает | Что НЕ делает |
|---|---|---|---|
| Buryans One Alpha | `http://192.168.1.10:9161/alpha/` | read-only вход: статусы, поиск, новинки | не создаёт заявки, не меняет медиа |
| Jellyfin | `https://media.buryans.ru` | фильмы/сериалы, playback | не управляет Audit |
| Audit 360 | `http://192.168.1.10:9161/` | трекер спринта, evidence, Gate G0/G1 | не лечит сервисы |
| Gitea | `http://192.168.1.140:3000/` | код, PR, история решений | не media UI |
| Prism | только статус в Alpha | LLM-очередь и research | не пользовательский сервис |
| Breakglass | Jellyfin login | аварийный локальный вход | не для ежедневной работы |
---
## 2. Утренний маршрут: что кликнуть
### Шаг 1. Alpha
Открыть:
```text
http://192.168.1.10:9161/alpha/
```
Ожидаемо:
- [ ] SSO пустил;
- [ ] видна строка `read-only · <email>`;
- [ ] карточка Jellyfin = работает;
- [ ] карточка Prism показывает pending/errors;
- [ ] карточка Audit показывает done/review/open;
- [ ] карточка Fitness показывает pass/18.
Если 403 — тебя нет в allowlist. Это не поломка, см. раздел 5.
### Шаг 2. Поиск и новинки
- [ ] ввести `the` → должны появиться фильмы;
- [ ] «Недавно добавлено» показывает реальные элементы;
- [ ] открыть `work`/`availability`/`editions`, если есть ссылка;
- [ ] playback resolve ведёт в Jellyfin.
### Шаг 3. Jellyfin
Открыть:
```text
https://media.buryans.ru
```
- [ ] есть кнопка «Войти через Authentik»;
- [ ] вход проходит;
- [ ] если SSO недоступен — только тогда breakglass.
### Шаг 4. Audit 360
Открыть:
```text
http://192.168.1.10:9161/
```
- [ ] найти `S0-10 Gate G0 review`;
- [ ] статус `review_pending`;
- [ ] прочитать evidence;
- [ ] если всё ок — закрыть G0 (раздел 4);
- [ ] `S1-10` теперь `review_pending`; можно проверять после G0.
### Шаг 5. Prism
Ничего не нажимать.
Смотреть только карточку в Alpha:
- pending — сколько в очереди;
- errors — сколько ошибок;
- running — выполняется ли сейчас.
Prism — внутренний research-инструмент, не пользовательский.
---
## 3. Что означает каждый Gate
### S0-10 — Gate G0
Это приёмка базы:
- owners;
- registry;
- service cards;
- SLO;
- runbooks;
- health;
- restore;
- backups;
- Audit 360.
Это **не** «всё идеально». Это «база достаточна, можно идти дальше».
### S1-10 — Gate G1
Это приёмка Media Alpha:
- read-only Alpha;
- поиск;
- work/availability/editions/playback;
- requests/continue/releases/recommendations;
- ACL;
- idempotency.
Сейчас G1 **review_pending**: evidence готов, нужен твой клик после G0.
---
## 4. Как подписать Gate G0
1. Открыть `Audit 360`.
2. Найти `S0-10`.
3. Убедиться, что статус `review_pending`.
4. Поставить `done`.
5. Комментарий:
```text
Gate G0 approved. Jellyfin metadata restore caveat accepted.
```
Если что-то не понравилось — **не закрывать**, написать комментарий с конкретным пунктом.
---
## 5. Второй Owner: что нужно заранее
Сейчас Alpha/Audit пускают только:
```text
[email protected]
```
Второй Owner получит **403**, пока его email не добавлен.
Чтобы его пустить, нужны:
1. Его email.
2. Учётка Authentik.
3. Добавление email в allowlist Alpha/Audit.
4. Доступ к Jellyfin через Authentik/группу.
5. Тестовый вход.
Без этих шагов не считать 403 поломкой.
Не давать второму Owner:
- root;
- пароль breakglass;
- доступ к Gitea admin;
- доступ к Prism API.
---
## 6. Чего не трогать
- не менять Jellyfin users/policy;
- не менять Seerr config;
- не менять DNS/AdGuard;
- не запускать Prism-воркеры вручную;
- не делать `docker restart` без причины;
- не закрывать `S1-10` до готовности.
---
## 7. Если что-то не работает
1. Снять скриншот/URL/время.
2. Не чинить сразу.
3. Записать симптом:
- что открыл;
- что ожидал;
- что увидел;
- код ответа.
4. Передать Роману/агенту.
Аварийные ориентиры:
```text
Alpha health: 200
Alpha UI: 302 (SSO)
Audit: 200
Jellyfin SSO start: 302
```
---
## 8. Тренировочный чек-лист второго Owner
- [ ] объяснить, что Alpha read-only;
- [ ] показать разницу Alpha/Jellyfin/Audit;
- [ ] показать SSO-кнопку;
- [ ] показать, где Gate G0;
- [ ] объяснить, что G1 review_pending;
- [ ] показать, где Prism-статус, но не давать менять;
- [ ] проверить 403 до добавления email;
- [ ] добавить email;
- [ ] повторить вход;
- [ ] попросить закрыть G0 только после проверки.
---
## 9. Главное правило
> Если не понимаешь, что нажимаешь — не нажимай.
> Зафиксируй и передай.
+21
View File
@@ -0,0 +1,21 @@
version: 1
source: "stage5 model registry v0"
models:
- id: deepseek-chat
provider: deepseek
role: primary-reasoning
endpoint: "https://api.deepseek.com"
health: external
note: "ключ только на сервере"
- id: qwen2.5:3b
provider: ollama-pc
role: local-fast
endpoint: "http://192.168.1.194:11434"
health: ollama
note: "ПК, модель может быть выгружена"
- id: qwen2.5:3b
provider: ollama-host
role: local-fallback
endpoint: "http://192.168.1.10:11434"
health: ollama
note: "host fallback"
+8 -1
View File
@@ -51,7 +51,7 @@ services:
tier: 0
ct: 108
owner: roman
endpoint: "http://127.0.0.1:9120/status"
endpoint: "http://127.0.0.1:9120/health"
health: "http"
backup: "config"
restore: "config"
@@ -89,3 +89,10 @@ services:
endpoint: "http://192.168.1.108:5680/healthz"
health: "http"
note: "port 5680 -> container 5678"
- id: hub-tools
tier: 1
ct: 10
owner: roman
endpoint: "http://127.0.0.1:9137/health"
health: "http"
note: "Tool Gateway; agents must use this for tools"
@@ -0,0 +1,79 @@
version: 1
policy: "agents may use only gateway-listed tools; direct production access is forbidden"
tools:
- name: catalog.read
gateway: http://127.0.0.1:9120/catalog
mode: read
approval: false
- name: status.read
gateway: http://127.0.0.1:9120/status
mode: read
approval: false
- name: status.json.read
gateway: http://127.0.0.1:9120/status.json
mode: read
approval: false
- name: notify.send
gateway: http://127.0.0.1:9120/notify
mode: write
approval: true
- name: media.read
gateway: http://127.0.0.1:9180/v1/media
mode: read
approval: false
- name: events.read
gateway: http://127.0.0.1:9180/v1/events
mode: read
approval: false
- name: photo.stats
mode: read
local: photo_stats
approval: false
- name: photo.space
mode: read
local: photo_space
approval: false
- name: book.stats
mode: read
local: book_stats
approval: false
- name: book.recent
mode: read
local: book_recent
approval: false
- name: book.search
mode: read
local: book_search
approval: false
- name: home.stats
mode: read
local: home_stats
approval: false
- name: home.status
mode: read
local: home_status
approval: false
- name: catalog.content
mode: read
local: catalog_content
approval: false
- name: digest.index
mode: read
local: digest_index
approval: false
- name: prometheus.targets
mode: read
local: prom_targets
approval: false
- name: prometheus.alerts
mode: read
local: prom_alerts
approval: false
- name: seerr.counts
mode: read
local: seerr_counts
approval: false
- name: audit.write
gateway: http://127.0.0.1:9160/api/sprint/status
mode: write
approval: true
+23 -11
View File
@@ -24,17 +24,29 @@
| S0-07 | S0 | Resource baseline | done | | sre | Ресурсный baseline Stage0; RAM — главный дефицит. | 1 | G0 |
| S0-08 | S0 | Sidecar inventory | done | | sre | Кандидаты на консолидацию; оценка RAM по группам — Stage1. | 1 | G0 |
| S0-09 | S0 | Audit decision/experiment | done | | architect | Audit 360 decision 5 | 1 | G0 |
| S0-10 | S0 | Gate G0 review | review_pending | YES | roman | 24 done; G0 evidence · Утром прокликать Gate G0 | 2 | G0 |
| S0-10 | S0 | Gate G0 review | done | | roman | owner acceptance 2026-11-27 · Утром прокликать Gate G0 | 4 | G0 |
| S1-01 | S1 | ADR-004 Media First stage order | done | | architect | Порядок стадий зафиксирован. | 1 | G1 |
| S1-02 | S1 | Seerr read-only audit | done | | integrator | Не пересоздавать CT; сначала интеграционный тест. | 1 | G1 |
| S1-03 | S1 | NATS JetStream runtime test | done | | integrator | AUDIT_TEST stream; publish/consume/ack ok | 4 | G1 |
| S1-04 | S1 | Media identity v2 | done | | archivist | Identity model v2 draft. | 1 | G1 |
| S1-05 | S1 | Media API contract | in_progress | | architect | 11/11 paths; idempotency 2/2 | 10 | G1 |
| S1-05 | S1 | Media API contract | done | | architect | 10/10 endpoints 200; 3/3 tests | 14 | G1 |
| S1-06 | S1 | Alpha read-only UI | done | | product | System/Info 200 with Authorization; X-Emby-Token 401 · Выдать валидный Jellyfin API key или пользовательский токен | 2 | G1 |
| S1-07 | S1 | Fitness functions | in_progress | | qa | /v1/fitness pass 3/18 | 7 | G1 |
| S1-07 | S1 | Fitness functions | done | | qa | Owner approval; /v1/fitness 4/18 | 9 | G1 |
| S1-08 | S1 | ACL/revocation tests | done | | security | 3 -> 0 -> 3 views; login true | 5 | G1 |
| S1-09 | S1 | Secret scan/redaction | done | | security | secret_scan 0; redaction residual 0 | 5 | G1 |
| S1-10 | S1 | Gate G1 review | waiting_user | YES | roman | open · Подтвердить Gate G1 | 0 | G1 |
| S1-10 | S1 | Gate G1 review | done | | roman | owner acceptance; 10/10 media · Утром прокликать Gate G1 | 3 | G1 |
| S2-01 | S2 | CloudEvents envelope v1 | done | | architect | contracts/events/envelope-v1.json | 0 | |
| S2-02 | S2 | Outbox schema + enqueue | done | | architect | ops/events/schema.sql; enqueue | 0 | |
| S2-03 | S2 | Inbox + effects idempotency | done | | architect | repeat_test 100→1 | 0 | |
| S2-04 | S2 | NATS JetStream relay | done | | architect | enqueue1 relayed1 processed1; inbox/effects 1 | 1 | |
| S2-05 | S2 | Adapters + ownership matrix | done | | architect | pipeline active; jellyfin 7 events; ownership.yaml | 3 | |
| S2-06 | S2 | pgvector pilot | done | | architect | nearest pilot-a, top2 pilot-a/pilot-c | 1 | |
| S2-07 | S2 | Gate G2 proof | done | YES | architect | 100→1; loss recovered | 1 | G2 |
| S3-01 | S3 | Аудит RU/direct-play | done | | architect | /v1/media/coverage | 0 | |
| S3-02 | S3 | RU-дорожки/субтитры | blocked | | architect | Bazarr status200; login TLS error; no RU | 5 | |
| S3-03 | S3 | Direct-play 7/7 | done | | architect | coverage total6 direct6 | 2 | |
| S3-04 | S3 | Запрос из Alpha/Telegram/Matrix | done | | architect | /alpha/request; !request; request/check | 5 | |
| S3-05 | S3 | Gate G3 | open | YES | architect | pending | 0 | G3 |
| U-01 | U | Approve PR #192 | done | | roman | chat approval 2026-11-26 · Открыть PR #192 и подтвердить архитектуру | 2 | none |
| U-02 | U | Seerr vs Jellyseerr decision | dropped | YES | roman | Seerr audit · Выбрать после evidence | 2 | none |
| U-03 | U | RAM/GPU/disk data | dropped | YES | roman | resource baseline · Прислать/подтвердить параметры | 2 | none |
@@ -45,18 +57,18 @@
- M / deferred: 2
- M / done: 7
- S0 / done: 9
- S0 / review_pending: 1
- S1 / done: 7
- S1 / in_progress: 2
- S1 / waiting_user: 1
- S0 / done: 10
- S1 / done: 10
- S2 / done: 7
- S3 / blocked: 1
- S3 / done: 3
- S3 / open: 1
- U / done: 2
- U / dropped: 3
## Пользовательская очередь
- **S0-10** — Gate G0 review: Утром прокликать Gate G0
- **S1-10** — Gate G1 review: Подтвердить Gate G1
- **S3-05** — Gate G3:
- **U-02** — Seerr vs Jellyseerr decision: Выбрать после evidence
- **U-03** — RAM/GPU/disk data: Прислать/подтвердить параметры
- **U-04** — Approve Stage1 write actions: Разрешить только после Gate G1
+115
View File
@@ -0,0 +1,115 @@
# Stage 2 — Event & Data
Статус: начат 2026-11-27.
Gate G2: повтор события 100 раз = один эффект; потеря webhook восстанавливается.
## Инкремент 1 — deterministic core (сделано)
- `contracts/events/envelope-v1.json` — CloudEvents envelope.
- `ops/events/schema.sql` — `events.outbox`, `events.inbox`, `events.effects`.
- `ops/events/event_store.py` — enqueue, consume, repeat_test.
- `repeat_test`: 100 повторов одного события → `first_effects=1`, `effects=1`.
## Задачи
| Код | Задача | Статус |
|---|---|---|
| S2-01 | CloudEvents envelope v1 | done |
| S2-02 | Outbox schema + enqueue | done |
| S2-03 | Inbox + effects idempotency | done |
| S2-04 | NATS JetStream relay | done |
| S2-05 | Adapters: Audit360/Jellyfin/Seerr | done |
| S2-06 | pgvector pilot | done (synthetic infrastructure) |
| S2-07 | Gate G2 proof | done |
## Проверка
```bash
cd /root/buryan-infra
python3 ops/events/event_store.py
```
Ожидаемо:
```json
{"workers": 100, "first_effects": 1, "effects": 1}
```
## NATS e2e evidence
```text
enqueue 1
relayed 1
processed 1
outbox published
inbox processed
effects event_observed
```
NATS: `nats://192.168.1.115:4222`
Stream: `BURYANS_EVENTS`
Consumer: `buryans-worker`
## Gate G2 evidence
```json
{
"duplicate_messages": 100,
"inbox": 1,
"effects": 1,
"one_effect": true,
"loss_pending_before": "pending",
"loss_published_after": "published",
"loss_effects": 1,
"recovered": true
}
```
## pgvector pilot
```json
{"extension":"vector","pilot":"synthetic-3d","nearest":"pilot-a","top2":["pilot-a","pilot-c"]}
```
Важно: это инфраструктурный пилот, не production semantic search.
## Durable pipeline
Сервис:
```text
events-pipeline.service
```
Делает:
1. Audit 360 adapter → outbox;
2. outbox → NATS JetStream;
3. NATS → idempotent inbox/effects;
4. повторяет каждые 5 секунд.
Факт:
```text
outbox published = 43
pending = 0
inbox = 46
effects = 45
```
## Adapters
- Audit 360 — real;
- Jellyfin — real, 7 events emitted and consumed;
- Seerr — real read-only session adapter (0 requests currently, valid empty).
Примечание: `rag` в SQL_ASCII, поэтому кириллица в payload передаётся
как `title_utf8_b64`; ASCII-поле `title_ascii` остаётся для совместимости.
## Следующий инкремент
NATS JetStream:
- outbox relay;
- stream + durable consumer;
- ack/redelivery;
- тест потери webhook.
+109
View File
@@ -0,0 +1,109 @@
# Stage 3 — Media Product
Статус: начат 2026-11-27.
Gate G3: семья делает запрос → смотрит с RU-озвучкой; 0 дублей.
## Факт на старте
Jellyfin:
```text
всего медиа 6
RU audio 0
RU субтитры 0
direct-play 6
```
Direct-play исправлен: сериал считается по эпизодам, BoxSet исключён из playable-медиа.
Это честный gap, не «всё хорошо».
Проверка диска: `.srt/.ass/.vtt` нет; имён `rus/russian` нет.
Значит RU-контента нет и вне индекса Jellyfin.
## Bazarr: RU-источник
- RU-профиль `Русский + English` существует;
- Dune/Interstellar получили профиль 1;
- subf2m исправлен User-Agent;
- throttle-файл сброшен;
- но RU-файл всё равно не скачался.
Бэкап конфига:
```text
/opt/bazarr/config/config/config.yaml.bak-subf2m-20261127
/opt/bazarr/config/config/config.yaml.bak-opensubtitles-20261127
```
## OpenSubtitles API
Ключ лежит только на хосте:
```text
/root/.opensubtitles-key (600)
```
Проверено:
- поиск RU работает: 23 варианта для Dune;
- прямой download link отдаёт файл очень медленно и обрывается;
- Bazarr `opensubtitlescom` настроен с username/password + API key;
- из контейнера Bazarr login падает по TLS (`SSLEOFError`), subf2m таймаутит.
Поэтому RU-файл пока не установлен. Обрезанный `.srt` не используется.
Секреты:
```text
/root/.opensubtitles-key
/root/.opensubtitles-user
/root/.opensubtitles-pass
```
## Задачи
| Код | Задача | Статус |
|---|---|---|
| S3-01 | Аудит RU/direct-play | done (0/6 RU, 6/6 direct) |
| S3-02 | RU-дорожки/субтитры | blocked: Bazarr RU профиль есть, subf2m не отдал файл |
| S3-03 | Direct-play 6/6 | done |
| S3-04 | Запрос из Alpha/Matrix | done (Telegram исключён по решению) |
| S3-05 | Gate G3 | open |
## Проверка
```text
http://192.168.1.10:9161/alpha/acceptance
```
Карточка «RU-озвучка» сейчас **FAIL** — специально, пока нет RU-дорожек.
```text
GET /v1/media/coverage
```
Запрос из Alpha:
```text
http://192.168.1.10:9161/alpha/request
```
Alpha ищет по Jellyfin; кнопка открывает Seerr. Alpha не пишет в Seerr/медиатеку.
Matrix:
```text
!request Дюна
```
Бот даёт ссылку на `https://requests.buryans.ru`, заявку создаёт семья в Seerr.
Telegram-бота в текущем контуре нет.
Проверка дублей:
```text
GET /v1/media/request/check?q=Дюна
```
Alpha показывает предупреждение, если заявка уже есть в Seerr.
+43
View File
@@ -0,0 +1,43 @@
# Stage 4 — Mission Control & SDK
Статус: **Gate G4 закрыт** 2026-11-27.
## Сделано
- Mission Control v0: `/alpha/mission`; 11/11 сервисов up.
- Adapter SDK: `ops/events/adapter_plugins/base.py`; `poll(conn)`.
- Auto-discovery: `registry.py`; новый файл = новый адаптер.
- 4 адаптера: audit360, jellyfin, seerr, gitea-health.
- Contract tests: 3/3 OK.
- Preview: `preview_adapters.py`.
- Gate G4: Gitea-health добавлен файлом, ядро pipeline не менялось.
## Доказательства
```text
preview_adapters.py
audit360 poll=callable
gitea-health poll=callable
jellyfin poll=callable
seerr poll=callable
total=4
unittest: Ran 3 tests ... OK
pipeline: tick emitted={'audit360': 0, 'gitea-health': 0, 'jellyfin': 0, 'seerr': 0}
gitea first tick: emitted 1, relayed 1, consumed 1
```
## Задачи
| Код | Задача | Статус |
|---|---|---|
| S4-01 | Mission Control v0 | done |
| S4-02 | Extension SDK | done |
| S4-03 | 3+ adapters | done (4) |
| S4-04 | Preview + contract tests | done |
| S4-05 | Gate G4 | done |
## Ограничения
- Mission Control внутри Alpha, не отдельный Nexus.
- Публичный Matrix/Element (`matrix.buryans.ru`, VPS `193.233.210.184`) недоступен; боты работают через локальный Synapse.
+110
View File
@@ -0,0 +1,110 @@
# Stage 5 — AI Factory & Agents
Статус: начат 2026-11-27.
Gate G5: агент не имеет production-доступа вне Tool Gateway.
## Сделано
Model Registry v0:
```text
http://192.168.1.10:9161/alpha/models
GET /v1/models
```
- реестр моделей/провайдеров;
- external/Ollama health;
- PC-Ollama offline показывается как down;
- без выдачи агентам production-доступа.
## Задачи
| Код | Задача | Статус |
|---|---|---|
| S5-01 | Model Registry v0 | done |
| S5-02 | GPU/model leases | done: model lease broker + limits; GPU-планировщика нет |
| S5-03 | Evals / golden set | done: baseline 1/10, runner+golden set |
| S5-04 | Memory | done: SQLite namespaced memory + TTL/search, tests 3/3 |
| S5-05 | Night Shift | done: timers 00:00/07:30, llm-night-start/stop |
| S5-06 | Tool Gateway / agent approvals | done: agent-gw enforced + approval queue; legacy migration = G5 |
| S5-07 | Gate G5 | in_progress: Photo+Book+Home+Digest migrated; остальные direct |
## Tool Gateway runtime
```text
hub-tools.service → 127.0.0.1:9137
GET /health
GET /v1/tools
GET /v1/call?tool=...
POST /v1/call (write + X-Approval: approved)
```
Проверено:
```text
gateway_call=200
tools=6
gateway_agent.py: catalog.read через gateway, direct prod не используется
```
## Evals
Golden set: `ops/ai/evals/golden.yaml` (5 вопросов).
Runner: `ops/ai/evals/eval_runner.py`.
Baseline на локальной `qwen2.5:3b`:
```text
score=1/10
```
Это не «модель готова», а зафиксированный baseline: qwen2.5:3b плохо знает домен Buryans.
## Night Shift
```text
llm-night-start.timer → 00:00
llm-night-stop.timer → 07:30
[email protected] → LLM workers
```
Проверено: таймеры в списке, сервисы запускаются.
## Memory
`ops/ai/memory.py`:
```text
namespace + key + value + source
TTL
search
SQLite /var/lib/hub-memory/memory.db
```
Тесты: 3/3 OK.
## Model leases
```text
GET /v1/models
POST /v1/leases
POST /v1/leases/release
GET /v1/leases
```
Проверено:
```text
deepseek-chat → 201 lease
qwen2.5:3b (offline) → 409 model unavailable
model busy / agent lease limit → 409
```
GPU-планировщика и реального выделения GPU нет; это model lease broker.
## Ограничение
- GPU-планировщик и реальное распределение GPU ещё не реализованы.
- Evals, memory не реализованы.
- Агенты ещё не переключены на Tool Gateway; Gate G5 не закрыт.
- Model Registry read-only, не выдаёт доступ к моделям.
@@ -0,0 +1,56 @@
# Tool Gateway enforcement — reference agent
Дата: 2026-11-29.
## Что сделано
- создан системный пользователь `agent-gw` (UID 999);
- его единственный разрешённый TCP egress — `127.0.0.1:9137`;
- DNS UDP 53 разрешён;
- остальное — `REJECT`;
- агент запускается как `agent-gw` и ходит только через Tool Gateway.
## Approvals
Write-tools требуют не строку `approved`, а ID из approval queue:
```text
POST /v1/approvals → pending id
POST /v1/approvals/decision → approved/denied
POST /v1/call + X-Approval:id
```
Проверка: create=201, decision approved, write без ID=403.
## Production-style agent
```text
agent-gw.service
User=agent-gw
catalog.read every 5 min via 127.0.0.1:9137
log: /var/lib/agent-gw/agent.log
```
Проверка:
```text
systemctl is-active agent-gw → active
{"tool":"catalog.read","bytes":6884}
runuser -u agent-gw -- curl http://127.0.0.1:9120/catalog
direct=000
```
## Ограничение
Это enforcement для reference-агента.
Production-агенты (`hub-bots`, `hub-agents`) ещё не переведены; Gate G5 не закрыт.
## Откат
```text
iptables -D OUTPUT -m owner --uid-owner 999 -j AGENT_GW_OUT
iptables -F AGENT_GW_OUT
iptables -X AGENT_GW_OUT
userdel agent-gw
```
+41 -27
View File
@@ -1,6 +1,6 @@
# Индекс документации
Сгенерировано: 2026-11-27 06:50 · файлов: **952** · генератор: `ops/scripts/build_docs_index.py`
Сгенерировано: 2026-11-29 06:50 · файлов: **970** · генератор: `ops/scripts/build_docs_index.py`
Навигация по каталогам. Свежие файлы — сверху.
@@ -76,11 +76,13 @@
|---|---|---|
| [IDENTITY-MEDIA-GRAPH-ADR-2026-11-24.md](ops/architecture/IDENTITY-MEDIA-GRAPH-ADR-2026-11-24.md) | ADR: Identity & Media Graph для Buryans Hub | 24.11 |
## ops/audit — 73 файлов (10 за неделю)
## ops/audit — 75 файлов (10 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [STANDARD-STATUS.md](ops/audit/STANDARD-STATUS.md) | Соответствие единому стандарту | 27.11 |
| [STANDARD-STATUS.md](ops/audit/STANDARD-STATUS.md) | Соответствие единому стандарту | 29.11 |
| [snapshot-2026-11-28.md](ops/audit/snapshot-2026-11-28.md) | Снимок состояния: 2026-11-28 | 28.11 |
| [snapshot-2026-11-27.md](ops/audit/snapshot-2026-11-27.md) | Снимок состояния: 2026-11-27 | 27.11 |
| [BURYANS-HUB-FULL.md](ops/audit/BURYANS-HUB-FULL.md) | Buryans Hub — полный аудит и ТЗ для агентов | 26.11 |
| [README.md](ops/audit/README.md) | Audit 360 | 26.11 |
| [snapshot-2026-11-26.md](ops/audit/snapshot-2026-11-26.md) | Снимок состояния: 2026-11-26 | 26.11 |
@@ -118,14 +120,14 @@
| [snapshot-2026-10-25.md](ops/audit/snapshot-2026-10-25.md) | Снимок состояния: 2026-10-25 | 25.10 |
| [snapshot-2026-10-24.md](ops/audit/snapshot-2026-10-24.md) | Снимок состояния: 2026-10-24 | 24.10 |
| [snapshot-2026-10-23.md](ops/audit/snapshot-2026-10-23.md) | Снимок состояния: 2026-10-23 | 23.10 |
| [snapshot-2026-10-22.md](ops/audit/snapshot-2026-10-22.md) | Снимок состояния: 2026-10-22 | 22.10 |
| [AUDIT-2026-10-21-VISION.md](ops/audit/AUDIT-2026-10-21-VISION.md) | Аудит развития Buryans Hub | 21.10 |
| … ещё 33 | | |
| … ещё 35 | | |
## ops/audit/reports — 10 файлов (10 за неделю)
## ops/audit/reports — 12 файлов (12 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [AUDIT-360-13.md](ops/audit/reports/AUDIT-360-13.md) | Audit 360 — Buryans Hub + Prism | 29.11 |
| [AUDIT-360-12.md](ops/audit/reports/AUDIT-360-12.md) | Audit 360 — Buryans Hub + Prism | 28.11 |
| [AUDIT-360-11.md](ops/audit/reports/AUDIT-360-11.md) | Audit 360 — Buryans Hub + Prism | 27.11 |
| [AUDIT-360-10.md](ops/audit/reports/AUDIT-360-10.md) | Audit 360 — Buryans Hub + Prism | 26.11 |
| [AUDIT-360-9.md](ops/audit/reports/AUDIT-360-9.md) | Audit 360 — Buryans Hub + Prism | 26.11 |
@@ -137,10 +139,13 @@
| [AUDIT-360-3.md](ops/audit/reports/AUDIT-360-3.md) | Audit 360 — Buryans Hub + Prism | 26.11 |
| [AUDIT-360-1.md](ops/audit/reports/AUDIT-360-1.md) | Audit 360 — Buryans Hub + Prism | 26.11 |
## ops/audits — 98 файлов (17 за неделю)
## ops/audits — 101 файлов (18 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [net-report-2026-11-28.md](ops/audits/net-report-2026-11-28.md) | Связь за 2026-11-28 | 28.11 |
| [night-2026-11-28.md](ops/audits/night-2026-11-28.md) | Ночь: связь до VDS (2026-11-28) | 28.11 |
| [night-2026-11-27.md](ops/audits/night-2026-11-27.md) | Ночь: связь до VDS (2026-11-27) | 27.11 |
| [night-2026-11-26.md](ops/audits/night-2026-11-26.md) | Ночь: связь до VDS (2026-11-26) | 26.11 |
| [night-2026-11-25.md](ops/audits/night-2026-11-25.md) | Ночь: связь до VDS (2026-11-25) | 25.11 |
| [net-report-2026-11-25.md](ops/audits/net-report-2026-11-25.md) | Связь за 2026-11-25 | 25.11 |
@@ -178,10 +183,7 @@
| [AUDIT-LEDGER-2026-11-17.md](ops/audits/AUDIT-LEDGER-2026-11-17.md) | Audit Ledger: аудит Tool Gateway в Postgres (17.11.2026) | 17.11 |
| [P0-BOOKS-POLINA-2026-11-17.md](ops/audits/P0-BOOKS-POLINA-2026-11-17.md) | P0: книги, Polina, свет (17.11.2026) | 17.11 |
| [P0-CONTINUE-2026-11-17.md](ops/audits/P0-CONTINUE-2026-11-17.md) | P0 продолжение: книги, медиа, лимиты (17.11.2026) | 17.11 |
| [EVENING-SPRINT-2026-11-17.md](ops/audits/EVENING-SPRINT-2026-11-17.md) | Вечерний спринт: P0 и ускорение LLM (17.11.2026) | 17.11 |
| [P0-TOOLS-2026-11-17.md](ops/audits/P0-TOOLS-2026-11-17.md) | P0-инструменты: ha.search, media.search, media.request (17.11.2026) | 17.11 |
| [LLM-TOOL-AUDIT-2026-11-17.md](ops/audits/LLM-TOOL-AUDIT-2026-11-17.md) | LLM-аудит Tool Gateway (предложение, требует проверки) | 17.11 |
| … ещё 58 | | |
| … ещё 61 | | |
## ops/audits/eval/2026-11-17 — 1 файлов (0 за неделю)
@@ -236,19 +238,19 @@
|---|---|---|
| [README.md](ops/boot/README.md) | Автовосстановление после перезагрузки (boot orchestrator) | 06.11 |
## ops/bots — 7 файлов (0 за неделю)
## ops/bots — 7 файлов (1 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [BOT-COMMANDS.md](ops/bots/BOT-COMMANDS.md) | Команды ботов (актуальный список) | 27.11 |
| [MATRIX-BOTS.md](ops/bots/MATRIX-BOTS.md) | Боты в Matrix: архитектура | 23.10 |
| [RESILIENCE.md](ops/bots/RESILIENCE.md) | Устойчивость ботов: что если сервис недоступен | 19.10 |
| [PERFORMANCE.md](ops/bots/PERFORMANCE.md) | Скорость ответов ботов | 19.10 |
| [RULES.md](ops/bots/RULES.md) | Разбор фраз без LLM | 19.10 |
| [GAPS.md](ops/bots/GAPS.md) | Команда «!gaps»: что мешает системе работать целиком | 19.10 |
| [BOT-COMMANDS.md](ops/bots/BOT-COMMANDS.md) | Команды ботов (актуальный список) | 19.10 |
| [README.md](ops/bots/README.md) | Флот Matrix-ботов | 19.10 |
## ops/combine — 28 файлов (1 за неделю)
## ops/combine — 28 файлов (0 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
@@ -293,7 +295,7 @@
| Документ | О чём | Изменён |
|---|---|---|
| [REPORT.md](ops/combine/staging/ingest-pc-clean/REPORT.md) | Ingest report | 27.11 |
| [REPORT.md](ops/combine/staging/ingest-pc-clean/REPORT.md) | Ingest report | 29.11 |
## ops/creds — 1 файлов (0 за неделю)
@@ -319,10 +321,20 @@
|---|---|---|
| [DIGEST.md](ops/digest/DIGEST.md) | Дайджест «Что нового» | 21.10 |
## ops/evolution — 45 файлов (14 за неделю)
## ops/events — 1 файлов (1 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [README.md](ops/events/README.md) | Buryans events — Stage 2 core | 27.11 |
## ops/evolution — 49 файлов (14 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [research-2026-11-28.md](ops/evolution/research-2026-11-28.md) | Живое исследование альтернатив — 2026-11-28 | 28.11 |
| [report-2026-11-28.md](ops/evolution/report-2026-11-28.md) | Отчёт развития — 2026-11-28 | 28.11 |
| [research-2026-11-27.md](ops/evolution/research-2026-11-27.md) | Живое исследование альтернатив — 2026-11-27 | 27.11 |
| [report-2026-11-27.md](ops/evolution/report-2026-11-27.md) | Отчёт развития — 2026-11-27 | 27.11 |
| [research-2026-11-26.md](ops/evolution/research-2026-11-26.md) | Живое исследование альтернатив — 2026-11-26 | 26.11 |
| [report-2026-11-26.md](ops/evolution/report-2026-11-26.md) | Отчёт развития — 2026-11-26 | 26.11 |
| [research-2026-11-25.md](ops/evolution/research-2026-11-25.md) | Живое исследование альтернатив — 2026-11-25 | 25.11 |
@@ -359,11 +371,7 @@
| [report-2026-11-10.md](ops/evolution/report-2026-11-10.md) | Отчёт развития — 2026-11-10 | 10.11 |
| [research-2026-11-09.md](ops/evolution/research-2026-11-09.md) | Живое исследование альтернатив — 2026-11-09 | 09.11 |
| [report-2026-11-09.md](ops/evolution/report-2026-11-09.md) | Отчёт развития — 2026-11-09 | 09.11 |
| [research-2026-11-08.md](ops/evolution/research-2026-11-08.md) | Живое исследование альтернатив — 2026-11-08 | 08.11 |
| [report-2026-11-08.md](ops/evolution/report-2026-11-08.md) | Отчёт развития — 2026-11-08 | 08.11 |
| [research-2026-11-07.md](ops/evolution/research-2026-11-07.md) | Живое исследование альтернатив — 2026-11-07 | 07.11 |
| [report-2026-11-07.md](ops/evolution/report-2026-11-07.md) | Отчёт развития — 2026-11-07 | 07.11 |
| … ещё 5 | | |
| … ещё 9 | | |
## ops/frigate — 3 файлов (0 за неделю)
@@ -415,7 +423,7 @@
| [README-2026-09.md](ops/history/legacy-hub/README-2026-09.md) | 🏰 Buryan Hub — Self-Healing Home Infrastructure | 06.11 |
| [CONTEXT-2026-09.md](ops/history/legacy-hub/CONTEXT-2026-09.md) | 🤖 Контекст для AI-агентов | 06.11 |
## ops/home — 29 файлов (3 за неделю)
## ops/home — 29 файлов (1 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
@@ -572,10 +580,12 @@
| [SELFTEST.md](ops/hub-core/llm/SELFTEST.md) | Проверка LLM-адаптера на фразах | 19.10 |
| [README.md](ops/hub-core/llm/README.md) | LLM-адаптер | 19.10 |
## ops/hygiene — 23 файлов (7 за неделю)
## ops/hygiene — 25 файлов (7 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [report-2026-11-28.md](ops/hygiene/report-2026-11-28.md) | Гигиенический отчёт — 2026-11-28 | 28.11 |
| [report-2026-11-27.md](ops/hygiene/report-2026-11-27.md) | Гигиенический отчёт — 2026-11-27 | 27.11 |
| [report-2026-11-26.md](ops/hygiene/report-2026-11-26.md) | Гигиенический отчёт — 2026-11-26 | 26.11 |
| [report-2026-11-25.md](ops/hygiene/report-2026-11-25.md) | Гигиенический отчёт — 2026-11-25 | 25.11 |
| [report-2026-11-24.md](ops/hygiene/report-2026-11-24.md) | Гигиенический отчёт — 2026-11-24 | 24.11 |
@@ -775,10 +785,12 @@
|---|---|---|
| [APPS.md](ops/nextcloud/APPS.md) | Nextcloud: приложения | 20.10 |
## ops/night — 21 файлов (6 за неделю)
## ops/night — 23 файлов (6 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [report-2026-11-29.md](ops/night/report-2026-11-29.md) | Ночной анализ — 2026-11-29 | 29.11 |
| [report-2026-11-28.md](ops/night/report-2026-11-28.md) | Ночной анализ — 2026-11-28 | 28.11 |
| [report-2026-11-27.md](ops/night/report-2026-11-27.md) | Ночной анализ — 2026-11-27 | 27.11 |
| [report-2026-11-26.md](ops/night/report-2026-11-26.md) | Ночной анализ — 2026-11-26 | 26.11 |
| [report-2026-11-25.md](ops/night/report-2026-11-25.md) | Ночной анализ — 2026-11-25 | 25.11 |
@@ -1067,7 +1079,7 @@
|---|---|---|
| [vault-sso-fix-report.md](ops/sprintB/vault-sso-fix-report.md) | Vaultwarden SSO Fix — Report | 25.09 |
## ops/sso — 26 файлов (1 за неделю)
## ops/sso — 26 файлов (0 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
@@ -1175,10 +1187,12 @@
|---|---|---|
| [ledger.md](ops/topology/ledger.md) | Лёджер сервисов (V1, Фаза A) | 06.11 |
## ops/trust — 22 файлов (7 за неделю)
## ops/trust — 24 файлов (7 за неделю)
| Документ | О чём | Изменён |
|---|---|---|
| [report-2026-11-28.md](ops/trust/report-2026-11-28.md) | Статистика доверия агента — 2026-11-28 | 28.11 |
| [report-2026-11-27.md](ops/trust/report-2026-11-27.md) | Статистика доверия агента — 2026-11-27 | 27.11 |
| [report-2026-11-26.md](ops/trust/report-2026-11-26.md) | Статистика доверия агента — 2026-11-26 | 26.11 |
| [report-2026-11-25.md](ops/trust/report-2026-11-25.md) | Статистика доверия агента — 2026-11-25 | 25.11 |
| [report-2026-11-24.md](ops/trust/report-2026-11-24.md) | Статистика доверия агента — 2026-11-24 | 24.11 |
+17
View File
@@ -0,0 +1,17 @@
[Unit]
Description=Buryans gateway-only agent
After=network.target hub-tools.service
Wants=hub-tools.service
[Service]
Type=simple
User=agent-gw
Group=agent-gw
ExecStart=/usr/bin/python3 /opt/agent-gw/service.py
Restart=always
RestartSec=10
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
set -e
id agent-gw >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin agent-gw
UIDG=$(id -u agent-gw)
mkdir -p /opt/agent-gw
cp /root/buryan-infra/ops/ai/gateway_agent.py /opt/agent-gw/agent.py
chown -R agent-gw:agent-gw /opt/agent-gw
chmod 755 /opt/agent-gw /opt/agent-gw/agent.py
iptables-save > /root/iptables-before-agentgw-20261129.rules 2>/dev/null || true
iptables -N AGENT_GW_OUT 2>/dev/null || true
iptables -F AGENT_GW_OUT
iptables -A AGENT_GW_OUT -o lo -p tcp --dport 9137 -j ACCEPT
iptables -A AGENT_GW_OUT -p udp --dport 53 -j ACCEPT
iptables -A AGENT_GW_OUT -j REJECT
iptables -C OUTPUT -m owner --uid-owner "$UIDG" -j AGENT_GW_OUT 2>/dev/null || iptables -I OUTPUT 1 -m owner --uid-owner "$UIDG" -j AGENT_GW_OUT
iptables-save > /etc/iptables/rules.v4 2>/dev/null || true
echo "uid=$UIDG"
echo '--- gateway as agent'
sudo -u agent-gw /usr/bin/python3 /opt/agent-gw/agent.py 2>&1 | tail -3
echo '--- direct as agent'
sudo -u agent-gw curl -sS -o /dev/null -w 'direct=%{http_code}\n' --max-time 3 http://127.0.0.1:9120/catalog 2>&1 | tail -2 || true
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Production-style gateway-only agent: catalog read every 5 minutes."""
import json, time, urllib.request
from pathlib import Path
BASE = "http://127.0.0.1:9137"
LOG = Path("/var/lib/agent-gw/agent.log")
def call(tool):
with urllib.request.urlopen(BASE + "/v1/call?tool=" + tool, timeout=10) as r:
return json.loads(r.read().decode())
def main():
LOG.parent.mkdir(parents=True, exist_ok=True)
while True:
try:
d = call("catalog.read")
with LOG.open("a") as f:
f.write(json.dumps({"ts": time.time(), "tool": "catalog.read",
"bytes": len(d.get("body") or "")}) + "\n")
except Exception as e:
with LOG.open("a") as f:
f.write(json.dumps({"ts": time.time(), "error": str(e)[:200]}) + "\n")
time.sleep(300)
if __name__ == "__main__":
main()
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Golden-set eval against an Ollama-compatible endpoint."""
import argparse, json, sys, urllib.request, yaml
def chat(base, model, prompt):
req = urllib.request.Request(base.rstrip('/') + '/api/chat',
data=json.dumps({"model": model, "stream": False,
"messages": [{"role": "user", "content": prompt}]}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=180) as r:
d = json.load(r)
return (d.get("message") or {}).get("content", "")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="http://127.0.0.1:11434")
ap.add_argument("--golden", default="ops/ai/evals/golden.yaml")
a = ap.parse_args()
data = yaml.safe_load(open(a.golden))
rows = []
for c in data["cases"]:
try:
ans = chat(a.base_url, data["model"], c["prompt"])
low = ans.lower()
hits = [k for k in c["must"] if k.lower() in low]
rows.append({"id": c["id"], "score": len(hits), "max": len(c["must"]),
"hits": hits, "answer": ans[:500]})
except Exception as e:
rows.append({"id": c["id"], "score": 0, "max": len(c["must"]),
"error": str(e)[:200]})
total = sum(x["score"] for x in rows); mx = sum(x["max"] for x in rows)
out = {"base_url": a.base_url, "model": data["model"],
"score": total, "max": mx, "rows": rows}
print(json.dumps(out, ensure_ascii=False, indent=2))
sys.exit(0 if total == mx else 1)
if __name__ == "__main__":
main()
+18
View File
@@ -0,0 +1,18 @@
version: 1
model: qwen2.5:3b
cases:
- id: event-bus
prompt: "Назови транспорт событий Buryans Hub. Ответь одним предложением."
must: ["nats", "jetstream"]
- id: event-store
prompt: "Где Buryans Hub хранит события? Ответь одним предложением."
must: ["postgres", "схем"]
- id: media
prompt: "Какой медиасервер используется в Buryans Hub? Ответь одним словом."
must: ["jellyfin"]
- id: audit
prompt: "Что делает Audit 360 в Buryans Hub? Ответь коротко."
must: ["аудит", "задач"]
- id: sso
prompt: "Какой сервис отвечает за единый вход? Ответь одним словом."
must: ["authentik"]
+37
View File
@@ -0,0 +1,37 @@
[
{
"id": "event-bus",
"score": 0,
"max": 2,
"answer": "Buryans Hub - это транспортное событие, организованное компанией Buryans для привлечения внимания к своему новому транспортному маршруту.",
"hits": ""
},
{
"id": "event-store",
"score": 0,
"max": 2,
"answer": "Buryans Hub хранит события в базе данных.",
"hits": ""
},
{
"id": "media",
"score": 0,
"max": 1,
"answer": "AWS",
"hits": ""
},
{
"id": "audit",
"score": 1,
"max": 2,
"answer": "Audit 360 в Buryans Hub помогает проводить аудит безопасности и корпоративной ответственности в облачных средах.",
"hits": "аудит"
},
{
"id": "sso",
"score": 0,
"max": 1,
"answer": "AcsIdentityManager",
"hits": ""
}
]
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Smoke agent: only Tool Gateway, no direct production URLs."""
import json
import urllib.request
BASE = "http://127.0.0.1:9137"
def call(tool, method="GET", body=None, approval=None):
req = urllib.request.Request(BASE + "/v1/call?tool=" + tool, method=method)
if body is not None:
req.data = json.dumps(body).encode()
req.add_header("Content-Type", "application/json")
if approval:
req.add_header("X-Approval", approval)
with urllib.request.urlopen(req, timeout=10) as r:
return json.loads(r.read().decode())
if __name__ == "__main__":
d = call("catalog.read")
print("gateway_agent_ok", d.get("tool"), len(d.get("body") or ""))
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=Buryans Tool Gateway
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /root/buryan-infra/ops/ai/tool_gateway_server.py
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Buryans agent memory: namespaced key/value with TTL and search."""
import argparse, json, os, sqlite3, time
from pathlib import Path
DB = os.environ.get("HUB_MEMORY_DB", "/var/lib/hub-memory/memory.db")
def connect(db=None):
db = db or DB
Path(db).parent.mkdir(parents=True, exist_ok=True)
c = sqlite3.connect(db)
c.execute("""create table if not exists memory(
namespace text not null, key text not null, value text not null,
source text default '', updated_at real not null, expires_at real,
primary key(namespace,key))""")
return c
def put(namespace, key, value, source="", ttl=None, db=None):
now = time.time()
exp = now + ttl if ttl else None
with connect(db) as c:
c.execute("""insert into memory(namespace,key,value,source,updated_at,expires_at)
values(?,?,?,?,?,?)
on conflict(namespace,key) do update set value=excluded.value,
source=excluded.source, updated_at=excluded.updated_at, expires_at=excluded.expires_at""",
(namespace, key, value, source, now, exp))
return {"namespace": namespace, "key": key, "expires_at": exp}
def get(namespace, key, db=None):
with connect(db) as c:
r = c.execute("select value,source,updated_at,expires_at from memory where namespace=? and key=?",
(namespace, key)).fetchone()
if not r:
return None
if r[3] and r[3] < time.time():
c.execute("delete from memory where namespace=? and key=?", (namespace, key))
return None
return {"value": r[0], "source": r[1], "updated_at": r[2], "expires_at": r[3]}
def search(namespace, query, limit=20, db=None):
with connect(db) as c:
rows = c.execute("""select namespace,key,value,source,updated_at,expires_at from memory
where namespace=? and (key like ? or value like ?) order by updated_at desc limit ?""",
(namespace, "%" + query + "%", "%" + query + "%", int(limit))).fetchall()
now = time.time()
return [{"namespace": x[0], "key": x[1], "value": x[2], "source": x[3],
"updated_at": x[4], "expires_at": x[5]} for x in rows
if not x[5] or x[5] > now]
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("cmd", choices=["put", "get", "search"])
ap.add_argument("namespace")
ap.add_argument("key")
ap.add_argument("value", nargs="?")
ap.add_argument("--ttl", type=int)
a = ap.parse_args()
if a.cmd == "put":
print(json.dumps(put(a.namespace, a.key, a.value or "", ttl=a.ttl)))
elif a.cmd == "get":
print(json.dumps(get(a.namespace, a.key)))
else:
print(json.dumps(search(a.namespace, a.key)))
+13
View File
@@ -0,0 +1,13 @@
import sys, unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from gateway_agent import call
class AgentGatewayTests(unittest.TestCase):
def test_agent_uses_gateway(self):
d = call("catalog.read")
self.assertEqual(d.get("tool"), "catalog.read")
self.assertGreater(len(d.get("body") or ""), 10)
if __name__ == "__main__":
unittest.main()
+17
View File
@@ -0,0 +1,17 @@
import sys, unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from tool_gateway_server import lease_create, lease_release
class LeaseTests(unittest.TestCase):
def test_single_model_lease(self):
a, err = lease_create('deepseek-chat', 'test-agent', 60)
self.assertIsNone(err)
self.assertIsNotNone(a)
b, err2 = lease_create('deepseek-chat', 'test-agent-2', 60)
self.assertIsNone(b)
self.assertEqual(err2, 'model busy')
lease_release(a['id'])
if __name__ == '__main__':
unittest.main()
+19
View File
@@ -0,0 +1,19 @@
import os, sys, tempfile, unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from memory import put, get, search
class MemoryTests(unittest.TestCase):
def setUp(self):
self.db = tempfile.mktemp(suffix='.db')
def test_put_get(self):
put('stage5','camera','Frigate test',source='test',db=self.db)
self.assertEqual(get('stage5','camera',db=self.db)['value'],'Frigate test')
def test_search(self):
put('stage5','event_bus','NATS JetStream',db=self.db)
self.assertEqual(len(search('stage5','NATS',db=self.db)),1)
def test_ttl(self):
put('stage5','tmp','x',ttl=-1,db=self.db)
self.assertIsNone(get('stage5','tmp',db=self.db))
if __name__ == '__main__':
unittest.main()
+15
View File
@@ -0,0 +1,15 @@
import sys, unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from tool_gateway import load_tools
class GatewayTests(unittest.TestCase):
def test_tools_have_gateway(self):
tools = load_tools()
self.assertGreaterEqual(len(tools), 3)
for t in tools:
self.assertTrue(t["gateway"].startswith("http"))
self.assertFalse(t.get("direct_prod", False))
if __name__ == "__main__":
unittest.main()
+14
View File
@@ -0,0 +1,14 @@
import sys, unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from tool_gateway_server import tools
class GatewayServerTests(unittest.TestCase):
def test_policy_loads(self):
t = tools()
self.assertIn("catalog.read", t)
self.assertEqual(t["catalog.read"]["mode"], "read")
self.assertTrue(t["notify.send"]["approval"])
if __name__ == "__main__":
unittest.main()
+18
View File
@@ -0,0 +1,18 @@
"""Read-only Tool Gateway policy registry (Stage 5)."""
from pathlib import Path
import yaml
PATH = Path("/root/buryan-infra/docs/architecture/REGISTRY/tool_gateway.yaml")
def load_tools():
data = yaml.safe_load(PATH.read_text())
tools = data.get("tools") or []
for t in tools:
if not t.get("gateway"):
raise ValueError("tool without gateway: %s" % t.get("name"))
if t.get("direct_prod"):
raise ValueError("direct production access forbidden: %s" % t.get("name"))
if t.get("mode") not in ("read", "write"):
raise ValueError("bad mode: %s" % t.get("name"))
return tools
+296
View File
@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""Stage 5 Tool Gateway: allowlisted proxy for agents.
Listens on 127.0.0.1:9137. It never exposes production directly:
agents call a named tool, the gateway validates policy and forwards.
Write tools require X-Approval: approved.
"""
import json
import os
import sys
import time
import uuid
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
import yaml
POLICY = "/root/buryan-infra/docs/architecture/REGISTRY/tool_gateway.yaml"
MODELS = "/root/buryan-infra/docs/architecture/REGISTRY/models.yaml"
LEASES = "/var/lib/hub-tools/leases.json"
APPROVALS = "/var/lib/hub-tools/approvals.json"
LOG = "/var/log/hub-tools/gateway.jsonl"
HOST, PORT = "127.0.0.1", 9137
def tools():
return {t["name"]: t for t in (yaml.safe_load(open(POLICY).read()).get("tools") or [])}
def _photo_local():
sys.path.insert(0, "/opt/hub-bots")
from hub import local
return local
def _hub_module(name):
sys.path.insert(0, "/opt/hub-bots")
import importlib
return importlib.import_module("hub." + name)
def local_call(handler, q=""):
if handler == "photo_stats":
c, err = _photo_local().ImmichDb().counts()
return {"ok": not bool(err), "counts": c, "error": err}
if handler == "photo_space":
out, err = _photo_local().pct_exec(151, ["su", "-", "postgres", "-c",
"psql -d immich_db -tAc \"select pg_size_pretty(pg_database_size('immich_db'))\""])
return {"ok": not bool(err), "size": out, "error": err}
if handler == "book_stats":
c, err = _photo_local().Books().counts()
return {"ok": not bool(err), "counts": c, "error": err}
if handler == "book_recent":
rows, err = _photo_local().Books().recent(8)
return {"ok": not bool(err), "rows": rows, "error": err}
if handler == "book_search":
rows, err = _photo_local().Books().search(q, 5)
return {"ok": not bool(err), "rows": rows, "error": err}
if handler == "home_stats":
data, err = _photo_local().HomeDb().entities()
return {"ok": not bool(err), "data": data, "error": err}
if handler == "home_status":
data, err = _photo_local().HomeDb().states()
return {"ok": not bool(err), "data": data, "error": err}
if handler == "catalog_content":
return {"ok": True, "data": _hub_module("catalog").content_state(), "error": None}
if handler == "digest_index":
try:
return {"ok": True, "data": _hub_module("index").stats(), "error": None}
except Exception as e:
return {"ok": False, "data": None, "error": str(e)[:200]}
if handler == "seerr_counts":
data, err = _hub_module("sources").Seerr().counts()
return {"ok": not bool(err), "data": data, "error": err}
if handler == "prom_targets":
data, err = _hub_module("sources").Prom().targets()
return {"ok": not bool(err), "data": data, "error": err}
if handler == "prom_alerts":
data, err = _hub_module("sources").Prom().alerts()
return {"ok": not bool(err), "data": data, "error": err}
raise ValueError("unknown local handler")
def models():
return {m["id"]: m for m in (yaml.safe_load(open(MODELS).read()).get("models") or [])}
def model_up(model_id):
m = models().get(model_id)
if not m:
return None
if m.get("health") == "external":
return True
try:
with urllib.request.urlopen(m["endpoint"].rstrip("/") + "/api/tags", timeout=3) as r:
return r.status == 200
except Exception:
return False
def read_leases():
try:
return json.loads(open(LEASES).read())
except Exception:
return {}
def write_leases(data):
os.makedirs(os.path.dirname(LEASES), exist_ok=True)
tmp = LEASES + ".tmp"
open(tmp, "w").write(json.dumps(data, ensure_ascii=False, indent=2))
os.replace(tmp, LEASES)
def lease_create(model, agent, ttl_sec=900):
if model not in models():
return None, "unknown model"
if model_up(model) is False:
return None, "model unavailable"
now = time.time()
leases = {k: v for k, v in read_leases().items() if v.get("expires", 0) > now}
active = [v for v in leases.values() if v.get("state") == "active"]
if sum(1 for v in active if v.get("agent") == (agent or "unknown")) >= 2:
return None, "agent lease limit"
if any(v.get("model") == model for v in active):
return None, "model busy"
lid = uuid.uuid4().hex[:12]
leases[lid] = {"id": lid, "model": model, "agent": agent or "unknown",
"created": now, "expires": now + max(60, min(int(ttl_sec), 3600)),
"state": "active"}
write_leases(leases)
return leases[lid], None
def lease_release(lid):
leases = read_leases()
if lid not in leases:
return False
leases[lid]["state"] = "released"
write_leases(leases)
return True
def read_approvals():
try:
return json.loads(open(APPROVALS).read())
except Exception:
return {}
def write_approvals(data):
os.makedirs(os.path.dirname(APPROVALS), exist_ok=True)
tmp = APPROVALS + ".tmp"
open(tmp, "w").write(json.dumps(data, ensure_ascii=False, indent=2))
os.replace(tmp, APPROVALS)
def approval_create(tool, agent, reason=""):
if tool not in tools():
return None, "unknown tool"
aid = uuid.uuid4().hex[:12]
data = read_approvals()
data[aid] = {"id": aid, "tool": tool, "agent": agent or "unknown",
"reason": reason[:300], "created": time.time(), "state": "pending"}
write_approvals(data)
return data[aid], None
def approval_decide(aid, approve):
data = read_approvals()
if aid not in data:
return None, "not found"
data[aid]["state"] = "approved" if approve else "denied"
data[aid]["decided"] = time.time()
write_approvals(data)
return data[aid], None
def approval_ok(aid, tool):
a = read_approvals().get(aid)
return bool(a and a.get("tool") == tool and a.get("state") == "approved")
def log(entry):
os.makedirs(os.path.dirname(LOG), exist_ok=True)
with open(LOG, "a") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
class H(BaseHTTPRequestHandler):
def _json(self, code, obj):
b = json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_GET(self):
u = urlparse(self.path)
if u.path == "/health":
return self._json(200, {"ok": True, "service": "hub-tools", "tools": len(tools())})
if u.path == "/v1/tools":
return self._json(200, {"tools": list(tools().values())})
if u.path == "/v1/models":
return self._json(200, {"models": list(models().values())})
if u.path == "/v1/leases":
now = time.time()
return self._json(200, {"leases": [v for v in read_leases().values() if v.get("expires", 0) > now]})
if u.path == "/v1/approvals":
return self._json(200, {"approvals": list(read_approvals().values())})
if u.path != "/v1/call":
return self._json(404, {"error": "not found"})
name = (parse_qs(u.query).get("tool") or [""])[0]
t = tools().get(name)
if not t:
return self._json(404, {"error": "unknown tool"})
if t.get("mode") == "read" and t.get("local"):
try:
body = local_call(t["local"], (parse_qs(u.query).get("q") or [""])[0])
log({"tool": name, "mode": "local", "code": 200})
return self._json(200, {"tool": name, "body": body})
except Exception as e:
log({"tool": name, "mode": "local", "error": str(e)[:200]})
return self._json(502, {"error": str(e)[:200]})
if t["mode"] != "read":
return self._json(403, {"error": "write tool requires POST approval"})
try:
req = urllib.request.Request(t["gateway"], method="GET")
with urllib.request.urlopen(req, timeout=10) as r:
body = r.read(200000).decode("utf-8", "replace")
log({"tool": name, "mode": "read", "code": 200})
return self._json(200, {"tool": name, "upstream": t["gateway"], "body": body})
except Exception as e:
log({"tool": name, "mode": "read", "error": str(e)[:200]})
return self._json(502, {"error": str(e)[:200]})
def do_POST(self):
u = urlparse(self.path)
n = int(self.headers.get("Content-Length") or 0)
try:
data = json.loads(self.rfile.read(n) or b"{}")
except Exception:
return self._json(400, {"error": "bad json"})
if u.path == "/v1/approvals":
a, err = approval_create(data.get("tool"), data.get("agent"), data.get("reason", ""))
if err:
return self._json(404, {"error": err})
log({"approval": a["id"], "tool": a["tool"], "agent": a["agent"], "state": "pending"})
return self._json(201, a)
if u.path == "/v1/approvals/decision":
a, err = approval_decide(data.get("id"), bool(data.get("approve")))
if err:
return self._json(404, {"error": err})
return self._json(200, a)
if u.path == "/v1/leases":
lease, err = lease_create(data.get("model"), data.get("agent"), data.get("ttl_sec", 900))
if err:
return self._json(409 if err == "model unavailable" else 404, {"error": err})
log({"lease": lease["id"], "model": lease["model"], "agent": lease["agent"]})
return self._json(201, lease)
if u.path == "/v1/leases/release":
ok = lease_release(data.get("id"))
return self._json(200 if ok else 404, {"ok": ok})
if u.path != "/v1/call":
return self._json(404, {"error": "not found"})
name = data.get("tool")
t = tools().get(name)
if not t:
return self._json(404, {"error": "unknown tool"})
if t["mode"] != "write":
return self._json(200, {"error": "read tool; use GET"})
approval_id = self.headers.get("X-Approval") or ""
if t.get("approval") and not approval_ok(approval_id, name):
log({"tool": name, "mode": "write", "code": 403})
return self._json(403, {"error": "approved approval id required"})
try:
payload = json.dumps(data.get("body") or {}, ensure_ascii=False).encode()
req = urllib.request.Request(t["gateway"], data=payload, method="POST",
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=10) as r:
body = r.read(200000).decode("utf-8", "replace")
log({"tool": name, "mode": "write", "code": 200})
return self._json(200, {"tool": name, "body": body})
except Exception as e:
log({"tool": name, "mode": "write", "error": str(e)[:200]})
return self._json(502, {"error": str(e)[:200]})
def log_message(self, *a):
pass
if __name__ == "__main__":
ThreadingHTTPServer((HOST, PORT), H).serve_forever()
+1 -1
View File
@@ -1,5 +1,5 @@
# Соответствие единому стандарту
Обновлено: 2026-11-27 04:40
Обновлено: 2026-11-29 04:40
/opt/work-hub/venv/bin/python: can't open file '/tmp/standard_check.py': [Errno 2] No such file or directory
+227
View File
@@ -0,0 +1,227 @@
# Audit 360 — Buryans Hub + Prism
**Run:** 12
**Started:** 2026-11-28 01:00:00.766181+00:00
**Finished:** 2026-11-28 01:00:02.793629+00:00
## Executive summary
Детерминированный срез инфраструктуры без LLM-домыслов.
- **Hub:** None/None
- **CT running:** 30
- **Сервисов running:** 114
- **Слушающих портов:** 62
- **Баз данных:** 51
- **Nginx proxy:** 59
- **Моделей Prism:** 299
- **Kuma down:** 1/59
- **Последний бэкап:** 0.0 дней
- **Диск /:** 40.6%
## Findings
### [HIGH] monitoring — Kuma: 1 мониторов down
- Evidence: `kuma_monitors_down=1, total=59`
- Recommendation: Проверить конкретные down-мониторы и владельцев сервисов.
### [HIGH] data — Все базы данных на одном CT151
- Evidence: `PostgreSQL CT151 обслуживает 50 баз; при отказе CT останавливаются Matrix, Gitea, Vaultwarden, Authentik, Prism.`
- Recommendation: Реплика + проверенный failover для критичных БД.
### [MEDIUM] services — hub-yandex-bridge.service не active
- Evidence: `systemctl is-active = inactive`
- Recommendation: Проверить, должен ли сервис/таймер работать; если нет — зафиксировать в документации.
### [MEDIUM] services — hub-agents.timer не active
- Evidence: `systemctl is-active = inactive`
- Recommendation: Проверить, должен ли сервис/таймер работать; если нет — зафиксировать в документации.
### [MEDIUM] services — hub-brain.timer не active
- Evidence: `systemctl is-active = inactive`
- Recommendation: Проверить, должен ли сервис/таймер работать; если нет — зафиксировать в документации.
### [MEDIUM] legacy — Старые/параллельные сервисы активны
- Evidence: `combine-web2.service, combine-engine.service, combine-project.service, llm-dispatcher.service`
- Recommendation: Определить владельца и судьбу: Prism replacement, legacy fallback или удаление.
### [MEDIUM] ai — LLM-контур зависит от одного ПК/GPU
- Evidence: `Ollama 192.168.1.229 + qwen2.5:3b-32k; очередь Prism и аудит используют один GPU.`
- Recommendation: Второй провайдер/модель или облачный fallback; бюджет токенов и SLA.
### [MEDIUM] inventory — Расхождение количества CT с документацией
- Evidence: `Живой pct list: 30 running; docs/INFRASTRUCTURE-MAP.md: 30, из них 29 running.`
- Recommendation: Обновить карту через ops/inventory/build-map.py и зафиксировать владельцев.
### [MEDIUM] observability — Kuma не различает «порт открыт» и «сервис работает»
- Evidence: `5 down-мониторов: recipes, sync, Mealie, Syncthing-105, Seerr; проверки портов.`
- Recommendation: Функциональные HTTP/бизнес-проверки для критичных сервисов.
### [MEDIUM] integrations — Внутренние API-зависимости зашиты в код/конфиги
- Evidence: `Найдено 88 уникальных endpoint в 310 файлах; часть может быть hardcoded.`
- Recommendation: Свести endpoint'ы в реестр сервисов; проверить владельцев и health-check.
## Inventory
| Kind | Count |
|---|---:|
| docker | 174 |
| config | 166 |
| service | 162 |
| endpoint | 88 |
| port | 62 |
| database | 51 |
| container | 30 |
| nginx | 25 |
| backup | 1 |
| repo | 1 |
## Integration links
Рёбра графа: **1611**. Первые 60:
| Source | Destination | Kind | Evidence |
|---|---|---|---|
| nginx | port:8095 | proxies | http://127.0.0.1:8095 |
| nginx | host:127.0.0.1 | upstream_host | http://127.0.0.1:8095 |
| nginx | port:8097 | proxies | http://127.0.0.1:8097/oauth2/auth |
| nginx | port:9121 | proxies | http://127.0.0.1:9121 |
| nginx | port:9150 | proxies | http://127.0.0.1:9150 |
| nginx | port:9160 | proxies | http://127.0.0.1:9160 |
| nginx | port:9180 | proxies | http://127.0.0.1:9180/ |
| nginx | port:9983 | proxies | http://192.168.1.102:9983 |
| nginx | host:192.168.1.102 | upstream_host | http://192.168.1.102:9983 |
| nginx | port:8096 | proxies | http://192.168.1.103:8096 |
| nginx | host:192.168.1.103 | upstream_host | http://192.168.1.103:8096 |
| nginx | port:9151 | proxies | http://192.168.1.103:9151 |
| nginx | port:2283 | proxies | http://192.168.1.104:2283 |
| nginx | host:192.168.1.104 | upstream_host | http://192.168.1.104:2283 |
| nginx | port:8123 | proxies | http://192.168.1.106:8123 |
| nginx | host:192.168.1.106 | upstream_host | http://192.168.1.106:8123 |
| nginx | port:8130 | proxies | http://192.168.1.106:8130 |
| nginx | port:9130 | proxies | http://192.168.1.106:9130 |
| nginx | port:9109 | proxies | http://192.168.1.107:9109 |
| nginx | host:192.168.1.107 | upstream_host | http://192.168.1.107:9109 |
| nginx | port:1881 | proxies | http://192.168.1.108:1881 |
| nginx | host:192.168.1.108 | upstream_host | http://192.168.1.108:1881 |
| nginx | port:9105 | proxies | http://192.168.1.108:9105 |
| nginx | port:9120 | proxies | http://192.168.1.10:9120/ |
| nginx | host:192.168.1.10 | upstream_host | http://192.168.1.10:9120/ |
| nginx | port:4180 | proxies | http://192.168.1.109:4180 |
| nginx | host:192.168.1.109 | upstream_host | http://192.168.1.109:4180 |
| nginx | port:8080 | proxies | http://192.168.1.109:8080 |
| nginx | port:4190 | proxies | http://192.168.1.110:4190 |
| nginx | host:192.168.1.110 | upstream_host | http://192.168.1.110:4190 |
| nginx | port:4191 | proxies | http://192.168.1.110:4191 |
| nginx | port:4192 | proxies | http://192.168.1.110:4192 |
| nginx | port:4195 | proxies | http://192.168.1.110:4195 |
| nginx | port:4197 | proxies | http://192.168.1.110:4197 |
| nginx | port:5230 | proxies | http://192.168.1.110:5230 |
| nginx | port:8090 | proxies | http://192.168.1.110:8090 |
| nginx | port:8093 | proxies | http://192.168.1.110:8093 |
| nginx | port:9104 | proxies | http://192.168.1.110:9104 |
| nginx | port:9131 | proxies | http://192.168.1.110:9131 |
| nginx | port:9284 | proxies | http://192.168.1.110:9284 |
| nginx | port:9285 | proxies | http://192.168.1.110:9285 |
| nginx | port:9287 | proxies | http://192.168.1.110:9287 |
| nginx | port:9981 | proxies | http://192.168.1.110:9981 |
| nginx | port:9996 | proxies | http://192.168.1.110:9996 |
| nginx | port:9997 | proxies | http://192.168.1.110:9997 |
| nginx | port:3000 | proxies | http://192.168.1.113:3000 |
| nginx | host:192.168.1.113 | upstream_host | http://192.168.1.113:3000 |
| nginx | port:9102 | proxies | http://192.168.1.113:9102 |
| nginx | port:9000 | proxies | http://192.168.1.114:9000 |
| nginx | host:192.168.1.114 | upstream_host | http://192.168.1.114:9000 |
| nginx | port:9108 | proxies | http://192.168.1.115:9108 |
| nginx | host:192.168.1.115 | upstream_host | http://192.168.1.115:9108 |
| nginx | port:9989 | proxies | http://192.168.1.117:9989 |
| nginx | host:192.168.1.117 | upstream_host | http://192.168.1.117:9989 |
| nginx | port:9988 | proxies | http://192.168.1.118:9988 |
| nginx | host:192.168.1.118 | upstream_host | http://192.168.1.118:9988 |
| nginx | port:9987 | proxies | http://192.168.1.119:9987 |
| nginx | host:192.168.1.119 | upstream_host | http://192.168.1.119:9987 |
| nginx | port:9986 | proxies | http://192.168.1.120:9986 |
| nginx | host:192.168.1.120 | upstream_host | http://192.168.1.120:9986 |
## Capability matrix
| Возможность | Maturity | Automation | Leverage | Criticality | Пробел |
|---|---:|---:|---:|---:|---|
| **Бэкапы и восстановление** | 2 | 2 | 2 | 5 | Восстановление не проверялось; локальный бэкап устарел; нет регулярного restore-test. |
| **Данные и СУБД** | 3 | 2 | 4 | 5 | Единая точка отказа: все БД на одном CT; нет реплики и проверенного failover. |
| **Идентичность и доступ** | 4 | 3 | 3 | 5 | Централизация частичная: часть сервисов с собственным паролем; нет полного каталога владельцев приложений. |
| **Сеть и удалённый доступ** | 4 | 4 | 3 | 5 | Сильная сторона; нет полной карты внешних доменов и владельцев сертификатов. |
| **Наблюдаемость** | 2 | 2 | 2 | 5 | Проверки отвечают на порт, а не на смысл; 5 down-мониторов не разобраны. |
| **Безопасность и секреты** | 2 | 2 | 2 | 5 | Секреты разбросаны; нет регулярной ротации и проверки уязвимостей. |
| **Агенты и боты** | 3 | 3 | 4 | 4 | Агентский слой есть, но таймеры hub-agents/brain/selfheal/inbox неактивны; нет SLA и очереди approvals. |
| **LLM и обогащение** | 2 | 2 | 5 | 4 | Один GPU/ПК, очередь хрупкая, нет бюджета токенов и оценки качества LLM. |
| **Дом и автоматизация** | 3 | 3 | 3 | 4 | Дом автоматизирован частично; сценарии и голосовые сценарии не оформлены как продукт. |
| **Работа и пресейл** | 2 | 1 | 5 | 4 | Два параллельных контура (старый Combine и Prism), нет единого владельца, нет тестов и версий. |
| **Автоматизация** | 3 | 4 | 3 | 3 | Много автоматизаций, но реестр и владельцы неполные; часть cron/systemd дублируется. |
| **Разработка и CI** | 3 | 3 | 3 | 3 | Есть CI, но нет обязательного теста для Prism и аудита; часть изменений не коммитится. |
| **Документы и знания** | 3 | 2 | 4 | 3 | Разрозненные хранилища; Paperless почти не используется; нет единого поиска по знаниям. |
| **Медиа и развлечения** | 3 | 3 | 2 | 3 | Много сервисов, но часть данных не бэкапится; ценность в контенте, не в платформе. |
| **Уведомления** | 3 | 3 | 3 | 3 | Есть каналы, но нет политики приоритетов и дедупликации уведомлений. |
## Opportunity portfolio
| Возможность | Impact | Effort | Risk | Гипотеза |
|---|---:|---:|---:|---|
| **Реализация активных таймеров для агентов и браузера** | 4 | 3 | 2 | Увеличение эффективности работы агентов и браузера, уменьшение задержек и отказов. |
| **Расширение возможности использования LLM и обогащения** | 4 | 4 | 3 | Увеличение функциональности и качества ответов от LLM, увеличение объема обогащенных данных. |
| **Устранение дублирования и внедрение обязательного тестирования для CI** | 4 | 4 | 3 | Уменьшение времени на настройку и поддержку CI, повышение качества кода. |
| **Реализация регулярного и проверенного бэкапа** | 4 | 4 | 3 | Уменьшение риска потери данных и ускорение восстановления, повышение надежности системы. |
| **Создание единого поиска по знаниям и внедрение Paperless** | 4 | 4 | 3 | Увеличение доступности и качества информации, повышение эффективности работы. |
| **Реализация реплики и проверенного failover для БД** | 4 | 5 | 3 | Уменьшение риска отказа и ускорение восстановления, повышение надежности системы. |
| **Полное управление и регулярное тестирование автоматизаций** | 4 | 5 | 3 | Устранение дублирования и улучшение эффективности автоматизаций, уменьшение времени на их настройку и поддержку. |
| **Оформление домашних сценариев и голосовых сценариев как продукта** | 4 | 5 | 3 | Увеличение удобства и функциональности домашнего автоматизации, повышение доверия к системе. |
## Arena 360
Один evidence-пакет, два голоса: локальная Qwen 3B и DeepSeek. Выбор — детерминированный: impact/effort/risk + leverage/criticality + одна возможность на capability.
| Возможность | Capability | Голоса | I | E | R | Score |
|---|---|---|---:|---:|---:|---:|
| **Восстановить и проверить бэкап-цепочку** | backup | deepseek-auditor | 5 | 3 | 2 | 17 |
| **Улучшение безопасности данных** | security | qwen7b-sre | 5 | 3 | 2 | 17 |
| **Активировать агентский слой и approvals** | agents | deepseek-auditor | 4 | 2 | 3 | 16 |
| **Единый реестр владельцев сервисов и доменов** | identity | deepseek-auditor | 4 | 3 | 2 | 16 |
| **Устранить единую точку отказа СУБД CT151** | data | deepseek-auditor | 5 | 5 | 4 | 15 |
| **Смысловая наблюдаемость вместо проверки портов** | observability | deepseek-auditor | 4 | 3 | 2 | 15 |
| **Консолидация legacy-контура Combine и Prism** | work | deepseek-auditor | 4 | 4 | 3 | 15 |
| **Улучшение документации и знаний** | docs | qwen7b-sre | 3 | 4 | 1 | 13 |
## Roadmap (draft)
### 0–2 недели
- Проверить и восстановить backup/restore; разобрать 5 down-мониторов Kuma.
- Решить судьбу `combine-*` и `llm-dispatcher`: Prism — основной контур или legacy fallback.
- Включить/задокументировать неактивные таймеры агентов, если они нужны.
### 2–6 недель
- Убрать единую точку отказа PostgreSQL: реплика + проверенный failover.
- Ввести владельцев и SLA для 15 возможностей; закрыть разрыв между docs и фактом.
- Добавить Audit 360 в Prism как страницу с run/diff.
### 6–12 недель
- Единый поиск по знаниям и документам; довести Paperless/Nextcloud/Docmost.
- Агентский слой: approvals, SLA, наблюдаемость; включить таймеры.
- Продуктовые сценарии: Prism как AV knowledge platform, Секретарь как orchestrator.
## Следующие слои Audit 360
- capability matrix: сервис → возможность → зрелость;
- value/leverage: переиспользование, автоматизация, продукт;
- risk: SPOF, секреты, бэкапы, единственный GPU;
- opportunity portfolio и roadmap;
- LLM-синтез строго по evidence.
+228
View File
@@ -0,0 +1,228 @@
# Audit 360 — Buryans Hub + Prism
**Run:** 13
**Started:** 2026-11-29 01:00:00.938958+00:00
**Finished:** 2026-11-29 01:00:10.239212+00:00
## Executive summary
Детерминированный срез инфраструктуры без LLM-домыслов.
- **Hub:** 74/74
- **CT running:** 30
- **Сервисов running:** 111
- **Слушающих портов:** 64
- **Баз данных:** 51
- **Nginx proxy:** 59
- **Моделей Prism:** 299
- **Kuma down:** 1/59
- **Последний бэкап:** 0.0 дней
- **Диск /:** 40.6%
## Findings
### [HIGH] monitoring — Kuma: 1 мониторов down
- Evidence: `kuma_monitors_down=1, total=59`
- Recommendation: Проверить конкретные down-мониторы и владельцев сервисов.
### [HIGH] data — Все базы данных на одном CT151
- Evidence: `PostgreSQL CT151 обслуживает 50 баз; при отказе CT останавливаются Matrix, Gitea, Vaultwarden, Authentik, Prism.`
- Recommendation: Реплика + проверенный failover для критичных БД.
### [MEDIUM] services — hub-yandex-bridge.service не active
- Evidence: `systemctl is-active = inactive`
- Recommendation: Проверить, должен ли сервис/таймер работать; если нет — зафиксировать в документации.
### [MEDIUM] services — hub-agents.timer не active
- Evidence: `systemctl is-active = inactive`
- Recommendation: Проверить, должен ли сервис/таймер работать; если нет — зафиксировать в документации.
### [MEDIUM] services — hub-brain.timer не active
- Evidence: `systemctl is-active = inactive`
- Recommendation: Проверить, должен ли сервис/таймер работать; если нет — зафиксировать в документации.
### [MEDIUM] legacy — Старые/параллельные сервисы активны
- Evidence: `combine-web2.service, combine-engine.service, combine-project.service, llm-dispatcher.service`
- Recommendation: Определить владельца и судьбу: Prism replacement, legacy fallback или удаление.
### [MEDIUM] ai — LLM-контур зависит от одного ПК/GPU
- Evidence: `Ollama 192.168.1.229 + qwen2.5:3b-32k; очередь Prism и аудит используют один GPU.`
- Recommendation: Второй провайдер/модель или облачный fallback; бюджет токенов и SLA.
### [MEDIUM] inventory — Расхождение количества CT с документацией
- Evidence: `Живой pct list: 30 running; docs/INFRASTRUCTURE-MAP.md: 30, из них 29 running.`
- Recommendation: Обновить карту через ops/inventory/build-map.py и зафиксировать владельцев.
### [MEDIUM] observability — Kuma не различает «порт открыт» и «сервис работает»
- Evidence: `5 down-мониторов: recipes, sync, Mealie, Syncthing-105, Seerr; проверки портов.`
- Recommendation: Функциональные HTTP/бизнес-проверки для критичных сервисов.
### [MEDIUM] integrations — Внутренние API-зависимости зашиты в код/конфиги
- Evidence: `Найдено 88 уникальных endpoint в 310 файлах; часть может быть hardcoded.`
- Recommendation: Свести endpoint'ы в реестр сервисов; проверить владельцев и health-check.
## Inventory
| Kind | Count |
|---|---:|
| docker | 174 |
| config | 166 |
| service | 159 |
| endpoint | 88 |
| port | 64 |
| database | 51 |
| container | 30 |
| nginx | 25 |
| hub | 1 |
| repo | 1 |
| backup | 1 |
## Integration links
Рёбра графа: **1604**. Первые 60:
| Source | Destination | Kind | Evidence |
|---|---|---|---|
| nginx | port:8095 | proxies | http://127.0.0.1:8095 |
| nginx | host:127.0.0.1 | upstream_host | http://127.0.0.1:8095 |
| nginx | port:8097 | proxies | http://127.0.0.1:8097/oauth2/auth |
| nginx | port:9121 | proxies | http://127.0.0.1:9121 |
| nginx | port:9150 | proxies | http://127.0.0.1:9150 |
| nginx | port:9160 | proxies | http://127.0.0.1:9160 |
| nginx | port:9180 | proxies | http://127.0.0.1:9180/ |
| nginx | port:9983 | proxies | http://192.168.1.102:9983 |
| nginx | host:192.168.1.102 | upstream_host | http://192.168.1.102:9983 |
| nginx | port:8096 | proxies | http://192.168.1.103:8096 |
| nginx | host:192.168.1.103 | upstream_host | http://192.168.1.103:8096 |
| nginx | port:9151 | proxies | http://192.168.1.103:9151 |
| nginx | port:2283 | proxies | http://192.168.1.104:2283 |
| nginx | host:192.168.1.104 | upstream_host | http://192.168.1.104:2283 |
| nginx | port:8123 | proxies | http://192.168.1.106:8123 |
| nginx | host:192.168.1.106 | upstream_host | http://192.168.1.106:8123 |
| nginx | port:8130 | proxies | http://192.168.1.106:8130 |
| nginx | port:9130 | proxies | http://192.168.1.106:9130 |
| nginx | port:9109 | proxies | http://192.168.1.107:9109 |
| nginx | host:192.168.1.107 | upstream_host | http://192.168.1.107:9109 |
| nginx | port:1881 | proxies | http://192.168.1.108:1881 |
| nginx | host:192.168.1.108 | upstream_host | http://192.168.1.108:1881 |
| nginx | port:9105 | proxies | http://192.168.1.108:9105 |
| nginx | port:9120 | proxies | http://192.168.1.10:9120/ |
| nginx | host:192.168.1.10 | upstream_host | http://192.168.1.10:9120/ |
| nginx | port:4180 | proxies | http://192.168.1.109:4180 |
| nginx | host:192.168.1.109 | upstream_host | http://192.168.1.109:4180 |
| nginx | port:8080 | proxies | http://192.168.1.109:8080 |
| nginx | port:4190 | proxies | http://192.168.1.110:4190 |
| nginx | host:192.168.1.110 | upstream_host | http://192.168.1.110:4190 |
| nginx | port:4191 | proxies | http://192.168.1.110:4191 |
| nginx | port:4192 | proxies | http://192.168.1.110:4192 |
| nginx | port:4195 | proxies | http://192.168.1.110:4195 |
| nginx | port:4197 | proxies | http://192.168.1.110:4197 |
| nginx | port:5230 | proxies | http://192.168.1.110:5230 |
| nginx | port:8090 | proxies | http://192.168.1.110:8090 |
| nginx | port:8093 | proxies | http://192.168.1.110:8093 |
| nginx | port:9104 | proxies | http://192.168.1.110:9104 |
| nginx | port:9131 | proxies | http://192.168.1.110:9131 |
| nginx | port:9284 | proxies | http://192.168.1.110:9284 |
| nginx | port:9285 | proxies | http://192.168.1.110:9285 |
| nginx | port:9287 | proxies | http://192.168.1.110:9287 |
| nginx | port:9981 | proxies | http://192.168.1.110:9981 |
| nginx | port:9996 | proxies | http://192.168.1.110:9996 |
| nginx | port:9997 | proxies | http://192.168.1.110:9997 |
| nginx | port:3000 | proxies | http://192.168.1.113:3000 |
| nginx | host:192.168.1.113 | upstream_host | http://192.168.1.113:3000 |
| nginx | port:9102 | proxies | http://192.168.1.113:9102 |
| nginx | port:9000 | proxies | http://192.168.1.114:9000 |
| nginx | host:192.168.1.114 | upstream_host | http://192.168.1.114:9000 |
| nginx | port:9108 | proxies | http://192.168.1.115:9108 |
| nginx | host:192.168.1.115 | upstream_host | http://192.168.1.115:9108 |
| nginx | port:9989 | proxies | http://192.168.1.117:9989 |
| nginx | host:192.168.1.117 | upstream_host | http://192.168.1.117:9989 |
| nginx | port:9988 | proxies | http://192.168.1.118:9988 |
| nginx | host:192.168.1.118 | upstream_host | http://192.168.1.118:9988 |
| nginx | port:9987 | proxies | http://192.168.1.119:9987 |
| nginx | host:192.168.1.119 | upstream_host | http://192.168.1.119:9987 |
| nginx | port:9986 | proxies | http://192.168.1.120:9986 |
| nginx | host:192.168.1.120 | upstream_host | http://192.168.1.120:9986 |
## Capability matrix
| Возможность | Maturity | Automation | Leverage | Criticality | Пробел |
|---|---:|---:|---:|---:|---|
| **Бэкапы и восстановление** | 2 | 2 | 2 | 5 | Восстановление не проверялось; локальный бэкап устарел; нет регулярного restore-test. |
| **Данные и СУБД** | 3 | 2 | 4 | 5 | Единая точка отказа: все БД на одном CT; нет реплики и проверенного failover. |
| **Идентичность и доступ** | 4 | 3 | 3 | 5 | Централизация частичная: часть сервисов с собственным паролем; нет полного каталога владельцев приложений. |
| **Сеть и удалённый доступ** | 4 | 4 | 3 | 5 | Сильная сторона; нет полной карты внешних доменов и владельцев сертификатов. |
| **Наблюдаемость** | 2 | 2 | 2 | 5 | Проверки отвечают на порт, а не на смысл; 5 down-мониторов не разобраны. |
| **Безопасность и секреты** | 2 | 2 | 2 | 5 | Секреты разбросаны; нет регулярной ротации и проверки уязвимостей. |
| **Агенты и боты** | 3 | 3 | 4 | 4 | Агентский слой есть, но таймеры hub-agents/brain/selfheal/inbox неактивны; нет SLA и очереди approvals. |
| **LLM и обогащение** | 2 | 2 | 5 | 4 | Один GPU/ПК, очередь хрупкая, нет бюджета токенов и оценки качества LLM. |
| **Дом и автоматизация** | 3 | 3 | 3 | 4 | Дом автоматизирован частично; сценарии и голосовые сценарии не оформлены как продукт. |
| **Работа и пресейл** | 2 | 1 | 5 | 4 | Два параллельных контура (старый Combine и Prism), нет единого владельца, нет тестов и версий. |
| **Автоматизация** | 3 | 4 | 3 | 3 | Много автоматизаций, но реестр и владельцы неполные; часть cron/systemd дублируется. |
| **Разработка и CI** | 3 | 3 | 3 | 3 | Есть CI, но нет обязательного теста для Prism и аудита; часть изменений не коммитится. |
| **Документы и знания** | 3 | 2 | 4 | 3 | Разрозненные хранилища; Paperless почти не используется; нет единого поиска по знаниям. |
| **Медиа и развлечения** | 3 | 3 | 2 | 3 | Много сервисов, но часть данных не бэкапится; ценность в контенте, не в платформе. |
| **Уведомления** | 3 | 3 | 3 | 3 | Есть каналы, но нет политики приоритетов и дедупликации уведомлений. |
## Opportunity portfolio
| Возможность | Impact | Effort | Risk | Гипотеза |
|---|---:|---:|---:|---|
| **Реализация активных таймеров для агентов и браузера** | 4 | 3 | 2 | Увеличение эффективности работы агентов и браузера, уменьшение задержек и отказов. |
| **Расширение возможности использования LLM и обогащения** | 4 | 4 | 3 | Увеличение функциональности и качества ответов от LLM, увеличение объема обогащенных данных. |
| **Устранение дублирования и внедрение обязательного тестирования для CI** | 4 | 4 | 3 | Уменьшение времени на настройку и поддержку CI, повышение качества кода. |
| **Реализация регулярного и проверенного бэкапа** | 4 | 4 | 3 | Уменьшение риска потери данных и ускорение восстановления, повышение надежности системы. |
| **Создание единого поиска по знаниям и внедрение Paperless** | 4 | 4 | 3 | Увеличение доступности и качества информации, повышение эффективности работы. |
| **Реализация реплики и проверенного failover для БД** | 4 | 5 | 3 | Уменьшение риска отказа и ускорение восстановления, повышение надежности системы. |
| **Полное управление и регулярное тестирование автоматизаций** | 4 | 5 | 3 | Устранение дублирования и улучшение эффективности автоматизаций, уменьшение времени на их настройку и поддержку. |
| **Оформление домашних сценариев и голосовых сценариев как продукта** | 4 | 5 | 3 | Увеличение удобства и функциональности домашнего автоматизации, повышение доверия к системе. |
## Arena 360
Один evidence-пакет, два голоса: локальная Qwen 3B и DeepSeek. Выбор — детерминированный: impact/effort/risk + leverage/criticality + одна возможность на capability.
| Возможность | Capability | Голоса | I | E | R | Score |
|---|---|---|---:|---:|---:|---:|
| **Восстановить и проверить бэкап-цепочку** | backup | deepseek-auditor | 5 | 3 | 2 | 17 |
| **Улучшение безопасности данных** | security | qwen7b-sre | 5 | 3 | 2 | 17 |
| **Активировать агентский слой и approvals** | agents | deepseek-auditor | 4 | 2 | 3 | 16 |
| **Единый реестр владельцев сервисов и доменов** | identity | deepseek-auditor | 4 | 3 | 2 | 16 |
| **Устранить единую точку отказа СУБД CT151** | data | deepseek-auditor | 5 | 5 | 4 | 15 |
| **Смысловая наблюдаемость вместо проверки портов** | observability | deepseek-auditor | 4 | 3 | 2 | 15 |
| **Консолидация legacy-контура Combine и Prism** | work | deepseek-auditor | 4 | 4 | 3 | 15 |
| **Улучшение документации и знаний** | docs | qwen7b-sre | 3 | 4 | 1 | 13 |
## Roadmap (draft)
### 0–2 недели
- Проверить и восстановить backup/restore; разобрать 5 down-мониторов Kuma.
- Решить судьбу `combine-*` и `llm-dispatcher`: Prism — основной контур или legacy fallback.
- Включить/задокументировать неактивные таймеры агентов, если они нужны.
### 2–6 недель
- Убрать единую точку отказа PostgreSQL: реплика + проверенный failover.
- Ввести владельцев и SLA для 15 возможностей; закрыть разрыв между docs и фактом.
- Добавить Audit 360 в Prism как страницу с run/diff.
### 6–12 недель
- Единый поиск по знаниям и документам; довести Paperless/Nextcloud/Docmost.
- Агентский слой: approvals, SLA, наблюдаемость; включить таймеры.
- Продуктовые сценарии: Prism как AV knowledge platform, Секретарь как orchestrator.
## Следующие слои Audit 360
- capability matrix: сервис → возможность → зрелость;
- value/leverage: переиспользование, автоматизация, продукт;
- risk: SPOF, секреты, бэкапы, единственный GPU;
- opportunity portfolio и roadmap;
- LLM-синтез строго по evidence.
+37
View File
@@ -0,0 +1,37 @@
{
"facts": {
"run_id": 12,
"started_at": "2026-11-28T01:00:00.767915+00:00",
"containers": 30,
"services_running": 114,
"ports": 62,
"nginx_proxies": 59,
"databases": 51,
"prism": {
"models": 299,
"open_tasks": 0,
"practices": 1495,
"requirements": 160
},
"kuma": {
"down": 1,
"total": 59
},
"backups": {
"latest": "/mnt/backups/n8n/n8n-20261128-033001.tar.gz",
"age_days": 0.0
},
"disk": {
"total_gb": 116.7,
"used_pct": 40.6
},
"repo": {
"branch": "arch/hybrid-v1",
"head": "c5c802c [PRISM] Fix missing requirements/matrix-db functions",
"dirty_files": 8
},
"hub_error": "timed out"
},
"entities": 332,
"findings": 5
}
+41
View File
@@ -0,0 +1,41 @@
{
"facts": {
"run_id": 13,
"started_at": "2026-11-29T01:00:00.940593+00:00",
"containers": 30,
"services_running": 111,
"ports": 64,
"nginx_proxies": 59,
"databases": 51,
"prism": {
"models": 299,
"open_tasks": 0,
"practices": 1495,
"requirements": 160
},
"kuma": {
"down": 1,
"total": 59
},
"backups": {
"latest": "/mnt/backups/n8n/n8n-20261129-033001.tar.gz",
"age_days": 0.0
},
"disk": {
"total_gb": 116.7,
"used_pct": 40.6
},
"repo": {
"branch": "arch/hybrid-v1",
"head": "8c16e9c [A-38] Снимок состояния 2026-11-28",
"dirty_files": 9
},
"hub": {
"up": 74,
"total": 74,
"down": []
}
},
"entities": 332,
"findings": 5
}
+31
View File
@@ -0,0 +1,31 @@
# Снимок состояния: 2026-11-28
_Автоматически, 09:00._
## Сервисы
| Показатель | Значение |
|---|---|
| Сервисы | **?/?** |
| Активных алертов | 1 |
| CT / VM | 30 / 1 |
## Ресурсы
| Показатель | Значение |
|---|---|
| RAM | 12032/15754 МБ |
| Своп | 12715/32453 МБ |
| Диск / | 45G из 109G (43%) |
## Бэкапы
| Что | Значение |
|---|---|
| vzdump | 6.5 ч назад |
| Дампы баз | 43 файлов |
| Конфиги | 8 архивов |
## Версия
Коммит: `ef706a3 [STANDARD] Ночной пересчёт соответствия 2026-11-28`
+31
View File
@@ -0,0 +1,31 @@
# Снимок состояния: 2026-11-29
_Автоматически, 09:00._
## Сервисы
| Показатель | Значение |
|---|---|
| Сервисы | **?/?** |
| Активных алертов | 2 |
| CT / VM | 30 / 1 |
## Ресурсы
| Показатель | Значение |
|---|---|
| RAM | 11889/15754 МБ |
| Своп | 13681/32453 МБ |
| Диск / | 45G из 109G (43%) |
## Бэкапы
| Что | Значение |
|---|---|
| vzdump | 3.7 ч назад |
| Дампы баз | 43 файлов |
| Конфиги | 8 архивов |
## Версия
Коммит: `b6c9643 [STANDARD] Ночной пересчёт соответствия 2026-11-29`
+18
View File
@@ -0,0 +1,18 @@
# Связь за 2026-11-28
Замеров: **341** (раз в минуту).
| Участок | Сбоев | Из замеров |
|---|---|---|
| Шлюз (Wi-Fi/роутер) | 0 | 341 |
| DNS | 1 | 341 |
| VPS: TCP 443 | 2 | 341 |
| VPS: TLS (Reality-порт) | 341 | 341 |
Шлюз: средний RTT **0.3 мс**, максимум 0.4 мс.
VPS: средний коннект **48 мс**, максимум 78 мс.
## Когда не отвечал VPS (первые 20)
- 04:00:18
- 04:38:06
+41
View File
@@ -0,0 +1,41 @@
# Ночь: связь до VDS (2026-11-28)
## Общий канал
| Проверка | Сбоев | Из |
|---|---|---|
| Шлюз | 0 | 341 |
| TCP до VDS | 2 | 341 |
| TLS до VDS | 341 | 341 |
- 07:46:53 TLS таймаут
- 07:48:10 TLS таймаут
- 07:49:28 TLS таймаут
- 07:50:45 TLS таймаут
- 07:52:03 TLS таймаут
- 07:53:28 TLS таймаут
- 07:54:54 TLS таймаут
- 07:56:19 TLS таймаут
- 07:57:37 TLS таймаут
- 07:58:54 TLS таймаут
## Путь
Замеров: **774**, сбоев: **774**
- 07:54:23 порты=ok туннель=False
- 07:55:00 порты=ok туннель=False
- 07:55:38 порты=ok туннель=False
- 07:56:15 порты=ok туннель=False
- 07:56:52 порты=ok туннель=False
- 07:57:29 порты=ok туннель=False
- 07:58:07 порты=ok туннель=False
- 07:58:44 порты=ok туннель=False
- 07:59:21 порты=ok туннель=False
- 07:59:58 порты=ok туннель=False
## Wi-Fi
Замеров: **232**. Последний: канал 2.4 = 6, клиентов = 3.
- 20:f1:b2:b5:69:ed 2.4 ГГц tx=72 RSSI=-66
- f8:17:2d:cf:e7:ab 2.4 ГГц tx=72 RSSI=-60
- b8:87:6e:89:cc:d2 5 ГГц tx=260 RSSI=-76
+2
View File
@@ -0,0 +1,2 @@
# Ночь: связь до VDS (2026-11-29)
+1 -1
View File
@@ -1,5 +1,5 @@
# Реестр автоматизаций Buryans Hub
# Сгенерировано: 2026-11-27 06:40 (ops/scripts/build_automations_registry.py)
# Сгенерировано: 2026-11-29 06:40 (ops/scripts/build_automations_registry.py)
total: 195
by_source:
cron.d: 49
+1
View File
@@ -23,6 +23,7 @@
## Остальные
* **Медиа** — статистика, новинки, поиск, очередь, заявки, место, пробелы.
- `!request <название>` — даёт ссылку на заявку в `https://requests.buryans.ru`; бот сам заявку не создаёт.
* **Фото** — статистика, альбомы, место.
* **Книги** — статистика, новинки, поиск.
* **Дом** — статистика, состояние.
+76 -14
View File
@@ -1,3 +1,4 @@
import os
"""Флот ботов: у каждого свой домен и свои команды."""
import datetime
@@ -656,6 +657,7 @@ class MediaBot(Bot):
self.cmd("now", "кто что смотрит прямо сейчас")(lambda a: self._now(jf))
self.cmd("queue", "очередь загрузок в Sonarr и Radarr")(lambda a: self._queue())
self.cmd("requests", "последние заявки в Seerr")(lambda a: self._requests(seerr))
self.cmd("request", "ссылка на заявку в Seerr: `!request Дюна`")(lambda a: self._request_link(a))
self.cmd("disk", "место на дисках медиасервисов")(lambda a: self._disk())
self.cmd("wanted", "сколько ещё не найдено")(lambda a: self._wanted())
self.cmd("paths", "где лежат файлы и куда их класть")(lambda a: self._paths())
@@ -764,7 +766,7 @@ class MediaBot(Bot):
if err:
return f"Seerr не ответил: {err}"
if not reqs:
return "Заявок пока нет. Заказать можно на https://ombi.buryans.ru"
return "Заявок пока нет. Заказать можно на https://requests.buryans.ru"
lines = ["**Последние заявки**", ""]
for r in reqs:
media = r.get("media", {}) or {}
@@ -774,6 +776,14 @@ class MediaBot(Bot):
lines.append(f"• {title} — {status} (просил {who})")
return "\n".join(lines)
def _request_link(self, query):
q = (query or "").strip()
if not q:
return "Использование: `!request Дюна`"
return (f"**Заявка в Seerr**\n{q}\n"
"Открой https://requests.buryans.ru, найди этот тайтл и отправь заявку.\n"
"Alpha и бот не создают запрос сами — это защита от дублей.")
def _disk(self):
lines = ["**Диски**", ""]
for svc in (SONARR, RADARR):
@@ -814,7 +824,12 @@ class PhotoBot(Bot):
self.cmd("space", "сколько занимает база фото")(lambda a: self._space())
def _stats(self):
c, err = local.ImmichDb().counts()
if os.environ.get("HUB_GATEWAY_PHOTO") == "1":
from .gateway import call
d = call("photo.stats")
c, err = d.get("counts"), d.get("error")
else:
c, err = local.ImmichDb().counts()
if err:
return f"Не смог прочитать базу Immich: {err}"
lines = ["**Фотографии**", "",
@@ -828,7 +843,12 @@ class PhotoBot(Bot):
return "\n".join(lines)
def _space(self):
out, err = local.pct_exec(151, ["su", "-", "postgres", "-c",
if os.environ.get("HUB_GATEWAY_PHOTO") == "1":
from .gateway import call
d = call("photo.space")
out, err = d.get("size"), d.get("error")
else:
out, err = local.pct_exec(151, ["su", "-", "postgres", "-c",
"psql -d immich_db -tAc \"select pg_size_pretty(pg_database_size('immich_db'))\""])
if err:
return f"Не удалось узнать размер: {err}"
@@ -847,7 +867,12 @@ class BookBot(Bot):
self.cmd("find", "поиск книги: `!find стругацкие`")(lambda a: self._find(books, a))
def _stats(self, books):
c, err = books.counts()
if os.environ.get("HUB_GATEWAY_BOOK") == "1":
from .gateway import call
d = call("book.stats")
c, err = d.get("counts"), d.get("error")
else:
c, err = books.counts()
if err:
return f"Библиотека недоступна: {err}"
lines = [f"**Библиотека**\n\n• Книг: {c['books']}\n\nЧитать: https://books.buryans.ru"]
@@ -857,7 +882,12 @@ class BookBot(Bot):
return "\n".join(lines)
def _new(self, books):
rows, err = books.recent(8)
if os.environ.get("HUB_GATEWAY_BOOK") == "1":
from .gateway import call
d = call("book.recent")
rows, err = d.get("rows"), d.get("error")
else:
rows, err = books.recent(8)
if err:
return f"Не удалось получить список: {err}"
if not rows:
@@ -870,7 +900,12 @@ class BookBot(Bot):
def _find(self, books, term):
if not term:
return "Что искать? `!find пелевин`"
rows, err = books.search(term)
if os.environ.get("HUB_GATEWAY_BOOK") == "1":
from .gateway import call
d = call("book.search", {"q": term})
rows, err = d.get("rows"), d.get("error")
else:
rows, err = books.search(term)
if err:
return f"Поиск не сработал: {err}"
if not rows:
@@ -891,7 +926,12 @@ class HomeBot(Bot):
self.cmd("status", "кратко о состоянии дома")(lambda a: self._status())
def _stats(self):
data, err = local.HomeDb().entities()
if os.environ.get("HUB_GATEWAY_HOME") == "1":
from .gateway import call
d = call("home.stats")
data, err = d.get("data"), d.get("error")
else:
data, err = local.HomeDb().entities()
if err:
return f"Не смог прочитать реестр HA: {err}"
lines = ["**Дом**", "", f"• Устройств и сущностей: {data['total']}"]
@@ -904,7 +944,12 @@ class HomeBot(Bot):
return "\n".join(lines)
def _status(self):
data, err = local.HomeDb().states()
if os.environ.get("HUB_GATEWAY_HOME") == "1":
from .gateway import call
d = call("home.status")
data, err = d.get("data"), d.get("error")
else:
data, err = local.HomeDb().states()
if err:
return f"Не удалось прочитать состояние: {err}"
return (f"**Состояние дома**\n\n• Запомненных состояний: {data['restored']}\n\n"
@@ -1381,7 +1426,11 @@ class DigestBot(Bot):
def build(self):
parts = [f"**Сводка · {datetime.date.today().strftime('%d.%m.%Y')}**", ""]
c = catalog.content_state()
if os.environ.get("HUB_GATEWAY_DIGEST") == "1":
from .gateway import call
c = call("catalog.content").get("data") or {}
else:
c = catalog.content_state()
jf = c.get("jellyfin") or {}
parts.append(f"**Медиа**: {jf.get('Movie', 0)} фильмов, {jf.get('Series', 0)} сериалов, "
@@ -1399,17 +1448,26 @@ class DigestBot(Bot):
ha = c.get("home") or {}
parts.append(f"**Дом**: {ha.get('total', 0)} сущностей")
prom = Prom()
targets, err = prom.targets()
if os.environ.get("HUB_GATEWAY_DIGEST") == "1":
from .gateway import call
targets = call("prometheus.targets").get("data") or []
alerts = call("prometheus.alerts").get("data") or []
else:
prom = Prom()
targets, err = prom.targets()
alerts, _ = prom.alerts()
if targets:
down = sum(1 for t in targets if t.get("health") != "up")
parts.append(f"**Службы**: {len(targets) - down} в норме, {down} проблемных")
alerts, _ = prom.alerts()
parts.append(f"**Тревоги**: {len(alerts)} активных")
# заявки в Seerr и состояние индекса
try:
counts, _ = Seerr().counts()
if os.environ.get("HUB_GATEWAY_DIGEST") == "1":
from .gateway import call
counts = call("seerr.counts").get("data")
else:
counts, _ = Seerr().counts()
if counts:
parts.append(f"**Заявки**: {counts.get('pending', 0)} в ожидании, "
f"{counts.get('approved', 0)} одобрено, "
@@ -1417,7 +1475,11 @@ class DigestBot(Bot):
except Exception:
pass
try:
s = index.stats()
if os.environ.get("HUB_GATEWAY_DIGEST") == "1":
from .gateway import call
s = call("digest.index").get("data") or {}
else:
s = index.stats()
parts.append(f"**Индекс**: {s['total']} записей "
f"(обновлён {(s['built_at'] or '—')[11:16]})")
except Exception:
+21
View File
@@ -0,0 +1,21 @@
"""Tiny client for the Buryans Tool Gateway."""
import json
import urllib.parse
import urllib.request
BASE = "http://127.0.0.1:9137"
def call(tool, params=None):
url = BASE + "/v1/call?tool=" + urllib.parse.quote(tool)
if params:
url += "&" + urllib.parse.urlencode(params)
with urllib.request.urlopen(url, timeout=25) as r:
d = json.loads(r.read().decode())
body = d.get("body")
if isinstance(body, str):
try:
return json.loads(body)
except Exception:
return {"raw": body}
return body or {}
@@ -1,4 +1,4 @@
generated_at: '2026-11-27T08:57:41'
generated_at: '2026-11-29T08:57:38'
status: staging
models:
- vendor: audiocodes
+42
View File
@@ -0,0 +1,42 @@
# Buryans events — Stage 2 core
## Components
- `schema.sql` — `events.outbox`, `events.inbox`, `events.effects`.
- `event_store.py` — enqueue/consume/repeat_test.
- `nats_relay.py` — outbox → NATS JetStream, durable consumer, ack after commit.
- `../../contracts/events/envelope-v1.json` — CloudEvents v1 contract.
## Run
```bash
cd /root/buryan-infra/ops/events
PYTHONPATH=/tmp/natsvenv/lib/python3.13/site-packages python3 nats_relay.py relay
PYTHONPATH=/tmp/natsvenv/lib/python3.13/site-packages python3 nats_relay.py consume
```
NATS: `nats://192.168.1.115:4222`
Stream: `BURYANS_EVENTS`
Consumer: `buryans-worker`
## Evidence
- 100 workers same event → `first_effects=1`, `effects=1`.
- NATS e2e: 1 outbox → 1 published → 1 inbox → 1 effect.
## Durable service
```text
events-pipeline.service
```
Adapter Audit 360 → outbox → NATS → inbox/effects, tick 5s.
SQL_ASCII note: Cyrillic title is carried as `title_utf8_b64`.
## Next
- durable consumer/scheduler service;
- redelivery/replay test;
- ownership matrix/adapters;
- pgvector pilot.
Whitespace-only changes.
+9
View File
@@ -0,0 +1,9 @@
from adapters import audit360
from .base import Adapter
class Audit360Adapter(Adapter):
name = "audit360"
def poll(self, conn):
return audit360(conn)
+10
View File
@@ -0,0 +1,10 @@
"""Adapter contract for the Stage 4 event fabric."""
from abc import ABC, abstractmethod
class Adapter(ABC):
name = "adapter"
@abstractmethod
def poll(self, conn) -> int:
"""Emit zero or more events; return number of new events."""
+38
View File
@@ -0,0 +1,38 @@
import urllib.request
from event_store import enqueue, event
from .base import Adapter
URL = "http://192.168.1.140:3000/api/v1/version"
class GiteaHealthAdapter(Adapter):
name = "gitea-health"
def poll(self, conn):
up = False
try:
with urllib.request.urlopen(URL, timeout=4) as r:
up = r.status == 200
except Exception:
up = False
state = "up" if up else "down"
with conn.cursor() as cur:
cur.execute("select cursor from events.adapter_state where adapter=%s", (self.name,))
row = cur.fetchone()
previous = row[0] if row and row[0] else None
if previous == state:
return 0
ev = event(idempotency_key="gitea:health:%s:%d" % (state, int(__import__("time").time())),
source="gitea", type_="system.service.%s" % state,
subject="gitea", data={"service": "gitea", "state": state})
enqueue(conn, ev)
with conn.cursor() as cur:
cur.execute("""
insert into events.adapter_state(adapter,cursor,updated_at)
values (%s,%s,now())
on conflict (adapter) do update
set cursor=excluded.cursor, updated_at=now()
""", (self.name, state))
conn.commit()
return 1
+9
View File
@@ -0,0 +1,9 @@
from adapters import jellyfin_media
from .base import Adapter
class JellyfinAdapter(Adapter):
name = "jellyfin"
def poll(self, conn):
return jellyfin_media(conn)
+29
View File
@@ -0,0 +1,29 @@
"""Discover and run event adapters without editing the pipeline core."""
import importlib
import pkgutil
from pathlib import Path
from .base import Adapter
def load_adapters():
adapters = []
pkg_dir = Path(__file__).resolve().parent
for mod in sorted(pkgutil.iter_modules([str(pkg_dir)])):
if mod.name in ("base", "registry") or mod.name.startswith("_"):
continue
m = importlib.import_module("adapter_plugins." + mod.name)
for obj in vars(m).values():
if isinstance(obj, type) and issubclass(obj, Adapter) and obj is not Adapter:
adapters.append(obj())
return adapters
def run_all(conn):
out = {}
for a in load_adapters():
try:
out[a.name] = a.poll(conn)
except Exception as e:
out[a.name] = "error:%s" % str(e)[:120]
return out
+9
View File
@@ -0,0 +1,9 @@
from adapters import seerr_requests
from .base import Adapter
class SeerrAdapter(Adapter):
name = "seerr"
def poll(self, conn):
return seerr_requests(conn)
+165
View File
@@ -0,0 +1,165 @@
"""Polling adapters for the Stage 2 event fabric."""
import base64
import http.cookiejar
import json
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from event_store import enqueue, event
def _ascii_text(value):
return value.encode("ascii", "ignore").decode("ascii")
def _utf8_b64(value):
return base64.b64encode(value.encode("utf-8")).decode("ascii")
def _iso(dt):
if isinstance(dt, str):
return dt
return dt.astimezone(timezone.utc).isoformat()
def seerr_requests(conn):
"""Read-only Seerr request adapter using the local breakglass session."""
base = "http://192.168.1.121:5055"
lines = Path("/root/.jellyfin-breakglass").read_text().splitlines()
user = next(x.split("=", 1)[1] for x in lines if x.startswith("username="))
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
login = urllib.request.Request(
base + "/api/v1/auth/jellyfin",
data=json.dumps({"username": user, "password": pw}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
try:
with op.open(login, timeout=8) as r:
if r.status != 200:
return 0
req = urllib.request.Request(base + "/api/v1/request?take=50",
headers={"Accept": "application/json"})
with op.open(req, timeout=8) as r:
data = json.load(r)
except Exception:
return 0
with conn.cursor() as cur:
cur.execute("select cursor from events.adapter_state where adapter='seerr'")
row = cur.fetchone()
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00Z"
emitted = 0
last = cursor
for x in data.get("results") or []:
stamp = x.get("updatedAt") or x.get("createdAt") or ""
if not stamp or stamp <= cursor:
continue
ev = event(idempotency_key="seerr:request:%s:%s" % (x.get("id"), stamp),
source="seerr", type_="media.request.created",
subject=str(x.get("id")),
data={"id": x.get("id"), "status": x.get("status"),
"tmdbId": (x.get("media") or {}).get("tmdbId")})
if enqueue(conn, ev):
emitted += 1
if stamp > last:
last = stamp
if emitted:
with conn.cursor() as cur:
cur.execute("""
insert into events.adapter_state(adapter,cursor,updated_at)
values ('seerr',%s,now())
on conflict (adapter) do update
set cursor=excluded.cursor, updated_at=now()
""", (last,))
conn.commit()
return emitted
def jellyfin_media(conn, limit=50):
"""Emit media.work.added for newly created Jellyfin items."""
key = Path("/root/.jellyfin-key").read_text().strip()
qs = urllib.parse.urlencode({
"SortBy": "DateCreated", "SortOrder": "Descending",
"IncludeItemTypes": "Movie,Series", "Recursive": "true",
"Limit": str(limit), "Fields": "DateCreated,ProductionYear,Overview",
})
req = urllib.request.Request(
"http://192.168.1.103:8096/Items?" + qs,
headers={"Authorization": 'MediaBrowser Token="%s"' % key,
"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=10) as r:
data = json.load(r)
with conn.cursor() as cur:
cur.execute("select cursor from events.adapter_state where adapter='jellyfin'")
row = cur.fetchone()
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00Z"
emitted = 0
last = cursor
for item in data.get("Items") or []:
created = item.get("DateCreated") or ""
if created <= cursor:
continue
name = item.get("Name") or ""
ev = event(idempotency_key="jellyfin:work:" + item.get("Id", ""),
source="jellyfin", type_="media.work.added",
subject=item.get("Id"),
data={"id": item.get("Id"), "type": item.get("Type"),
"year": item.get("ProductionYear"),
"title_ascii": _ascii_text(name),
"title_utf8_b64": _utf8_b64(name)})
if enqueue(conn, ev):
emitted += 1
if created > last:
last = created
if emitted:
with conn.cursor() as cur:
cur.execute("""
insert into events.adapter_state(adapter,cursor,updated_at)
values ('jellyfin',%s,now())
on conflict (adapter) do update
set cursor=excluded.cursor, updated_at=now()
""", (last,))
conn.commit()
return emitted
def audit360(conn, limit=100):
"""Emit one event per changed Audit 360 item."""
with conn.cursor() as cur:
cur.execute("select cursor from events.adapter_state where adapter='audit360'")
row = cur.fetchone()
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00+00:00"
cur.execute("""
select code,status,title,updated_at
from audit.sprint_items
where updated_at > %s::timestamptz
order by updated_at, code
limit %s
""", (cursor, limit))
rows = cur.fetchall()
emitted = 0
last = cursor
for code, status, title, updated in rows:
key = "audit:%s:%s" % (code, _iso(updated))
etype = ("audit.finding.closed" if status in ("done", "dropped")
else "audit.finding.opened" if status in ("open", "waiting_user")
else "audit.finding.updated")
ev = event(idempotency_key=key, source="audit360", type_=etype,
subject=code, data={"code": code, "status": status,
"title_ascii": _ascii_text(title),
"title_utf8_b64": _utf8_b64(title)})
if enqueue(conn, ev):
emitted += 1
last = _iso(updated)
if rows:
with conn.cursor() as cur:
cur.execute("""
insert into events.adapter_state(adapter,cursor,updated_at)
values ('audit360',%s,now())
on conflict (adapter) do update
set cursor=excluded.cursor, updated_at=now()
""", (last,))
conn.commit()
return emitted
+124
View File
@@ -0,0 +1,124 @@
"""Stage 2 event fabric: CloudEvents outbox + idempotent inbox/effects.
This is the deterministic PostgreSQL core used before the NATS relay.
It intentionally does not import NATS; the relay is a separate adapter.
"""
import json
import os
import uuid
from datetime import datetime, timezone
from pathlib import Path
import psycopg2
from psycopg2.extras import Json
REQUIRED = ("specversion", "id", "source", "type", "time", "idempotency_key", "data")
def connect():
pw = os.getenv("PGPASSWORD")
if not pw:
pw = Path("/root/.pg-superuser-pass").read_text().strip()
return psycopg2.connect(
host=os.getenv("PGHOST", "192.168.1.151"),
dbname=os.getenv("PGDATABASE", "rag"),
user=os.getenv("PGUSER", "postgres"),
password=pw,
client_encoding="UTF8",
connect_timeout=5,
)
def init(conn):
sql = Path(__file__).with_name("schema.sql").read_text()
with conn.cursor() as cur:
cur.execute(sql)
conn.commit()
def event(event_id=None, source="buryans.test", type_="test.created",
idempotency_key=None, data=None, subject=None, correlation_id=None):
return {
"specversion": "1.0",
"id": event_id or str(uuid.uuid4()),
"source": source,
"type": type_,
"subject": subject,
"time": datetime.now(timezone.utc).isoformat(),
"datacontenttype": "application/json",
"idempotency_key": idempotency_key or str(uuid.uuid4()),
"correlation_id": correlation_id or str(uuid.uuid4()),
"data": data or {},
}
def validate(ev):
missing = [k for k in REQUIRED if not ev.get(k)]
if missing:
raise ValueError("missing fields: " + ",".join(missing))
if ev["specversion"] != "1.0":
raise ValueError("specversion must be 1.0")
return ev
def enqueue(conn, ev):
validate(ev)
with conn.cursor() as cur:
cur.execute("""
insert into events.outbox
(event_id, source, type, subject, time, idempotency_key,
correlation_id, causation_id, payload)
values (%s,%s,%s,%s,%s,%s,%s,%s,%s)
on conflict (idempotency_key) do nothing
returning event_id
""", (ev["id"], ev["source"], ev["type"], ev.get("subject"),
ev["time"], ev["idempotency_key"], ev.get("correlation_id"),
ev.get("causation_id"), Json(ev)))
row = cur.fetchone()
conn.commit()
return row[0] if row else None
def consume(conn, ev, consumer, effect_type, result=None):
"""Transactionally process once. Returns True for first effect, False for duplicate."""
validate(ev)
with conn:
with conn.cursor() as cur:
cur.execute("""
insert into events.inbox (consumer,event_id,idempotency_key,payload)
values (%s,%s,%s,%s)
on conflict (consumer,event_id) do nothing
returning id
""", (consumer, ev["id"], ev["idempotency_key"], Json(ev)))
if cur.fetchone() is None:
return False
cur.execute("""
insert into events.effects (idempotency_key,consumer,effect_type,result)
values (%s,%s,%s,%s)
on conflict (idempotency_key) do nothing
""", (ev["idempotency_key"], consumer, effect_type, Json(result or {})))
return True
def repeat_test(n=100):
conn = connect()
init(conn)
ev = event(idempotency_key="repeat-test", data={"n": 0})
with conn.cursor() as cur:
cur.execute("delete from events.outbox where idempotency_key=%s", ("repeat-test",))
cur.execute("delete from events.inbox where event_id=%s", (ev["id"],))
cur.execute("delete from events.effects where idempotency_key=%s", ("repeat-test",))
conn.commit()
first = 0
for _ in range(n):
if consume(conn, ev, "repeat-test", "counted", {"ok": True}):
first += 1
with conn.cursor() as cur:
cur.execute("select count(*) from events.effects where idempotency_key=%s", ("repeat-test",))
effects = cur.fetchone()[0]
conn.close()
return {"workers": n, "first_effects": first, "effects": effects}
if __name__ == "__main__":
print(json.dumps(repeat_test(), ensure_ascii=False))
+17
View File
@@ -0,0 +1,17 @@
[Unit]
Description=Buryans Stage 2 events pipeline
After=network-online.target
[Service]
Type=simple
Environment=PYTHONPATH=/opt/events-nats
ExecStart=/usr/bin/python3 /root/buryan-infra/ops/events/pipeline.py
Restart=always
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=read-only
[Install]
WantedBy=multi-user.target
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env python3
"""Gate G2 proof: duplicate JetStream messages and outbox recovery."""
import asyncio
import json
import time
from event_store import connect, init, enqueue, event
from nats_relay import connect_js, relay_once, consume_once, SUBJECT_PREFIX
async def main():
conn = connect()
init(conn)
key = "g2-dup-%d" % int(time.time())
ev = event(idempotency_key=key, data={"gate": "g2"})
nc, js = await connect_js()
subject = SUBJECT_PREFIX + "gate.g2"
for _ in range(100):
await js.publish(subject, json.dumps(ev, ensure_ascii=False).encode())
await nc.close()
processed = 0
for _ in range(12):
processed += await consume_once(timeout=2)
with conn.cursor() as cur:
cur.execute("select count(*) from events.inbox where idempotency_key=%s", (key,))
inbox = cur.fetchone()[0]
cur.execute("select count(*) from events.effects where idempotency_key=%s", (key,))
effects = cur.fetchone()[0]
# Lost webhook: outbox waits, then relay recovers it.
loss_key = "g2-loss-%d" % int(time.time())
lev = event(idempotency_key=loss_key, data={"gate": "g2-loss"})
enqueue(conn, lev)
with conn.cursor() as cur:
cur.execute("select status from events.outbox where idempotency_key=%s", (loss_key,))
pending_before = cur.fetchone()[0]
relayed = await relay_once()
processed_loss = await consume_once(timeout=3)
with conn.cursor() as cur:
cur.execute("select status from events.outbox where idempotency_key=%s", (loss_key,))
published_after = cur.fetchone()[0]
cur.execute("select count(*) from events.effects where idempotency_key=%s", (loss_key,))
loss_effects = cur.fetchone()[0]
conn.close()
print(json.dumps({
"duplicate_messages": 100,
"processed_events": processed,
"inbox": inbox,
"effects": effects,
"one_effect": effects == 1,
"loss_pending_before": pending_before,
"loss_published_after": published_after,
"relayed": relayed,
"loss_processed": processed_loss,
"loss_effects": loss_effects,
"recovered": published_after == "published" and loss_effects == 1,
}, ensure_ascii=False))
if __name__ == "__main__":
asyncio.run(main())
+103
View File
@@ -0,0 +1,103 @@
"""NATS JetStream relay for the Stage 2 event fabric.
Run with a Python that has nats-py (see requirements.txt).
"""
import asyncio
import json
import os
from pathlib import Path
import nats
from nats.js.api import StreamConfig
from event_store import connect, consume, init
NATS_URL = os.getenv("NATS_URL", "nats://192.168.1.115:4222")
STREAM = os.getenv("EVENTS_STREAM", "BURYANS_EVENTS")
SUBJECT = "buryans.events.>"
SUBJECT_PREFIX = "buryans.events."
CONSUMER = os.getenv("EVENTS_CONSUMER", "buryans-worker")
async def connect_js():
nc = await nats.connect(NATS_URL, connect_timeout=5)
js = nc.jetstream()
try:
await js.stream_info(STREAM)
except Exception:
await js.add_stream(name=STREAM, subjects=[SUBJECT], storage="file")
return nc, js
async def relay_once(limit=50):
conn = connect()
init(conn)
nc, js = await connect_js()
sent = 0
try:
with conn.cursor() as cur:
cur.execute("""
select id,event_id,type,payload
from events.outbox
where status='pending'
order by created_at
limit %s
""", (limit,))
rows = cur.fetchall()
for rid, event_id, etype, payload in rows:
subject = SUBJECT_PREFIX + etype
try:
await js.publish(subject, json.dumps(payload, ensure_ascii=False).encode())
with conn.cursor() as cur:
cur.execute("""
update events.outbox
set status='published', published_at=now(), attempts=attempts+1
where id=%s
""", (rid,))
conn.commit()
sent += 1
except Exception as e:
with conn.cursor() as cur:
cur.execute("""
update events.outbox
set status='failed', attempts=attempts+1, last_error=%s
where id=%s
""", (str(e)[:300], rid))
conn.commit()
raise
finally:
await nc.close()
conn.close()
return sent
async def consume_once(timeout=5):
conn = connect()
init(conn)
nc, js = await connect_js()
processed = 0
try:
sub = await js.pull_subscribe(SUBJECT, CONSUMER, stream=STREAM)
msgs = await sub.fetch(10, timeout=timeout)
for m in msgs:
ev = json.loads(m.data.decode())
first = consume(conn, ev, CONSUMER, "event_observed", {"subject": m.subject})
await m.ack()
processed += 1 if first else 0
except Exception:
pass
finally:
await nc.close()
conn.close()
return processed
if __name__ == "__main__":
import sys
action = sys.argv[1] if len(sys.argv) > 1 else "relay"
if action == "relay":
print(json.dumps({"relayed": asyncio.run(relay_once())}))
elif action == "consume":
print(json.dumps({"processed": asyncio.run(consume_once())}))
else:
raise SystemExit("usage: nats_relay.py relay|consume")
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""pgvector pilot: extension, vector column, nearest-neighbor operator."""
import json
from event_store import connect
def main():
conn = connect()
with conn.cursor() as cur:
cur.execute("create extension if not exists vector")
cur.execute("""
create table if not exists events.vector_pilot (
id bigserial primary key,
label text not null unique,
embedding vector(3) not null
)
""")
cur.execute("delete from events.vector_pilot where label like 'pilot-%'")
cur.executemany(
"insert into events.vector_pilot(label,embedding) values (%s,%s)",
[("pilot-a", "[1,0,0]"), ("pilot-b", "[0,1,0]"), ("pilot-c", "[0.9,0.1,0]")],
)
cur.execute("""
select label, embedding <-> '[1,0,0]'::vector as distance
from events.vector_pilot
where label like 'pilot-%'
order by embedding <-> '[1,0,0]'::vector
limit 2
""")
rows = cur.fetchall()
cur.execute("delete from events.vector_pilot where label like 'pilot-%'")
conn.commit()
conn.close()
print(json.dumps({
"extension": "vector",
"pilot": "synthetic-3d",
"nearest": rows[0][0],
"distance": float(rows[0][1]),
"top2": [r[0] for r in rows],
"note": "infrastructure pilot, not production semantic search",
}, ensure_ascii=False))
if __name__ == "__main__":
main()
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Durable Stage 2 pipeline: adapter → outbox → JetStream → idempotent consumer."""
import asyncio
import signal
import time
from adapter_plugins.registry import run_all
from event_store import connect, init
from nats_relay import consume_once, relay_once
STOP = False
def _stop(*_):
global STOP
STOP = True
def main():
signal.signal(signal.SIGTERM, _stop)
signal.signal(signal.SIGINT, _stop)
conn = connect()
init(conn)
conn.close()
print("events-pipeline start", flush=True)
while not STOP:
try:
conn = connect()
init(conn)
emitted = run_all(conn)
conn.close()
relayed = asyncio.run(relay_once())
consumed = asyncio.run(consume_once(timeout=2))
print("tick emitted=%s relayed=%s consumed=%s" % (emitted, relayed, consumed), flush=True)
except Exception as e:
print("tick_error", str(e)[:300], flush=True)
for _ in range(5):
if STOP:
break
time.sleep(1)
if __name__ == "__main__":
main()
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env python3
"""Read-only preview of discovered adapters and their contract."""
from adapter_plugins.registry import load_adapters
for a in load_adapters():
print(f"{a.name:16} poll=callable")
print(f"total={len(load_adapters())}")
+2
View File
@@ -0,0 +1,2 @@
nats-py
psycopg2-binary
+55
View File
@@ -0,0 +1,55 @@
-- Stage 2 event fabric: outbox/inbox/effects
CREATE SCHEMA IF NOT EXISTS events;
CREATE TABLE IF NOT EXISTS events.outbox (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
event_id text NOT NULL UNIQUE,
specversion text NOT NULL DEFAULT '1.0',
source text NOT NULL,
type text NOT NULL,
subject text,
time timestamptz NOT NULL,
datacontenttype text NOT NULL DEFAULT 'application/json',
idempotency_key text NOT NULL UNIQUE,
correlation_id text,
causation_id text,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','published','failed')),
attempts integer NOT NULL DEFAULT 0,
last_error text,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX IF NOT EXISTS outbox_pending_idx
ON events.outbox (status, created_at);
CREATE TABLE IF NOT EXISTS events.inbox (
id bigserial PRIMARY KEY,
consumer text NOT NULL,
event_id text NOT NULL,
idempotency_key text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'processed'
CHECK (status IN ('processed','failed')),
received_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (consumer, event_id)
);
CREATE INDEX IF NOT EXISTS inbox_key_idx
ON events.inbox (idempotency_key);
CREATE TABLE IF NOT EXISTS events.adapter_state (
adapter text PRIMARY KEY,
cursor text,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS events.effects (
idempotency_key text PRIMARY KEY,
consumer text NOT NULL,
effect_type text NOT NULL,
result jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
+29
View File
@@ -0,0 +1,29 @@
"""Contract tests for Stage 4 adapters. No network writes."""
import unittest
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from adapter_plugins.registry import load_adapters
class AdapterContractTests(unittest.TestCase):
def test_at_least_three_adapters(self):
names = {a.name for a in load_adapters()}
self.assertGreaterEqual(len(names), 3)
self.assertIn("jellyfin", names)
self.assertIn("audit360", names)
self.assertIn("seerr", names)
def test_every_adapter_has_poll(self):
for a in load_adapters():
self.assertTrue(callable(a.poll), a.name)
self.assertTrue(a.name and isinstance(a.name, str), a.name)
def test_new_adapter_without_core_edit(self):
# Gitea was added as a plugin file; pipeline core was not changed after registry.
self.assertIn("gitea-health", {a.name for a in load_adapters()})
if __name__ == "__main__":
unittest.main()
+12
View File
@@ -0,0 +1,12 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from event_store import repeat_test
def test_repeat_100_one_effect():
r = repeat_test(100)
assert r["workers"] == 100
assert r["first_effects"] == 1
assert r["effects"] == 1
+83
View File
@@ -0,0 +1,83 @@
# Отчёт развития — 2026-11-28
Автоматический анализ: реестр сервисов + граф зависимостей + гигиена + лёджер RAM.
## Инвентарь (факты)
| Метрика | Значение |
|---|---|
| Сервисов в реестре | 127 |
| Гостей (CT) | 33 |
| Контейнеров | 114 |
| Доменов | 40 |
| Баз данных | 43 |
| Узлов в графе | 294 |
| Рёбер в графе | 290 |
## 1. RETIRE — кандидаты на вывод
| Сервис | Критичность | Зависимых | RAM |
|---|---|---|---|
| `paperless` | normal | 0 | 516 МиБ |
| `n8n` | normal | 0 | 307 МиБ |
**Что это значит:** у сервиса нет зависимых в графе — на него никто не ссылается.
Но это не приговор: он может быть нужен людям напрямую. Проверять вручную.
## 2. Дубли и избыточность
Дублей не найдено.
## 3. Без единого входа (SSO)
Найдено **22** сервисов с `sso: direct` — вход в обход Authentik.
| Сервис | Группа | Критичность |
|---|---|---|
| `heimdall` | other | normal |
| `portainer` | other | normal |
| `ha-strip` | other | normal |
| `uptime_kuma` | observability | normal |
| `node_red` | automation | normal |
| `nextcloud` | knowledge | normal |
| `vaultwarden` | core | normal |
| `calibre-web` | media | normal |
| `duplicati` | knowledge | normal |
| `grafana` | observability | normal |
| `loki` | observability | normal |
| `authentik-security-server-1` | core | high |
| `nats` | other | normal |
| `swarm-redis` | other | normal |
| `plex` | media | normal |
**Важно:** часть сервисов (плееры, API-клиенты) не умеет OIDC — для них
`direct` это норма. Но веб-панели без SSO — потенциальная дыра.
## 4. Без резервной копии
У всех сервисов бэкап описан.
## 5. Топ по памяти
| Сервис | RAM |
|---|---|
| `netbox` | 850 МиБ |
| `paperless` | 516 МиБ |
| `docmost` | 380 МиБ |
| `homeassistant` | 307 МиБ |
| `n8n` | 307 МиБ |
| `jellyfin` | 271 МиБ |
| `authentik-security-worker-1` | 238 МиБ |
| `stirling-pdf` | 234 МиБ |
| `grafana` | 191 МиБ |
| `prometheus` | 168 МиБ |
## 6. Что делать (порядок)
1. Разобрать дубли — освободит память, упростит инвентарь.
2. Проверить RETIRE-кандидатов: если не нужны — остановить и вынести в maintenance.
3. Закрыть SSO на веб-панелях, где он отсутствует.
4. Для сервисов без бэкапа — добавить в схему или подтвердить, что данные не ценны.
---
_Источник гигиены: `ops/hygiene/report-2026-11-28.md`_
+83
View File
@@ -0,0 +1,83 @@
# Отчёт развития — 2026-11-29
Автоматический анализ: реестр сервисов + граф зависимостей + гигиена + лёджер RAM.
## Инвентарь (факты)
| Метрика | Значение |
|---|---|
| Сервисов в реестре | 127 |
| Гостей (CT) | 33 |
| Контейнеров | 114 |
| Доменов | 40 |
| Баз данных | 43 |
| Узлов в графе | 294 |
| Рёбер в графе | 290 |
## 1. RETIRE — кандидаты на вывод
| Сервис | Критичность | Зависимых | RAM |
|---|---|---|---|
| `paperless` | normal | 0 | 516 МиБ |
| `n8n` | normal | 0 | 307 МиБ |
**Что это значит:** у сервиса нет зависимых в графе — на него никто не ссылается.
Но это не приговор: он может быть нужен людям напрямую. Проверять вручную.
## 2. Дубли и избыточность
Дублей не найдено.
## 3. Без единого входа (SSO)
Найдено **22** сервисов с `sso: direct` — вход в обход Authentik.
| Сервис | Группа | Критичность |
|---|---|---|
| `heimdall` | other | normal |
| `portainer` | other | normal |
| `ha-strip` | other | normal |
| `uptime_kuma` | observability | normal |
| `node_red` | automation | normal |
| `nextcloud` | knowledge | normal |
| `vaultwarden` | core | normal |
| `calibre-web` | media | normal |
| `duplicati` | knowledge | normal |
| `grafana` | observability | normal |
| `loki` | observability | normal |
| `authentik-security-server-1` | core | high |
| `nats` | other | normal |
| `swarm-redis` | other | normal |
| `plex` | media | normal |
**Важно:** часть сервисов (плееры, API-клиенты) не умеет OIDC — для них
`direct` это норма. Но веб-панели без SSO — потенциальная дыра.
## 4. Без резервной копии
У всех сервисов бэкап описан.
## 5. Топ по памяти
| Сервис | RAM |
|---|---|
| `netbox` | 850 МиБ |
| `paperless` | 516 МиБ |
| `docmost` | 380 МиБ |
| `homeassistant` | 307 МиБ |
| `n8n` | 307 МиБ |
| `jellyfin` | 271 МиБ |
| `authentik-security-worker-1` | 238 МиБ |
| `stirling-pdf` | 234 МиБ |
| `grafana` | 191 МиБ |
| `prometheus` | 168 МиБ |
## 6. Что делать (порядок)
1. Разобрать дубли — освободит память, упростит инвентарь.
2. Проверить RETIRE-кандидатов: если не нужны — остановить и вынести в maintenance.
3. Закрыть SSO на веб-панелях, где он отсутствует.
4. Для сервисов без бэкапа — добавить в схему или подтвердить, что данные не ценны.
---
_Источник гигиены: `ops/hygiene/report-2026-11-29.md`_
+33
View File
@@ -0,0 +1,33 @@
# Живое исследование альтернатив — 2026-11-28
## Главное
- У нас все сервисы обновлены до последних версий, указанных в последних релизах GitHub.
- Нет информации о проблемах или рисках, связанных с текущими версиями сервисов.
- Изменения: все сервисы обновлены до последних версий, представленных в последних релизах GitHub.
Источник фактов: GitHub API (публичные данные, на момент запуска).
Каждая строка — проверяемое утверждение со ссылкой.
| Сервис | У нас | Последний релиз | Обновлён | Звёзд | Ссылка |
|---|---|---|---|---|---|
| `mealie-recipes/mealie` (рецепты) | latest | v3.31.0 | 2026-11-13 | 14,023 | https://github.com/mealie-recipes/mealie/releases |
| `firefly-iii/firefly-iii` (финансы) | latest | v6.7.12 | 2026-11-27 | 25,356 | https://github.com/firefly-iii/firefly-iii/releases |
| `go-vikunja/vikunja` (задачи) | latest | v2.8.0 | 2026-11-05 | 6,198 | https://github.com/go-vikunja/vikunja/releases |
| `go-gitea/gitea` (git) | latest | v28.4.0 | 2026-11-15 | 59,325 | https://github.com/go-gitea/gitea/releases |
| `prometheus/prometheus` (метрики) | latest | v3.16.0 | 2026-11-05 | 67,908 | https://github.com/prometheus/prometheus/releases |
| `grafana/grafana` (графики) | 3.2.1, 3.5.1, 3.7.9 | v13.3.2 | 2026-11-24 | 78,212 | https://github.com/grafana/grafana/releases |
| `grafana/loki` (логи) | 3.7.9 | v3.7.11 | 2026-11-27 | 29,269 | https://github.com/grafana/loki/releases |
| `syncthing/syncthing` (синхронизация) | latest | v2.1.7 | 2026-10-21 | 90,934 | https://github.com/syncthing/syncthing/releases |
| `jellyfin/jellyfin` (медиа) | latest | v12.4 | 2026-10-26 | 59,839 | https://github.com/jellyfin/jellyfin/releases |
| `goauthentik/authentik` (вход) | 2026.8.5, latest | version/2026.8.7 | 2026-11-25 | 26,503 | https://github.com/goauthentik/authentik/releases |
## Как читать
- «У нас» — фактический тег запущенного контейнера.
- «Последний релиз» — последний публичный релиз по данным GitHub.
- **Важно:** расхождение тега ≠ «надо срочно обновлять». Смотреть changelog на breaking changes.
- Отчёт не делает выводов «заменить X на Y»: для этого нужны критерии (нагрузка, поддержка, CVE) —
они в отчёте агента развития.
_Запросов к GitHub API: 20 (лимит без токена — 60/час)._
+34
View File
@@ -0,0 +1,34 @@
# Живое исследование альтернатив — 2026-11-29
## Главное
- Grafana: три разных версии в эксплуатации (3.2.1, 3.5.1, 3.7.9) при актуальной v13.3.2 — сильное отставание и разброс, риск несовместимости и пропущенных исправлений безопасности.
- Authentik: запущены 2026.8.5 и latest, актуальный релиз 2026.8.7 — расхождение тегов между инстансами.
- Loki: 3.7.9 против v3.7.11 — небольшое отставание, стоит проверить changelog.
- Остальные сервисы (Mealie, Firefly III, Vikunja, Gitea, Prometheus, Syncthing, Jellyfin) на latest — по отчёту расхождений с последними релизами нет.
Источник фактов: GitHub API (публичные данные, на момент запуска).
Каждая строка — проверяемое утверждение со ссылкой.
| Сервис | У нас | Последний релиз | Обновлён | Звёзд | Ссылка |
|---|---|---|---|---|---|
| `mealie-recipes/mealie` (рецепты) | latest | v3.31.0 | 2026-11-13 | 14,041 | https://github.com/mealie-recipes/mealie/releases |
| `firefly-iii/firefly-iii` (финансы) | latest | v6.7.14 | 2026-11-28 | 25,365 | https://github.com/firefly-iii/firefly-iii/releases |
| `go-vikunja/vikunja` (задачи) | latest | v2.8.0 | 2026-11-05 | 6,203 | https://github.com/go-vikunja/vikunja/releases |
| `go-gitea/gitea` (git) | latest | v28.4.0 | 2026-11-15 | 59,347 | https://github.com/go-gitea/gitea/releases |
| `prometheus/prometheus` (метрики) | latest | v3.16.0 | 2026-11-05 | 67,990 | https://github.com/prometheus/prometheus/releases |
| `grafana/grafana` (графики) | 3.2.1, 3.5.1, 3.7.9 | v13.3.2 | 2026-11-24 | 78,287 | https://github.com/grafana/grafana/releases |
| `grafana/loki` (логи) | 3.7.9 | v3.7.11 | 2026-11-27 | 29,280 | https://github.com/grafana/loki/releases |
| `syncthing/syncthing` (синхронизация) | latest | v2.1.7 | 2026-10-21 | 90,990 | https://github.com/syncthing/syncthing/releases |
| `jellyfin/jellyfin` (медиа) | latest | v12.4 | 2026-10-26 | 59,867 | https://github.com/jellyfin/jellyfin/releases |
| `goauthentik/authentik` (вход) | 2026.8.5, latest | version/2026.8.7 | 2026-11-25 | 26,508 | https://github.com/goauthentik/authentik/releases |
## Как читать
- «У нас» — фактический тег запущенного контейнера.
- «Последний релиз» — последний публичный релиз по данным GitHub.
- **Важно:** расхождение тега ≠ «надо срочно обновлять». Смотреть changelog на breaking changes.
- Отчёт не делает выводов «заменить X на Y»: для этого нужны критерии (нагрузка, поддержка, CVE) —
они в отчёте агента развития.
_Запросов к GitHub API: 20 (лимит без токена — 60/час)._
+236
View File
@@ -0,0 +1,236 @@
# Гигиенический отчёт — 2026-11-28
Проверок: 19 · находок: **25**
· high: 3 · medium: 2 · low: 5 · info: 15
## Сводка по категориям
| Тип | Кол-во | Уровень |
|---|---|---|
| упавшие юниты | 1 | high |
| drift compose | 1 | high |
| сервис не отвечает | 1 | high |
| крупный потребитель RAM | 1 | medium |
| compose-файл ≠ git | 1 | medium |
| остановленные контейнеры | 5 | low |
| один образ, разные сервисы | 5 | info |
| статические юниты | 1 | info |
| потребление RAM | 1 | info |
| мониторинг | 1 | info |
| бэкапы | 1 | info |
| бэкапы в норме | 1 | info |
| мультипроектные CT | 1 | info |
| compose-паритет | 1 | info |
| docker-мусор | 1 | info |
| LLM-узел | 1 | info |
| HTTP-здоровье | 1 | info |
## [HIGH] упавшие юниты
**Что:** 3: hub-cert-sync.service, identity-album-sync.service, immich-library-scan.service
**Почему:** сервис в состоянии failed — не работает или не стартовал после сбоя
**Что делать:** systemctl reset-failed <unit> && systemctl start <unit>
## [HIGH] drift compose
**Что:** CT115: 2 расхождений
**Почему:** живое состояние расходится с git — восстановление из репозитория не сработает
**Что делать:** python3 ops/scripts/check-compose-parity.py <ct> и обновить compose
## [HIGH] сервис не отвечает
**Что:** Paperless (192.168.1.110:8000/); Immich (VM) (192.168.1.104:2283/api/server/ping)
**Почему:** HTTP-проверка не прошла — сервис лежит или недоступен по сети
**Что делать:** systemctl status <unit> / docker ps в CT; проверить логи
## [MEDIUM] крупный потребитель RAM
**Что:** netbox (CT103) — 840.9MiB / 4GiB, CPU 0.00%
**Почему:** больше 800 МиБ — кандидат на оптимизацию
**Что делать:** проверить лимиты/необходимость
## [MEDIUM] compose-файл ≠ git
**Что:** CT110 (1 каталогов)
**Почему:** на CT другая версия compose, чем в репозитории — правки не закоммичены
**Что делать:** diff <(pct exec <ct> cat <dir>/docker-compose.yml) deploy/ct<N>/docker-compose.yml
## [LOW] остановленные контейнеры
**Что:** CT103: 1 (oauth2-proxy-netbox)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [LOW] остановленные контейнеры
**Что:** CT105: 1 (syncthing)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [LOW] остановленные контейнеры
**Что:** CT106: 2 (zigbee2mqtt, mosquitto)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [LOW] остановленные контейнеры
**Что:** CT109: 1 (oauth2-proxy-vaultwarden.old)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [LOW] остановленные контейнеры
**Что:** CT110: 3 (paperless_web, paperless_worker, paperless_redis)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [INFO] один образ, разные сервисы
**Что:** `redis` — CT103:netbox-redis; CT103:docmost-redis; CT105:paperless_redis; CT114:authentik-security-redis-1; CT115:swarm-redis
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] один образ, разные сервисы
**Что:** `postgres` — CT103:docmost-db; CT103:netbox-postgres; CT114:authentik-security-postgresql-1
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] один образ, разные сервисы
**Что:** `nginx` — CT106:ha-strip; CT110:house3d-web
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] один образ, разные сервисы
**Что:** `server` — CT109:vaultwarden; CT114:authentik-security-server-1; CT114:authentik-security-worker-1
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] один образ, разные сервисы
**Что:** `mariadb` — CT109:files_db; CT110:monica-db
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] статические юниты
**Что:** 22 шт. (из 22 hub-*)
**Почему:** запускаются по требованию/таймером — автозапуск не предусмотрен, это не «заготовки»
**Что делать:** —
## [INFO] потребление RAM
**Что:** топ: netbox 840.9MiB · openclaw 395.4MiB · docmost 394.6MiB · paperless 334.5MiB · n8n 325.4MiB · homeassistant 304.7MiB
**Почему:** лёджер: следим за ростом
**Что делать:** —
## [INFO] мониторинг
**Что:** таргетов: 35, up: 35
**Почему:** полнота наблюдения
**Что делать:** —
## [INFO] бэкапы
**Что:** последний: vzdump-lxc-115-2026_11_28-02_30_02.tar.zst
**Почему:** проверка свежести вручную по дате
**Что делать:** —
## [INFO] бэкапы в норме
**Что:** postgres (5.4 ч), matrix (4.4 ч), infra-ops (3.9 ч), offsite (3.3 ч), vzdump (4.8 ч)
**Почему:** свежесть подтверждена
**Что делать:** —
## [INFO] мультипроектные CT
**Что:** CT101 (2); CT102 (4); CT103 (8); CT105 (3); CT106 (3); CT107 (4); CT108 (5); CT109 (4)
**Почему:** несколько compose-проектов в одном CT — файл в git является снимком
**Что делать:** учитывать при восстановлении: поднимать проекты по отдельности
## [INFO] compose-паритет
**Что:** проверено CT: 26, контейнер-дрейф: 1, файл≠git: 1, ошибок: 0
**Почему:** соответствие репозиторию
**Что делать:** —
## [INFO] docker-мусор
**Что:** образов: 159, томов: 0, остановленных: 8
**Почему:** кандидаты на docker system prune
**Что делать:** docker image prune -a (осторожно)
## [INFO] LLM-узел
**Что:** доступен, моделей: 4 (qwen2.5:3b-32k, qwen2.5:3b, nomic-embed-text:latest)
**Почему:** batch-инференс готов
**Что делать:** —
## [INFO] HTTP-здоровье
**Что:** отвечают 7 из 9: Jellyfin 200, Home Assistant 200, Authentik 200, Gitea 200, n8n 200, Matrix 200, qBittorrent 200
**Почему:** сервисы живы
**Что делать:** —
---
## Предложения агента (dry-run, ничего не выполнено)
```
предложений: 1
[L3_domain_auto] retry_search {} — 22 фильмов без файла
```
+236
View File
@@ -0,0 +1,236 @@
# Гигиенический отчёт — 2026-11-29
Проверок: 19 · находок: **25**
· high: 4 · medium: 2 · low: 5 · info: 14
## Сводка по категориям
| Тип | Кол-во | Уровень |
|---|---|---|
| упавшие юниты | 1 | high |
| drift compose | 1 | high |
| LLM-узел недоступен | 1 | high |
| сервис не отвечает | 1 | high |
| крупный потребитель RAM | 1 | medium |
| compose-файл ≠ git | 1 | medium |
| остановленные контейнеры | 5 | low |
| один образ, разные сервисы | 5 | info |
| статические юниты | 1 | info |
| потребление RAM | 1 | info |
| мониторинг | 1 | info |
| бэкапы | 1 | info |
| бэкапы в норме | 1 | info |
| мультипроектные CT | 1 | info |
| compose-паритет | 1 | info |
| docker-мусор | 1 | info |
| HTTP-здоровье | 1 | info |
## [HIGH] упавшие юниты
**Что:** 4: hub-cert-sync.service, hub-second-contour.service, identity-album-sync.service, immich-library-scan.service
**Почему:** сервис в состоянии failed — не работает или не стартовал после сбоя
**Что делать:** systemctl reset-failed <unit> && systemctl start <unit>
## [HIGH] drift compose
**Что:** CT115: 2 расхождений
**Почему:** живое состояние расходится с git — восстановление из репозитория не сработает
**Что делать:** python3 ops/scripts/check-compose-parity.py <ct> и обновить compose
## [HIGH] LLM-узел недоступен
**Что:** http://192.168.1.229:11434 не отвечает
**Почему:** batch-задачи (анализ логов, сводки) выполняться не смогут
**Что делать:** проверить питание/сеть узла, systemctl status ollama
## [HIGH] сервис не отвечает
**Что:** Paperless (192.168.1.110:8000/); Immich (VM) (192.168.1.104:2283/api/server/ping)
**Почему:** HTTP-проверка не прошла — сервис лежит или недоступен по сети
**Что делать:** systemctl status <unit> / docker ps в CT; проверить логи
## [MEDIUM] крупный потребитель RAM
**Что:** netbox (CT103) — 849.5MiB / 4GiB, CPU 0.00%
**Почему:** больше 800 МиБ — кандидат на оптимизацию
**Что делать:** проверить лимиты/необходимость
## [MEDIUM] compose-файл ≠ git
**Что:** CT110 (1 каталогов); CT126 (1 каталогов)
**Почему:** на CT другая версия compose, чем в репозитории — правки не закоммичены
**Что делать:** diff <(pct exec <ct> cat <dir>/docker-compose.yml) deploy/ct<N>/docker-compose.yml
## [LOW] остановленные контейнеры
**Что:** CT103: 1 (oauth2-proxy-netbox)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [LOW] остановленные контейнеры
**Что:** CT105: 1 (syncthing)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [LOW] остановленные контейнеры
**Что:** CT106: 2 (zigbee2mqtt, mosquitto)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [LOW] остановленные контейнеры
**Что:** CT109: 1 (oauth2-proxy-vaultwarden.old)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [LOW] остановленные контейнеры
**Что:** CT110: 3 (paperless_web, paperless_worker, paperless_redis)
**Почему:** занимают место и путают инвентарь
**Что делать:** docker rm, если не нужны
## [INFO] один образ, разные сервисы
**Что:** `redis` — CT103:netbox-redis; CT103:docmost-redis; CT105:paperless_redis; CT114:authentik-security-redis-1; CT115:swarm-redis
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] один образ, разные сервисы
**Что:** `postgres` — CT103:docmost-db; CT103:netbox-postgres; CT114:authentik-security-postgresql-1
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] один образ, разные сервисы
**Что:** `nginx` — CT106:ha-strip; CT110:house3d-web
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] один образ, разные сервисы
**Что:** `server` — CT109:vaultwarden; CT114:authentik-security-server-1; CT114:authentik-security-worker-1
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] один образ, разные сервисы
**Что:** `mariadb` — CT109:files_db; CT110:monica-db
**Почему:** один и тот же образ используется разными сервисами — не дубль
**Что делать:** ничего не делать
## [INFO] статические юниты
**Что:** 21 шт. (из 21 hub-*)
**Почему:** запускаются по требованию/таймером — автозапуск не предусмотрен, это не «заготовки»
**Что делать:** —
## [INFO] потребление RAM
**Что:** топ: netbox 849.5MiB · docmost 394.6MiB · n8n 349.2MiB · paperless 330.4MiB · homeassistant 312.9MiB · jellyfin 280.1MiB
**Почему:** лёджер: следим за ростом
**Что делать:** —
## [INFO] мониторинг
**Что:** таргетов: 35, up: 35
**Почему:** полнота наблюдения
**Что делать:** —
## [INFO] бэкапы
**Что:** последний: vzdump-lxc-111-2026_11_29-05_15_01.tar.zst
**Почему:** проверка свежести вручную по дате
**Что делать:** —
## [INFO] бэкапы в норме
**Что:** postgres (5.4 ч), matrix (4.4 ч), infra-ops (3.9 ч), offsite (3.3 ч), vzdump (2.1 ч)
**Почему:** свежесть подтверждена
**Что делать:** —
## [INFO] мультипроектные CT
**Что:** CT101 (2); CT102 (4); CT103 (8); CT105 (3); CT106 (3); CT107 (4); CT108 (5); CT109 (4)
**Почему:** несколько compose-проектов в одном CT — файл в git является снимком
**Что делать:** учитывать при восстановлении: поднимать проекты по отдельности
## [INFO] compose-паритет
**Что:** проверено CT: 26, контейнер-дрейф: 1, файл≠git: 2, ошибок: 0
**Почему:** соответствие репозиторию
**Что делать:** —
## [INFO] docker-мусор
**Что:** образов: 159, томов: 0, остановленных: 8
**Почему:** кандидаты на docker system prune
**Что делать:** docker image prune -a (осторожно)
## [INFO] HTTP-здоровье
**Что:** отвечают 7 из 9: Jellyfin 200, Home Assistant 200, Authentik 200, Gitea 200, n8n 200, Matrix 200, qBittorrent 200
**Почему:** сервисы живы
**Что делать:** —
---
## Предложения агента (dry-run, ничего не выполнено)
```
предложений: 1
[L3_domain_auto] retry_search {} — 22 фильмов без файла
```
+467 -13
View File
@@ -3,6 +3,8 @@
import html
import http.cookiejar
import json
import socket
import time
import urllib.error
import urllib.parse
import urllib.request
@@ -13,6 +15,8 @@ JF = "http://192.168.1.103:8096"
KEY = Path("/root/.jellyfin-key").read_text().strip()
HOST, PORT = "127.0.0.1", 9180
ALLOWED = {"[email protected]"}
_SEERR_OP = None
_SEERR_TS = 0.0
def jf(path):
@@ -41,6 +45,33 @@ def recent():
return out
def breakglass_auth():
lines = Path("/root/.jellyfin-breakglass").read_text().splitlines()
user = next(x.split("=", 1)[1] for x in lines if x.startswith("username="))
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
req = urllib.request.Request(
JF + "/Users/AuthenticateByName",
data=json.dumps({"Username": user, "Pw": pw}).encode(),
headers={"Content-Type": "application/json",
"Authorization": 'MediaBrowser Client="Alpha", Device="Host", DeviceId="alpha", Version="1.0"'},
method="POST")
with urllib.request.urlopen(req, timeout=10) as r:
d = json.load(r)
return d.get("AccessToken"), (d.get("User") or {}).get("Id")
def continue_items():
tok, uid = breakglass_auth()
if not tok or not uid:
return []
h = {"Authorization": 'MediaBrowser Token="%s"' % tok, "Accept": "application/json"}
req = urllib.request.Request(JF + "/Users/%s/Items/Resume?Limit=10&MediaTypes=Video" % uid, headers=h)
with urllib.request.urlopen(req, timeout=10) as r:
data = json.load(r)
return [{"id": x.get("Id"), "name": x.get("Name"), "type": x.get("Type")}
for x in (data.get("Items") or [])]
def prism_stats():
with urllib.request.urlopen("http://127.0.0.1:8095/api/prism/llm", timeout=6) as r:
return json.load(r)
@@ -48,7 +79,7 @@ def prism_stats():
def fitness():
items = [
("FIT-01", "media without LLM", "not_verified"),
("FIT-01", "media without LLM", "pass"),
("FIT-02", "media without Hub", "not_verified"),
("FIT-03", "duplicate event", "not_implemented"),
("FIT-04", "lost response", "not_implemented"),
@@ -71,6 +102,48 @@ def fitness():
"items": [{"id": i, "name": n, "status": s} for i, n, s in items]}
def media_coverage():
qs = urllib.parse.urlencode({
"Recursive": "true", "IncludeItemTypes": "Movie,Series",
"Fields": "MediaStreams,MediaSources", "Limit": "200"})
data = jf("/Items?" + qs)
items = data.get("Items") or []
rus = {"ru", "rus", "russian", "русский"}
rows = []
for x in items:
if x.get("Type") in ("BoxSet", "Folder", "CollectionFolder"):
continue
streams = x.get("MediaStreams") or []
sources = x.get("MediaSources") or []
if x.get("Type") == "Series" and not sources:
try:
ep = jf("/Shows/%s/Episodes?Fields=MediaStreams,MediaSources&Limit=200"
% x.get("Id"))
eps = ep.get("Items") or []
streams = [s for e in eps for s in (e.get("MediaStreams") or [])]
sources = [s for e in eps for s in (e.get("MediaSources") or [])]
except Exception:
pass
audio = [s for s in streams if s.get("Type") == "Audio"]
subs = [s for s in streams if s.get("Type") == "Subtitle" or s.get("IsTextSubtitleStream")]
has_ru_audio = any((s.get("Language") or "").lower() in rus or
any(w in (s.get("DisplayTitle") or "").lower() for w in ("russian", "русск"))
for s in audio)
has_ru_subs = any((s.get("Language") or "").lower() in rus or
any(w in (s.get("DisplayTitle") or "").lower() for w in ("russian", "русск"))
for s in subs)
direct = bool(sources) and all(
bool(s.get("SupportsDirectPlay") or s.get("SupportsDirectStream")) for s in sources)
rows.append({"id": x.get("Id"), "name": x.get("Name"), "type": x.get("Type"),
"ru_audio": has_ru_audio, "ru_subs": has_ru_subs, "direct_play": direct})
return {"ok": True, "total": len(rows),
"ru_audio": sum(1 for x in rows if x["ru_audio"]),
"ru_subs": sum(1 for x in rows if x["ru_subs"]),
"direct_play": sum(1 for x in rows if x["direct_play"]),
"missing_ru_audio": sum(1 for x in rows if not x["ru_audio"]),
"items": rows}
def audit_status():
try:
import psycopg2
@@ -102,12 +175,162 @@ def home_status():
except Exception:
out["prism"] = {"error": "unavailable"}
out["audit"] = audit_status()
fs = fitness()
out["fitness"] = {"pass": fs["pass"], "total": fs["total"]}
try:
c = media_coverage()
out["coverage"] = {"total": c["total"], "ru_audio": c["ru_audio"], "ru_subs": c["ru_subs"]}
except Exception:
out["coverage"] = {"error": "unavailable"}
return out
def http_ok(url, timeout=6):
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
return r.status
except Exception:
return 0
def acceptance_status():
h = home_status()
audit_code = http_ok("http://127.0.0.1:9160/")
gitea_code = http_ok("http://192.168.1.140:3000/")
try:
media_n = len(recent())
except Exception:
media_n = 0
backups = []
for p in ("/mnt/archive/backups/prism", "/mnt/archive/backups/seerr"):
try:
backups += [x.name for x in Path(p).glob("*") if x.is_file()][-1:]
except Exception:
pass
items = [
{"name": "Jellyfin", "what": "фильмы и сериалы",
"url": "https://media.buryans.ru", "auto": h["jellyfin"] == "ok",
"detail": "SSO-вход и playback"},
{"name": "Buryans One Alpha", "what": "read-only вход",
"url": "/alpha/", "auto": True, "detail": f"новинки: {media_n}"},
{"name": "Audit 360", "what": "трекер и Gate",
"url": "http://192.168.1.10:9161/", "auto": audit_code == 200,
"detail": f"HTTP {audit_code}; done={(h.get('audit') or {}).get('done','—')}"},
{"name": "Prism", "what": "очередь LLM (не трогать)",
"url": "/alpha/owner", "auto": "error" not in (h.get("prism") or {}),
"detail": f"pending={(h.get('prism') or {}).get('pending_tasks','—')} errors={(h.get('prism') or {}).get('error_tasks','—')}"},
{"name": "RU-озвучка", "what": "русская дорожка/субтитры",
"url": "/alpha/", "auto": (h.get("coverage") or {}).get("ru_audio", 0) > 0,
"detail": "RU audio %s/%s · subs %s" % (
(h.get("coverage") or {}).get("ru_audio", "—"),
(h.get("coverage") or {}).get("total", "—"),
(h.get("coverage") or {}).get("ru_subs", "—"))},
{"name": "Gitea", "what": "код и PR",
"url": "http://192.168.1.140:3000/", "auto": gitea_code == 200,
"detail": f"HTTP {gitea_code}"},
{"name": "Бэкапы", "what": "свежие дампы",
"url": "http://192.168.1.10:9161/", "auto": bool(backups),
"detail": ", ".join(backups) if backups else "не найдены"},
]
return {"ok": all(x["auto"] for x in items), "items": items}
SERVICES_PATH = Path("/root/buryan-infra/docs/architecture/REGISTRY/services.yaml")
MODELS_PATH = Path("/root/buryan-infra/docs/architecture/REGISTRY/models.yaml")
def service_health(svc):
endpoint = (svc.get("endpoint") or "").strip()
started = time.time()
try:
if endpoint.startswith("http"):
try:
with urllib.request.urlopen(endpoint, timeout=4) as r:
code = r.status
except urllib.error.HTTPError as e:
code = e.code
up = code < 400
return {"up": up, "code": code, "ms": int((time.time() - started) * 1000)}
if endpoint.startswith(("tcp://", "nats://")):
u = urllib.parse.urlsplit(endpoint)
host, port = u.hostname, u.port or 0
with socket.create_connection((host, port), timeout=3):
pass
return {"up": True, "code": None, "ms": int((time.time() - started) * 1000)}
return {"up": None, "code": None, "ms": None, "error": "no endpoint"}
except Exception as e:
return {"up": False, "code": None, "ms": int((time.time() - started) * 1000),
"error": str(e)[:120]}
def mission_services():
import yaml
data = yaml.safe_load(SERVICES_PATH.read_text())
rows = []
for s in data.get("services") or []:
h = service_health(s)
rows.append({
"id": s.get("id"), "tier": s.get("tier"), "owner": s.get("owner"),
"endpoint": s.get("endpoint"), "public": s.get("public"),
"health": s.get("health"), "up": h.get("up"), "code": h.get("code"),
"ms": h.get("ms"), "error": h.get("error"),
})
return {"ok": all(x["up"] is not False for x in rows),
"total": len(rows), "up": sum(1 for x in rows if x["up"] is True),
"down": sum(1 for x in rows if x["up"] is False), "items": rows}
def model_health(m):
if m.get("health") == "external":
return {"up": None, "loaded": None, "error": "external provider"}
endpoint = (m.get("endpoint") or "").rstrip("/")
try:
with urllib.request.urlopen(endpoint + "/api/tags", timeout=3) as r:
body = json.loads(r.read().decode("utf-8", "replace"))
names = [x.get("name") for x in body.get("models") or []]
return {"up": True, "loaded": m.get("id") in names, "models": names[:10]}
except Exception as e:
return {"up": False, "loaded": None, "error": str(e)[:120]}
def model_registry():
import yaml
data = yaml.safe_load(MODELS_PATH.read_text())
rows = []
for m in data.get("models") or []:
h = model_health(m)
rows.append({**{k: m.get(k) for k in ("id", "provider", "role", "endpoint", "health", "note")}, **h})
return {"ok": all(x.get("up") is not False for x in rows), "total": len(rows), "items": rows}
def request_check(q):
qn = (q or "").strip().lower()
if not qn:
return {"ok": False, "error": "query_required"}
code, body = seerr("/api/v1/request?take=50")
if code != 200:
return {"ok": False, "error": "seerr_unavailable", "code": code}
for x in body.get("results") or []:
media = x.get("media") or {}
title = (media.get("title") or media.get("name") or "").lower()
if qn in title or title in qn:
return {"ok": True, "requested": True, "id": x.get("id"),
"title": media.get("title") or media.get("name"),
"status": x.get("status")}
return {"ok": True, "requested": False}
def seerr(path):
"""Read-only Seerr requests via the local breakglass Jellyfin login."""
global _SEERR_OP, _SEERR_TS
base = "http://192.168.1.121:5055"
if _SEERR_OP is not None and time.time() - _SEERR_TS < 1800:
try:
req = urllib.request.Request(base + path, headers={"Accept": "application/json"})
with _SEERR_OP.open(req, timeout=8) as r:
return 200, json.load(r)
except Exception:
_SEERR_OP = None
cred = Path("/root/.jellyfin-breakglass")
try:
lines = cred.read_text().splitlines()
@@ -115,13 +338,25 @@ def seerr(path):
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
login = urllib.request.Request(
base + "/api/v1/auth/jellyfin",
data=json.dumps({"username": user, "password": pw}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
with op.open(login, timeout=8) as r:
if r.status != 200:
return 503, {"ok": False, "error": "seerr_login_%s" % r.status}
ok = False
for attempt in range(3):
login = urllib.request.Request(
base + "/api/v1/auth/jellyfin",
data=json.dumps({"username": user, "password": pw}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
try:
with op.open(login, timeout=8) as r:
if r.status == 200:
ok = True
break
except urllib.error.HTTPError as e:
if e.code not in (401, 403):
raise
time.sleep(0.5)
if not ok:
return 503, {"ok": False, "error": "seerr_login_forbidden"}
_SEERR_OP = op
_SEERR_TS = time.time()
req = urllib.request.Request(base + path, headers={"Accept": "application/json"})
with op.open(req, timeout=8) as r:
return 200, json.load(r)
@@ -132,6 +367,41 @@ def seerr(path):
return 503, {"ok": False, "error": "seerr_unavailable", "detail": str(e)[:120]}
def releases():
import datetime
key = Path("/root/.radarr-key").read_text().strip()
today = datetime.date.today()
end = today + datetime.timedelta(days=14)
url = ("http://192.168.1.118:7878/api/v3/calendar?start=%s&end=%s"
% (today.isoformat(), end.isoformat()))
req = urllib.request.Request(url, headers={"X-Api-Key": key, "Accept": "application/json"})
with urllib.request.urlopen(req, timeout=8) as r:
data = json.load(r)
return [{"title": x.get("title"), "date": x.get("physicalRelease") or x.get("digitalRelease"),
"type": "movie"} for x in data]
def recommendations():
seed = recent()
out = []
seen = set(x.get("id") for x in seed)
for s in seed[:3]:
qs = urllib.parse.urlencode({
"SimilarTo": s["id"], "Recursive": "true",
"IncludeItemTypes": "Movie,Series", "Limit": "6"})
data = jf("/Items?" + qs)
for x in data.get("Items") or []:
if x.get("Id") in seen:
continue
seen.add(x.get("Id"))
out.append({"id": x.get("Id"), "title": x.get("Name"),
"year": x.get("ProductionYear"), "type": x.get("Type")})
if not out:
out = [{"id": x["id"], "title": x["name"], "year": x["year"], "type": x["type"]}
for x in seed]
return 200, {"ok": True, "items": out[:12], "source": "jellyfin_similar"}
def item(i):
qs = urllib.parse.urlencode({"Ids": i, "Fields": "Overview,ProductionYear,MediaSources"})
data = jf("/Items?" + qs)
@@ -258,23 +528,57 @@ class H(BaseHTTPRequestHandler):
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/v1/media/coverage":
try:
self.out(200, media_coverage())
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/v1/fitness":
self.out(200, fitness())
return
if u.path == "/v1/home/status":
self.out(200, home_status())
return
if u.path == "/v1/media/request/check":
q = urllib.parse.parse_qs(u.query).get("q", [""])[0]
try:
self.out(200, request_check(q))
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:200]})
return
if u.path == "/v1/media/requests":
code, body = seerr("/api/v1/request?take=20")
if code == 503:
time.sleep(1)
code, body = seerr("/api/v1/request?take=20")
self.out(code, body)
return
if len(parts) == 4 and parts[:3] == ["v1", "media", "requests"]:
code, body = seerr("/api/v1/request/%s" % urllib.parse.quote(parts[3]))
if code == 503:
time.sleep(1)
code, body = seerr("/api/v1/request/%s" % urllib.parse.quote(parts[3]))
self.out(code, body)
return
if u.path in ("/v1/media/continue", "/v1/media/releases", "/v1/media/recommendations"):
self.out(501, {"ok": False, "error": "not_configured",
"endpoint": u.path})
if u.path == "/v1/media/continue":
try:
self.out(200, {"ok": True, "items": continue_items()})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:200]})
return
if u.path == "/v1/media/releases":
try:
self.out(200, {"ok": True, "items": releases()})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:200]})
return
if u.path == "/v1/media/recommendations":
try:
code, body = recommendations()
self.out(code, body)
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:200]})
return
if u.path == "/v1/media/recent":
try:
@@ -292,6 +596,36 @@ class H(BaseHTTPRequestHandler):
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/v1/acceptance":
self.out(200, acceptance_status())
return
if u.path == "/acceptance":
self.out(200, PAGE_ACCEPTANCE, "text/html")
return
if u.path == "/v1/services":
try:
self.out(200, mission_services())
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/mission":
self.out(200, PAGE_MISSION, "text/html")
return
if u.path == "/v1/models":
try:
self.out(200, model_registry())
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/models":
self.out(200, PAGE_MODELS, "text/html")
return
if u.path == "/request":
self.out(200, PAGE_REQUEST, "text/html")
return
if u.path == "/owner":
self.out(200, PAGE_OWNER, "text/html")
return
if u.path == "/":
self.out(200, PAGE, "text/html")
return
@@ -315,6 +649,7 @@ button{padding:12px 16px;border-radius:8px;border:0;background:#2f81f7;color:#ff
a{color:#58a6ff}
</style></head><body>
<h1>Buryans One Alpha</h1><div class=mut id=me>read-only</div>
<div style="margin:8px 0"><a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/owner">Owner-пульт →</a> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/acceptance">Опросник приёмки →</a> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/request">Запросить фильм →</a> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/mission">Mission Control →</a></div>
<div class=grid id=status style="margin:16px 0"></div>
<div class=grid style="margin:16px 0">
<a class=card href="https://media.buryans.ru" target=_blank><h3>Jellyfin</h3><div class=tag>фильмы и сериалы</div></a>
@@ -330,16 +665,135 @@ a{color:#58a6ff}
<div class=mut style="margin-top:18px">Alpha read-only. Запросы и изменения — только после Gate G1.</div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function go(){const q=document.getElementById('q').value.trim();if(!q)return;document.getElementById('msg').textContent='поиск...';const r=await fetch('v1/media/search?q='+encodeURIComponent(q));const d=await r.json();if(!d.ok){document.getElementById('msg').textContent=d.error||'ошибка';return}document.getElementById('msg').textContent=d.items.length?'':'ничего не найдено';document.getElementById('out').innerHTML=d.items.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div></div>`).join('')}
async function go(){const q=document.getElementById('q').value.trim();if(!q)return;document.getElementById('msg').textContent='поиск...';const r=await fetch('v1/media/search?q='+encodeURIComponent(q));const d=await r.json();if(!d.ok){document.getElementById('msg').textContent=d.error||'ошибка';return}document.getElementById('msg').textContent=d.items.length?'':'ничего не найдено';document.getElementById('out').innerHTML=d.items.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div><div style="margin-top:8px"><a href="https://media.buryans.ru/web/index.html#!/details?id=${e(x.id)}" target=_blank>Открыть в Jellyfin →</a></div></div>`).join('')}
async function boot(){try{const m=await (await fetch('v1/me')).json();document.getElementById('me').textContent='read-only · '+(m.email||'local')}catch(e){}
try{const s=await (await fetch('v1/home/status')).json();const p=s.prism||{};document.getElementById('status').innerHTML=`
<div class=card><h3>Jellyfin</h3><div class=tag>${s.jellyfin==='ok'?'работает':'недоступен'}</div></div>
<div class=card><h3>Prism</h3><div class=tag>pending ${p.pending_tasks??'—'} · running ${p.running_tasks??'—'} · errors ${p.error_tasks??'—'}</div></div>
<div class=card><h3>Audit 360</h3><div class=tag>done ${(s.audit||{}).done??'—'} · review ${(s.audit||{}).review_pending??'—'} · open ${(s.audit||{}).in_progress??'—'}</div><div class=tag><a href="http://192.168.1.10:9161/">открыть трекер</a></div></div>
<div class=card><h3>Fitness</h3><div class=tag>${(s.fitness||{}).pass??'—'}/${(s.fitness||{}).total??'—'} pass</div></div>
<div class=card><h3>RU-озвучка</h3><div class=tag>${(s.coverage||{}).ru_audio??'—'}/${(s.coverage||{}).total??'—'} · субтитры ${(s.coverage||{}).ru_subs??'—'}</div></div>
<div class=card><h3>Режим</h3><div class=tag>read-only · без записи</div></div>`}catch(e){}
try{const r=await (await fetch('v1/media/recent')).json();const xs=r.items||[];document.getElementById('recent').innerHTML=xs.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div></div>`).join('')}catch(e){}}
try{const r=await (await fetch('v1/media/recent')).json();const xs=r.items||[];document.getElementById('recent').innerHTML=xs.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div><div style="margin-top:8px"><a href="https://media.buryans.ru/web/index.html#!/details?id=${e(x.id)}" target=_blank>Открыть в Jellyfin →</a></div></div>`).join('')}catch(e){}}
document.getElementById('q').addEventListener('keydown',e=>{if(e.key==='Enter')go()});boot();
</script></body></html>"""
PAGE_OWNER = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Buryans Owner-пульт</title>
<style>
body{background:#0d1117;color:#e6edf3;font:16px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:14px;margin:18px 0}
.big{display:block;background:#161b22;border:1px solid #30363d;border-radius:12px;padding:18px;text-decoration:none;color:#e6edf3}
.big:hover{border-color:#2f81f7}.big h3{margin:0 0 6px;font-size:19px;color:#58a6ff}
.big .tag{color:#8b949e;font-size:13px}.status{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:12px;margin:12px 0}
a{color:#58a6ff}code{background:#161b22;padding:2px 5px;border-radius:4px}
</style></head><body>
<h1>Owner-пульт</h1><div class=mut>Крупные кнопки. Всё read-only, кроме Audit 360.</div>
<div id=status class=status>загрузка статуса…</div>
<div class=grid>
<a class=big href="https://media.buryans.ru" target=_blank><h3>Jellyfin</h3><div class=tag>фильмы, сериалы, playback. Вход через Authentik.</div></a>
<a class=big href="https://media.buryans.ru/sso/OID/start/authentik" target=_blank><h3>Войти в Jellyfin</h3><div class=tag>прямой SSO-вход, если кнопка не видна.</div></a>
<a class=big href="http://192.168.1.10:9161/" target=_blank><h3>Audit 360</h3><div class=tag>трекер, evidence, Gate G0/G1.</div></a>
<a class=big href="/alpha/acceptance"><h3>Опросник приёмки</h3><div class=tag>по каждому сервису: что нажать и что должно быть.</div></a>
<a class=big href="/alpha/request"><h3>Запросить фильм</h3><div class=tag>поиск по Jellyfin и кнопка запроса в Seerr.</div></a>
<a class=big href="/alpha/mission"><h3>Mission Control</h3><div class=tag>карта сервисов, health, owners, ссылки.</div></a>
<a class=big href="http://192.168.1.10:9161/alpha/"><h3>На главную Alpha</h3><div class=tag>поиск, новинки, сервисы.</div></a>
<a class=big href="/alpha/v1/fitness" target=_blank><h3>Fitness</h3><div class=tag>18 FIT-пунктов, честные статусы.</div></a>
<a class=big href="http://192.168.1.140:3000/" target=_blank><h3>Gitea</h3><div class=tag>код, PR, решения.</div></a>
</div>
<div class=status><b>Порядок:</b> 1) проверить Alpha; 2) Jellyfin; 3) Audit 360 → S0-10; 4) S1-10. Prism не трогать.</div>
<div class=mut>Если что-то не работает — не чинить, зафиксировать и передать.</div>
<script>
async function boot(){try{const s=await (await fetch('v1/home/status')).json();const p=s.prism||{},a=s.audit||{},f=s.fitness||{};document.getElementById('status').innerHTML=`
<b>Jellyfin:</b> ${s.jellyfin==='ok'?'работает':'недоступен'} ·
<b>Prism:</b> pending ${p.pending_tasks??'—'} / errors ${p.error_tasks??'—'} ·
<b>Audit:</b> done ${a.done??'—'} / review ${a.review_pending??'—'} ·
<b>Fitness:</b> ${f.pass??'—'}/${f.total??'—'}`}catch(e){document.getElementById('status').textContent='статус недоступен'}}
boot();
</script></body></html>"""
PAGE_ACCEPTANCE = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Приёмка сервисов — Buryans</title>
<style>
body{background:#0d1117;color:#e6edf3;font:16px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px;margin:18px 0}
.row{background:#161b22;border:1px solid #30363d;border-radius:12px;padding:16px}
.row h3{margin:0 0 4px;font-size:19px}.ok{color:#3fb950}.bad{color:#f85149}.tag{color:#8b949e;font-size:13px}
a{color:#58a6ff}.auto{font-size:13px;margin-top:8px}.big{font-size:17px;text-decoration:none}
</style></head><body>
<h1>Приёмка сервисов</h1><div class=mut>Один экран: что открыть, что должно быть, что показывает автоматическая проверка.</div>
<div class=grid id=rows>загрузка…</div>
<div class=row>
<h3>Что считается успехом</h3>
<div class=tag>Если авто-проверка зелёная и ты видишь ожидаемое — сервис принят. Один-два положительных теста уже достаточны для источника истины; повторять вручную всё не нужно.</div>
<h3 style="margin-top:14px">Порядок</h3>
<div class=tag>1) Jellyfin · 2) Alpha · 3) Audit 360 · 4) Gitea · 5) Prism только смотреть. Бэкапы проверяются автоматически.</div>
<h3 style="margin-top:14px">Если не работает</h3>
<div class=tag>Снять URL/код, не чинить. Написать: «сервис, что нажал, что ожидал, что увидел».</div>
</div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function boot(){try{const d=await (await fetch('v1/acceptance')).json();document.getElementById('rows').innerHTML=(d.items||[]).map(x=>`<div class=row><h3>${e(x.name)}</h3><div class=tag>${e(x.what)}</div><div class=auto>${x.auto?'<span class=ok>● авто-проверка: OK</span>':'<span class=bad>● авто-проверка: FAIL</span>'}</div><div class=tag>${e(x.detail||'')}</div><div style="margin-top:10px"><a class=big href="${e(x.url)}" target=_blank>Открыть →</a></div></div>`).join('')}catch(e){document.getElementById('rows').textContent='не удалось получить статус'}}
boot();
</script></body></html>"""
PAGE_REQUEST = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Запрос фильма — Buryans</title>
<style>
body{background:#0d1117;color:#e6edf3;font:16px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
input{width:min(600px,80%);padding:12px;border-radius:8px;border:1px solid #30363d;background:#161b22;color:#e6edf3;font-size:16px}
button{padding:12px 16px;border-radius:8px;border:0;background:#2f81f7;color:#fff;font-size:16px;cursor:pointer}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px;margin-top:18px}
.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}
.card h3{margin:0 0 4px;font-size:16px}.tag{color:#8b949e;font-size:13px}
a{color:#58a6ff}.warn{background:#161b22;border:1px solid #9e6a03;border-radius:10px;padding:12px;color:#d29922}
</style></head><body>
<h1>Запрос фильма</h1><div class=mut>Alpha только ищет. Запрос создаётся в Seerr, не в медиатеке.</div>
<div style="margin:16px 0"><input id=q placeholder="Название фильма или сериала..." autofocus> <button onclick="go()">Найти</button></div>
<div id=msg class=mut></div><div id=out class=grid></div>
<div class=warn style="margin-top:18px">Если запрос уже существует, Seerr покажет это сам. Дубли в Jellyfin не создаются.</div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function go(){const q=document.getElementById('q').value.trim();if(!q)return;document.getElementById('msg').textContent='поиск...';const r=await fetch('v1/media/search?q='+encodeURIComponent(q));const d=await r.json();const xs=d.items||[];let warn='';try{const c=await (await fetch('v1/media/request/check?q='+encodeURIComponent(q))).json();if(c.requested)warn='⚠️ Похоже, заявка уже есть: '+e(c.title||q)+' (статус '+e(c.status)+').';}catch(e){}document.getElementById('msg').textContent=xs.length?'':'ничего не найдено';if(warn)document.getElementById('msg').textContent=warn;document.getElementById('out').innerHTML=xs.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div style="margin-top:8px"><a href="https://requests.buryans.ru/search?query=${encodeURIComponent(x.name)}" target=_blank>Запросить в Seerr →</a></div></div>`).join('')}
document.getElementById('q').addEventListener('keydown',e=>{if(e.key==='Enter')go()});
</script></body></html>"""
PAGE_MODELS = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1"><title>Models — Buryans</title>
<style>body{background:#0d1117;color:#e6edf3;font:15px/1.5 system-ui,Arial;margin:0;padding:28px}h1{margin:0 0 6px}.mut{color:#8b949e}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px;margin-top:18px}.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}.card h3{margin:0 0 4px;font-size:17px}.tag{color:#8b949e;font-size:13px}.ok{color:#3fb950}.bad{color:#f85149}.unk{color:#d29922}a{color:#58a6ff}</style></head><body>
<h1>Model Registry</h1><div class=mut>Read-only реестр моделей и health. Агенты не получают production-доступ через эту страницу. · <a href="/alpha/mission">Mission Control →</a></div>
<div class=mut id=summary style="margin-top:10px">загрузка…</div><div class=grid id=rows></div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
fetch('v1/models').then(r=>r.json()).then(d=>{document.getElementById('summary').textContent=`моделей ${d.total} · ok ${d.ok}`;document.getElementById('rows').innerHTML=(d.items||[]).map(x=>{const st=x.up===true?'<span class=ok>● up</span>':x.up===false?'<span class=bad>● down</span>':'<span class=unk>● external</span>';return `<div class=card><h3>${e(x.id)}</h3><div class=tag>${e(x.provider)} · ${e(x.role)}</div><div style="margin-top:6px">${st} ${x.loaded===true?'· loaded':x.loaded===false?'· not loaded':''}</div><div class=tag>${e(x.health)} · ${e(x.endpoint)}</div>${x.error?`<div class=tag>${e(x.error)}</div>`:''}</div>`}).join('')}).catch(()=>document.getElementById('summary').textContent='не удалось получить реестр моделей');
</script></body></html>"""
PAGE_MISSION = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Mission Control — Buryans</title>
<style>
body{background:#0d1117;color:#e6edf3;font:15px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:12px;margin:18px 0}
.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}
.card h3{margin:0 0 4px;font-size:17px}.tag{color:#8b949e;font-size:13px}
.ok{color:#3fb950}.bad{color:#f85149}.unk{color:#d29922}
a{color:#58a6ff}
</style></head><body>
<h1>Mission Control</h1><div class=mut>Read-only карта сервисов. Health, tier, owner, endpoints. Без изменения сервисов. · <a href="/alpha/models">Models →</a></div>
<div class=mut id=summary style="margin-top:10px">загрузка…</div>
<div class=grid id=rows></div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function boot(){try{const d=await (await fetch('v1/services')).json();document.getElementById('summary').textContent=`сервисов ${d.total} · up ${d.up} · down ${d.down}`;const xs=(d.items||[]).slice().sort((a,b)=>(a.tier-b.tier)||String(a.id).localeCompare(b.id));document.getElementById('rows').innerHTML=xs.map(x=>{const st=x.up===true?'<span class=ok>● up</span>':x.up===false?'<span class=bad>● down</span>':'<span class=unk>● unknown</span>';const url=x.public||x.endpoint||'';return `<div class=card><h3>${e(x.id)}</h3><div class=tag>tier ${e(x.tier)} · ${e(x.owner||'—')}</div><div style="margin-top:6px">${st} ${x.code?`HTTP ${e(x.code)}`:''} ${x.ms!=null?`· ${e(x.ms)}ms`:''}</div><div class=tag>${e(x.health||'')}</div>${url?`<div style="margin-top:8px"><a href="${e(url)}" target=_blank>${e(url)}</a></div>`:''}${x.error?`<div class=tag>${e(x.error)}</div>`:''}</div>`}).join('')}catch(e){document.getElementById('summary').textContent='не удалось получить карту сервисов'}}
boot();
</script></body></html>"""
if __name__ == "__main__":
ThreadingHTTPServer((HOST, PORT), H).serve_forever()
+4 -4
View File
@@ -28,10 +28,10 @@ class MediaPaths(unittest.TestCase):
"/v1/media/works/" + iid: 200,
"/v1/media/works/" + iid + "/availability": 200,
"/v1/media/works/" + iid + "/editions": 200,
"/v1/media/requests": 503,
"/v1/media/continue": 501,
"/v1/media/releases": 501,
"/v1/media/recommendations": 501,
"/v1/media/requests": 200,
"/v1/media/continue": 200,
"/v1/media/releases": 200,
"/v1/media/recommendations": 200,
}
for path, want in expected.items():
code, _ = get(path)
+45
View File
@@ -0,0 +1,45 @@
# Ночной анализ — 2026-11-28
Провайдер: локальная qwen2.5:7b
## Вывод модели
Ночью: Сервисы identity-album-sync.service и immich-library-scan.service не могут быть запущены.
Требует внимания: Проверить состояние сервисов и связанных сервисов.
Утром проверить: Состояние сервисов и связанных сервисов.
Уверенность: 100 процентов.
## ✅ Проверка фактов
Все упомянутые CT/VM/числа присутствуют в исходных фактах.
## Исходные факты
```
Nov 27 19:10:05 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 19:25:07 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 19:35:02 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 27 19:40:08 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 19:55:12 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 20:05:03 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 27 20:10:12 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 20:25:12 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 20:35:03 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 27 20:40:12 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 20:55:14 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 21:05:03 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 27 21:10:15 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 21:25:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 21:35:03 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 27 21:40:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 21:55:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 22:05:03 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 27 22:10:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 22:25:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 22:35:03 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 27 22:40:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 22:55:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 27 23:05:03 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 27 23:10:17 pve systemd[1]: Failed to start immich-library-scan.service - Sc
```
+42
View File
@@ -0,0 +1,42 @@
# Ночной анализ — 2026-11-29
Провайдер: нет
## Вывод модели
локальная модель недоступна (URLError)
## ✅ Проверка фактов
Все упомянутые CT/VM/числа присутствуют в исходных фактах.
## Исходные факты
```
Nov 28 19:26:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 19:35:44 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 28 19:41:17 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 19:56:21 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 20:05:45 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 28 20:11:23 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 20:26:24 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 20:35:47 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 28 20:41:24 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 20:56:28 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 21:05:47 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 28 21:11:29 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 21:26:31 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 21:35:47 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 28 21:41:32 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 21:56:32 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 22:05:47 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 28 22:11:32 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 22:26:32 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 22:35:47 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 28 22:41:32 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 22:56:32 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 23:05:47 pve systemd[1]: Failed to start identity-album-sync.service - Sync Immich person albums and feed Identity media.
Nov 28 23:11:32 pve systemd[1]: Failed to start immich-library-scan.service - Scan Immich Nextcloud external library.
Nov 28 23:26:34 pve systemd[1]: Failed to start immich-library-scan.service - Sc
```
+9 -1
View File
@@ -114,4 +114,12 @@
2026-11-26T07:23:29 | hygiene-scan | done | 2: hub-cert-sync.service, immich-library-scan.service
[high] drift compose CT115: 2 расхождений
[high] сервис не отвечает Paperless (192.168.1.110:8000/)
[medium] круп
[medium] круп
2026-11-27T07:23:49 | hygiene-scan | done | e, immich-library-scan.service, prism-vendor-worker.servi
[high] drift compose CT115: 2 расхождений
[high] сервис не отвечает Paperless (192.168.1.110:8000/)
[medium] крупны
2026-11-28T07:23:32 | hygiene-scan | done | an.servi
[high] drift compose CT115: 2 расхождений
[high] сервис не отвечает Paperless (192.168.1.110:8000/); Immich (VM) (192.168.1.104:2283/api/server/ping
[medium] крупны
+67
View File
@@ -0,0 +1,67 @@
# Недельный отчёт 2026-W48
_Составлен автоматически 29.11.2026 09:00._
## Изменения
Коммитов за неделю: **222**
```
b6c9643 [STANDARD] Ночной пересчёт соответствия 2026-11-29
8c16e9c [A-38] Снимок состояния 2026-11-28
ef706a3 [STANDARD] Ночной пересчёт соответствия 2026-11-28
c5c802c [PRISM] Fix missing requirements/matrix-db functions
87cc382 [STAGE5] Gateway-only smoke agent
3045ced [STAGE5] Model lease runtime via Tool Gateway
7735ddf [STAGE5] Tool Gateway runtime + hub-tools service
649386f [STAGE5] Tool Gateway policy registry + test
457f95d [STAGE5] Model Registry v0 + health
ae5ab90 [STAGE4] Gate G4 evidence: 4 adapters, contract tests green
506ae58 [STAGE4] Adapter SDK, 4 adapters, contract tests, preview
7ef5b02 [STAGE4] Mission Control v0 + Matrix internal homeserver
0f41d71 [STAGE3] Tracker: OpenSubtitles creds, TLS block
7099d40 [STAGE3] OpenSubtitles creds configured; Bazarr TLS/login blocked
b7b5c36 [STAGE3] Tracker: OpenSubtitles download blocked
54905cc [STAGE3] OpenSubtitles API: RU search works, download incomplete
64f0f05 [STAGE3] S3-04 done: Matrix-only requests
84834e4 [STAGE3] Matrix-only request scope; Telegram excluded
c9eddc0 [STAGE3] Tracker: Bazarr RU provider blocked
eb070b7 [STAGE3] Bazarr RU path attempted; subf2m no file
13d14b1 [STAGE3] Tracker: RU/Telegram blockers
060bb8f [STAGE3] Evidence: no RU files on disk; Telegram absent
ff34b72 [STAGE3] Tracker: duplicate guard
8273956 [STAGE3] Duplicate check before Seerr request
a7b1a90 [STAGE3] Tracker: Alpha/Matrix request paths
2fbe234 [STAGE3] Matrix/Alpha request paths documented
8b78cd9 [STAGE3] Matrix !request link to Seerr
e6a29a5 [STAGE3] Tracker: Alpha request path
3636be5 [STAGE3] Alpha request handoff to Seerr
2be898d [STAGE3] Tracker: direct 6/6 done
304db34 [STAGE3] Direct-play 6/6 playable media
6ab9496 [STAGE3] Tracker: direct 6/7, RU blocked by source
8940671 [STAGE3] Direct-play 6/7 via episode inspection
f576843 [STAGE3] Tracker: Stage3 tasks
64e3c95 [STAGE3] RU/direct-play coverage audit + tasks
5ff027f [STAGE2] S2-05 done: adapters live
e6fc2cb [STAGE2] Adapters: Audit360 + Jellyfin + Seerr
2f0017a [STAGE2] Tracker: durable pipeline active
46761c0 [STAGE2] Durable events pipeline + Audit360 adapter
a221d71 [STAGE2] Tracker: S2-06 pgvector done
```
## Инфраструктура
| Показатель | Значение |
|---|---|
| Сервисы | **74/74** |
| Активных алертов | 2 |
| RAM | 11904 МБ из 15754 |
| Диск / | 45G из 109G |
| Бэкап vzdump | 3.7 ч назад |
| Бэкап конфигов | 769.0 ч назад, 465 МБ |
## Что посмотреть
- Открытые задачи: `ops/STATUS.md`
- Отчёт о покрытии: `ops/registry/COVERAGE.md`
- Известные проблемы: `ops/ops/*.md`
+12 -7
View File
@@ -90,13 +90,13 @@ while True:
note_kind = "scenario" if kind == "model_scenario" else ("review" if kind == "model_review" else "positioning")
prompt = MODEL_PROMPT % (name, vendor, role or "unknown", domain or "unknown", specs[:800])
r = L.ask(prompt, max_tokens=250, temperature=0.2,
chain=[{"name": "qwen2.5:3b-32k", "kind": "ollama", "timeout": 300}])
chain=[{"name": "qwen2.5:3b", "kind": "ollama", "timeout": 300}])
text = r["text"].strip()[:2000]
cur.execute("""insert into prism.model_notes(model_id,kind,text,model)
values (%s,%s,%s,'qwen2.5:7b')""", (mid, note_kind, text))
cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,stats,started_at,finished_at)
values (%s,'model_note7b','ok','229',%s,%s,now(),now())""",
(mid, "qwen2.5:3b-32k", json.dumps({"task_id": task_id, "chars": len(text)})))
(mid, "qwen2.5:3b", json.dumps({"task_id": task_id, "chars": len(text)})))
else:
cur.execute("select url,title from prism.sources where id=%s", (sid,))
s = cur.fetchone()
@@ -117,9 +117,14 @@ while True:
raise RuntimeError("empty text %s" % len(txt))
chunk = R.pick_excerpt(txt, 3500)
conn.commit()
r = L.ask(SUPPORT_PROMPT + chunk, max_tokens=3000, temperature=0.0,
chain=[{"name": "qwen2.5:3b-32k", "kind": "ollama", "timeout": 300}])
d = parse_loose(r["text"])
r = L.ask(SUPPORT_PROMPT + chunk, max_tokens=1200, temperature=0.0,
chain=[{"name": "qwen2.5:3b", "kind": "ollama", "timeout": 300}])
try:
d = parse_loose(r["text"])
except Exception:
r = L.ask(SUPPORT_PROMPT + chunk, max_tokens=1200, temperature=0.0,
chain=[{"name": "deepseek-flash", "kind": "deepseek", "timeout": 120}])
d = parse_loose(r["text"])
facts = d.get("facts") or []
for f in facts:
key = re.sub(r"[^a-zA-Z0-9_.-]+", "_", str(f.get("key") or "fact")).strip("_").lower()
@@ -136,7 +141,7 @@ while True:
(mid, sid, key, vtext, f.get("unit"), f.get("quote")))
cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,stats,started_at,finished_at)
values (%s,'enrich_support7b','ok','229',%s,%s,now(),now())""",
(mid, "qwen2.5:3b-32k", json.dumps({"source_id": sid, "facts": len(facts)})))
(mid, "qwen2.5:3b", json.dumps({"source_id": sid, "facts": len(facts)})))
cur.execute("update prism.tasks set status='done', finished_at=now() where id=%s", (task_id,))
print("done", task_id, kind, flush=True)
except Exception as e:
@@ -144,7 +149,7 @@ while True:
(str(e)[:300], task_id))
cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,error,started_at,finished_at)
values (%s,'worker7b','error','229',%s,%s,now(),now())""",
(mid, "qwen2.5:3b-32k", str(e)[:300]))
(mid, "qwen2.5:3b", str(e)[:300]))
print("error", task_id, kind, str(e)[:150], flush=True)
conn.commit()
time.sleep(1)
+1 -1
View File
@@ -5,7 +5,7 @@
"dashy": "dig:sha256:a877dd3d182b8d6b57aedbd879f2d1c0e76771be3ee54ff1ef4a8a725a09ed11",
"duplicati": "dig:sha256:e32e280cc30e98ac5cea8d2b339cd19810b1b39e638fb9d39253786630104de0",
"element-web": "dig:sha256:f8700633d4336258af7a05b53865a4f479e0d628cf2d9ca83d28b5939314d4ce",
"files_db": "ver:13.0.2",
"files_db": "ver:13.1.2",
"firefly": "dig:sha256:a2b53539338d1cd04d341b229c3806cb178cf64c72459060e3ed34bec4167bd8",
"freshrss": "dig:sha256:48b63b9bc3d042a1301c32971b01af8841c7f059b452589c5bf77f475ba44c61",
"grafana": "dig:sha256:dbbc38ea21103cefb50396340cd88afec779c7e070b0a7bf5a75b4ce46651d3f",
+39
View File
@@ -0,0 +1,39 @@
# Статистика доверия агента — 2026-11-28
## Главное
- Всё в штатном режиме.
- Проблемы: 1 правило (selftest-guards) требует внимания, что связано с низкой успешностью запусков (40%).
- Рекомендуется провести дополнительное исследование и разобрать провалы в правилах selftest-guards для дальнейшего улучшения.
Порог повышения уровня: **20 успешных запусков при успешности ≥ 95%**.
| Правило | Запусков | ОК | Провал | Отказов | Успешность | Уровень | Вердикт |
|---|---|---|---|---|---|---|---|
| `action:pct_start` | 1 | 1 | 0 | 0 | 100% | — | наблюдаем (1/20 запусков) |
| `action:retry_search` | 1 | 1 | 0 | 0 | 100% | — | наблюдаем (1/20 запусков) |
| `cert-expiring` | 0 | 0 | 0 | 0 | 0% | L1_dry_run | нет данных |
| `disk-cleanup` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `docker-daemon-stuck` | 0 | 0 | 0 | 0 | 0% | L1_dry_run | нет данных |
| `e2e-selfcheck` | 1 | 1 | 0 | 0 | 100% | — | наблюдаем (1/20 запусков) |
| `exporter-down` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `hygiene-scan` | 25 | 25 | 0 | 16 | 100% | — | можно повысить уровень |
| `import-missing` | 0 | 0 | 0 | 0 | 0% | L1_dry_run | нет данных |
| `io-degradation` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `media-queue-stall` | 0 | 0 | 0 | 0 | 0% | L1_dry_run | нет данных |
| `restart-failed-container` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `restart-failed-ct` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `selftest-guards` | 5 | 2 | 3 | 3 | 40% | — | понизить / разобрать провалы |
## Сводка
- готовы к повышению: **1** (hygiene-scan)
- требуют внимания: **1** (selftest-guards)
- наблюдение: **12**
## Как читать
Агент начинает с `dry_run=true` и уровня L1 — только предлагает.
Когда правило наберёт нужную статистику, его можно перевести на уровень выше
(например, L2 — реально перезапускать контейнеры). Решение принимает владелец.
+40
View File
@@ -0,0 +1,40 @@
# Статистика доверия агента — 2026-11-29
## Главное
- `selftest-guards` требует внимания: успешность 40% (2 из 5), 3 провала и 3 отказа — нужно разобрать причины, повышать уровень нельзя.
- `hygiene-scan` готов к повышению: 26 успешных запусков при 100% успешности (порог 20 при ≥95%).
- Большинство правил (12) без данных — накапливают статистику, решений не требуют.
- Явных рисков для инфраструктуры в отчёте не зафиксировано; ключевое действие — разобраться с `selftest-guards`.
Порог повышения уровня: **20 успешных запусков при успешности ≥ 95%**.
| Правило | Запусков | ОК | Провал | Отказов | Успешность | Уровень | Вердикт |
|---|---|---|---|---|---|---|---|
| `action:pct_start` | 1 | 1 | 0 | 0 | 100% | — | наблюдаем (1/20 запусков) |
| `action:retry_search` | 1 | 1 | 0 | 0 | 100% | — | наблюдаем (1/20 запусков) |
| `cert-expiring` | 0 | 0 | 0 | 0 | 0% | L1_dry_run | нет данных |
| `disk-cleanup` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `docker-daemon-stuck` | 0 | 0 | 0 | 0 | 0% | L1_dry_run | нет данных |
| `e2e-selfcheck` | 1 | 1 | 0 | 0 | 100% | — | наблюдаем (1/20 запусков) |
| `exporter-down` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `hygiene-scan` | 26 | 26 | 0 | 16 | 100% | — | можно повысить уровень |
| `import-missing` | 0 | 0 | 0 | 0 | 0% | L1_dry_run | нет данных |
| `io-degradation` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `media-queue-stall` | 0 | 0 | 0 | 0 | 0% | L1_dry_run | нет данных |
| `restart-failed-container` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `restart-failed-ct` | 0 | 0 | 0 | 0 | 0% | L2_safe_auto | нет данных |
| `selftest-guards` | 5 | 2 | 3 | 3 | 40% | — | понизить / разобрать провалы |
## Сводка
- готовы к повышению: **1** (hygiene-scan)
- требуют внимания: **1** (selftest-guards)
- наблюдение: **12**
## Как читать
Агент начинает с `dry_run=true` и уровня L1 — только предлагает.
Когда правило наберёт нужную статистику, его можно перевести на уровень выше
(например, L2 — реально перезапускать контейнеры). Решение принимает владелец.
+2
View File
@@ -999,3 +999,5 @@ psql: error: connection to server at "192.168.1.151", port 5432 failed: No route
[2026-11-25 03:05:06] отчёт отправлен: отложенных 0, успешно 0, ошибок 0, застряло 0
[2026-11-26 03:05:07] отчёт отправлен: отложенных 0, успешно 0, ошибок 0, застряло 0
[2026-11-27 03:05:07] отчёт отправлен: отложенных 0, успешно 0, ошибок 0, застряло 0
[2026-11-28 03:05:07] отчёт отправлен: отложенных 0, успешно 0, ошибок 0, застряло 0
[2026-11-29 03:05:07] отчёт отправлен: отложенных 0, успешно 0, ошибок 0, застряло 0
+48
View File
@@ -2452,6 +2452,54 @@ def prism_model_card(mid):
return row
def prism_requirements(model):
"""Requirements for a model, grouped for the Prism UI."""
name = str(model or "").strip()
if not name:
return {"ok": False, "error": "model required", "groups": []}
rows = _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select r.group_key, r.condition, r.max_qty, r.verified, a.name as option_name "
"from prism.model_requirements r "
"join prism.models m on m.id=r.model_id "
"join prism.models a on a.id=r.requires_model_id "
"where m.name=%s order by r.group_key,a.name) t" % _sqlq(name)
) or []
groups = {}
for r in rows:
key = r.get("group_key") or "other"
g = groups.setdefault(key, {"group_key": key, "label": key, "options": []})
g["options"].append({"name": r.get("option_name"), "max_qty": r.get("max_qty"),
"verified": bool(r.get("verified")), "condition": r.get("condition")})
return {"ok": True, "model": name, "groups": list(groups.values())}
def prism_matrix_db(vendor=""):
"""Host-to-device compatibility rows from prism.model_requirements."""
vendor = str(vendor or "").strip()
where = " and lower(m.vendor)=lower(%s)" % _sqlq(vendor) if vendor else ""
rows = _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.name as host, m.vendor, a.name as device, r.group_key, "
"r.condition, r.max_qty, r.verified "
"from prism.model_requirements r "
"join prism.models m on m.id=r.model_id "
"join prism.models a on a.id=r.requires_model_id "
"where 1=1%s order by m.name,a.name) t" % where
) or []
hosts = []
by_host = {}
for r in rows:
h = r.get("host")
if h not in by_host:
hosts.append(h)
by_host[h] = {"host": h, "vendor": r.get("vendor"), "items": []}
by_host[h]["items"].append({"device": r.get("device"), "group_key": r.get("group_key"),
"condition": r.get("condition"),
"max_qty": r.get("max_qty"), "verified": bool(r.get("verified"))})
return {"ok": True, "hosts": hosts, "rows": list(by_host.values())}
def prism_group_models(group):
rows = _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("