@consilium108/mcp-module-devops 1.0.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,69 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.0 — 2026-11-24
4
+
5
+ <!-- generated by Claude (Opus 5.5), 2026-11-24; Konsilium SDD-P37-160 — owner 2026-11-24 «Запускай все, добавь сразу».
6
+ 1.2.0 was never published (npm has 1.0.0, 1.1.0): its changes are folded into this section. -->
7
+
8
+ - **Deploy lifecycle from the journal (G1).** The orchestrator subscribes to `deploy.*` as well as `agent.*` and moves
9
+ the jobs that follow a deploy request by `deploy.requested / approved / rejected / running / done / failed /
10
+ rolled_back / expired` (the core's `project_events`, migration 151 `meta`; the DevOps module reports them through its
11
+ `core_outbox`). `GET /deploys/:id` stays as the fallback: every tick until the project is seen sending `deploy.*`,
12
+ then only after `deployPollFallbackMs` (default 5 min) without a fact. A `deploy.requested` of the job's target after
13
+ the assignment gives the deploy id when the agent's result line has none (IT-14).
14
+ - **Target / environment / branch / commit from the agent event (G2).** When an `agent.*` event carries `meta.target` /
15
+ `environment`, the route is chosen among the configured routes of that project (an unrouted target is ignored:
16
+ `target_not_routed`); `branch` / `commit_sha` go into the job (`konsilium.devops-job/1`) and leave `unknown`.
17
+ - **Turn-monitor state through `@consilium108/mcp/turnmonitor` (G4)** when the host package (≥ 0.11.1) is installed —
18
+ incl. `TURN_STARTED` (G3) = running; otherwise the files are read as before.
19
+ - **Live dispatch per slot (stage 3).** The global dispatch stays `dry_run`. `agents[].dispatch: "live"` (only `mode:
20
+ "headless"` + `provider: "claude"`, only in `run`) starts `claude -p <job> --output-format json --permission-mode
21
+ default --allowedTools <DevOps MCP tools + read-only git>` in the slot's workspace without a shell — one job at a time
22
+ per slot, `timeout_ms` ≤ `leaseMs` (stop + retry), only the default env names + `env_pass`, a masked per-run log in
23
+ `<stateDir>/live/`, the `ORCHESTRATOR_RESULT` → complete → agent-events report (sent although the global dispatch is
24
+ dry-run). `validateLivePlan` refuses any other shape before anything is spawned (bypass flags, another permission mode,
25
+ extra flags, tools outside the list, another binary). `agents[].dispatch: "handoff"` (only `mode: "session"`) creates a
26
+ hand-off (`POST /api/projects/:id/handoffs`, `handoff_agent` or the provider) instead of a second process; the
27
+ hand-off's result completes the job; a hand-off nobody took by the end of the lease is cancelled. A restart during a
28
+ live run retries the job at once. New exports: `createLiveDispatcher`, `validateLivePlan`, `LIVE_ALLOWED_TOOLS`,
29
+ `READ_ONLY_GIT`, `SLOT_DISPATCH`, `LIVE_ENV_DEFAULT`, `DEPLOY_EVENT_STATUS`, `resultTextOf`, `liveEnvOf`,
30
+ `maskSecrets`. `ALLOWED_ROUTES` + the three hand-off routes (create / read / cancel its own) — still no approve route.
31
+
32
+ ### Folded from 1.2.0 (never published)
33
+
34
+ - The local DevOps agent orchestrator — a SEPARATE service in the same package: bin `consilium-devops-orchestrator`
35
+ (`run`, `once`, `status`, `agents`, `check`, `config --print`, `unit --print`) and export `./orchestrator` (Node
36
+ built-ins; SSE through `subscribeSse` of `@nativemind108/mcp`). Event source = the existing delivery of #437
37
+ (`projectEvents` SSE, `get_events` catch-up / long poll, cursor saved after handling, a first start is a baseline);
38
+ agent registry = config slots + #470 turn-monitor facts (idle / running / waiting_for_user / blocked / unavailable);
39
+ durable queue with a lock per project + environment + target, coalescing, lease with renewal, retry with backoff,
40
+ restart recovery; provider adapters (claude, codex, generic) — **dry-run dispatch only**; follows the status of a
41
+ deploy an agent requested; reports through `POST /api/projects/:id/agent-events`. Never approves; plans with a
42
+ permission-bypass flag are refused; no secret in config, prompts, reports or logs.
43
+ - `acquireLock(dir, name = 'runner.lock')` — optional lock-file name (the runner is unchanged).
44
+
45
+ ## 1.1.0 (unreleased)
46
+
47
+ <!-- generated by Claude (Opus 5.5), 2026-11-22; Konsilium #482 (TASK-P37-482) -->
48
+
49
+ - The DevOps MCP on its own: `bin` `consilium-devops-mcp` (stdio) and `./standalone` (`createDevopsMcp`) — the module's
50
+ `deploy` and `debug` groups unchanged, plus `devops_session`, `select_project`, `list_deploy_targets`, `list_deploys`.
51
+ Credential: `KONSILIUM_API_KEY` or the `@consilium108/mcp login` sign-in; project: `--project` /
52
+ `KONSILIUM_PROJECT_ID` / `select_project` / the connection default; calls go to the core (it proxies to the DevOps
53
+ module) or with `--devops-api` straight to the module API. Stable error codes. No approval tools.
54
+ - The module definition (groups, tools of the host catalog) is unchanged — `@consilium108/mcp` and the cloud MCP keep
55
+ their tool lists. Dependencies: + `@modelcontextprotocol/sdk`, `zod` (runtime).
56
+ - `list_deploy_targets` / `list_deploys` need the core with the key routes of #482 (older core → `key_not_allowed`).
57
+ - The deploy runner joins the package as a SEPARATE service (2026-11-23, by the assistant's recommendation): bin
58
+ `consilium-devops-runner` (`run`, `once`, `doctor`, `install --print`, `unit --print`, `config --print`) and export
59
+ `./runner` (Node built-ins only). Ported from the monorepo's `deploy-runner/`: config outside the repository (mode 600
60
+ enforced, `tokenFile` / env overrides), explicit PATH with a preflight (`command_not_found` instead of «spawn docker
61
+ ENOENT»), recipe `konsilium-linux` (tests → web build → DB backup → `:prev` → `up -d --build app mcp` → healthy → checks;
62
+ rollback to `:prev`), JSON logs, heartbeat during a job, one deploy at a time, idempotent claim, graceful stop, systemd
63
+ unit printed (never installed). The watchdog no longer reads the core's `.env`. MCP tools `runner_status`,
64
+ `runner_setup` (standalone server only; the host catalog is unchanged). Extra bin `mcp-module-devops` keeps
65
+ `npx -y @consilium108/mcp-module-devops` starting the MCP now that the package has two commands.
66
+
3
67
  ## 1.0.0 (unreleased)
4
68
 
5
69
  <!-- generated by Claude (Opus 5.5), 2026-11-20; Konsilium #442, SDD flows/sdd-consilium-mcp-modules -->
package/README.md CHANGED
@@ -25,4 +25,211 @@ mod.id; // 'devops'
25
25
  Object.keys(mod.groups);
26
26
  ```
27
27
 
28
+ ## Отдельный MCP DevOps (1.1.0, #482)
29
+
30
+ <!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-22. -->
31
+
32
+ Тот же пакет запускается сам, без хоста и без остальных модулей: `bin` **`consilium-devops-mcp`** (stdio).
33
+ Инструменты (11): `devops_session` (кто, проекты и права, активный проект, включён ли модуль), `select_project`,
34
+ `request_deploy`, `deploy_status`, `list_deploy_targets` (цели и когда runner последний раз выходил на связь),
35
+ `list_deploys` (последние запросы), `runner_status` (runner каждой цели: на связи / нет, текущая выкатка, ожидающие),
36
+ `runner_setup` (шаги установки runner'а текстом — сам ничего не ставит), `list_debug_reports`, `get_debug_report`,
37
+ `attach_debug_capture`.
38
+ Одобрить, отклонить, откатить, создать цель или выдать право MCP **не может** — это делает человек с правом выкатки
39
+ (✅ в мессенджере / приложение). Бизнес-логики в MCP нет: каждый вызов — REST API Консилиума с ключом человека.
40
+
41
+ Куда идут вызовы: ядро Консилиума (`KONSILIUM_API_URL`, по умолчанию `https://konsilium.nativemind.net`); ядро
42
+ проверяет права и модуль и проксирует DevOps-маршруты в API модуля (`MODULE_DEVOPS=remote`). `--devops-api <url>` /
43
+ `DEVOPS_API_URL` — прямо в API модуля (те же пути; модуль сам проверяет ключ через ядро) — только когда он доступен
44
+ снаружи (сейчас нет: модуль слушает только сеть ядра).
45
+
46
+ Вход: ключ Консилиума в `KONSILIUM_API_KEY` (Аккаунт → API: нужный проект и право `tasks:work`) или OAuth-токен;
47
+ без него — вход `npx @consilium108/mcp login`, если этот пакет установлен. Никаких токенов модуля, секретов
48
+ сервера или runner здесь нет и не нужно.
49
+
50
+ Подключение (Claude Code, `.mcp.json`):
51
+
52
+ ```json
53
+ {
54
+ "mcpServers": {
55
+ "consilium-devops": {
56
+ "command": "npx",
57
+ "args": ["-y", "@consilium108/mcp-module-devops", "--project", "37"],
58
+ "env": { "KONSILIUM_API_KEY": "${KONSILIUM_API_KEY}" }
59
+ }
60
+ }
61
+ }
62
+ ```
63
+
64
+ Или `claude mcp add consilium-devops -e KONSILIUM_API_KEY=… -- npx -y @consilium108/mcp-module-devops --project 37`.
65
+ Удалённо (облачный MCP Консилиума, OAuth в клиенте): `https://konsilium.nativemind.net/mcp/p/<project_id>` —
66
+ там те же `request_deploy`, `deploy_status` и отчёты (модуль DevOps включается в «Подключённых приложениях»).
67
+
68
+ Ошибки — `code: message` и `structuredContent.error.code`: `auth_required`, `auth_invalid`, `project_not_chosen`,
69
+ `forbidden_project`, `no_deploy_right`, `module_disabled`, `module_unavailable`, `network_unavailable`,
70
+ `key_not_allowed` (ядро старше 1.1.0 — `list_deploy_targets` / `list_deploys` ещё не открыты для ключей), `rate_limited`.
71
+
72
+ ## Оркестратор агентов (1.2.0 → 1.3.0, #486, SDD-P37-160)
73
+
74
+ `consilium-devops-orchestrator` — третья команда пакета и **отдельная** долгоживущая служба (systemd user unit), не
75
+ процесс MCP и не runner. Слушает события агентов проекта (SSE `projectEvents` из #437 + `get_events` для догонки и
76
+ как запасной long poll), ведёт устойчивую очередь (`state.json` вне репозитория: курсоры, дедупликация, задания, lease,
77
+ outbox отчётов) с блокировкой на проект + окружение + цель, выбирает **действительно свободного** совместимого агента
78
+ (слоты из конфига + факты монитора ходов #470 из `~/.local/state/konsilium-mcp/<sha1>/turnmonitor/`; запущенный процесс
79
+ сам по себе свободным не считается) и передаёт ему структурированное задание через адаптер провайдера (Claude Code,
80
+ Codex, generic). `DEPLOY_REQUIRED` — сигнал на **проверку**: агент может только *запросить* выкатку (`request_deploy`),
81
+ одобряет человек ✅; оркестратор ничего не одобряет и не обходит permission gate. После запроса задание следит за
82
+ статусом выкатки на сервере (pending → `waiting_for_user`, approved/running → `running`, done → `succeeded`, failed →
83
+ `failed` (runner), rejected/expired → `cancelled`) и держит блокировку цели. Отчёты — в журнал событий проекта через
84
+ существующий маршрут `POST /api/projects/:id/agent-events` (идемпотентно, никого не уведомляет; свои события не
85
+ перечитываются).
86
+
87
+ <!-- Обновлено ассистентом (Claude Opus 5.5), 2026-11-24: 1.3.0 — G1–G4 и этап 3 (решение владельца «Запускай все»). -->
88
+
89
+ **1.3.0 — события выкаток, маршрутизация по цели, живой запуск по слоту.**
90
+ - *События выкаток (G1)*: ядро (и модуль DevOps в режиме `remote` через свой `core_outbox`) пишет в журнал проекта
91
+ `deploy.requested / approved / rejected / running / done / failed / rolled_back / expired` (`meta`: id, ключ цели,
92
+ вид, статус, exit/health; без хвоста лога). Оркестратор подписан на `agent.*` и `deploy.*` и двигает задания по
93
+ ним; опрос `GET /deploys/:id` остаётся запасным — каждый такт, пока сервер не прислал ни одного `deploy.*` по
94
+ проекту, затем только после `deployPollFallbackMs` (5 мин) тишины. `deploy.requested` своей цели после назначения
95
+ даёт номер выкатки, если агент его не назвал.
96
+ - *Цель из события (G2)*: событие агента может нести `target / environment / branch / commit_sha`; маршрут выбирается
97
+ среди настроенных маршрутов проекта события (событие цель не добавляет: чужая цель → `target_not_routed`), ветка и
98
+ коммит попадают в задание.
99
+ - *Монитор ходов (G3/G4)*: с `@consilium108/mcp` ≥ 0.11.1 состояние сессий читается через её экспорт
100
+ `@consilium108/mcp/turnmonitor` (в т. ч. `TURN_STARTED` — начало хода), без неё — из файлов, как раньше.
101
+ - *Запуск (этап 3)*: глобально по-прежнему `dry_run`; включается **по слоту**:
102
+
103
+ | `agents[].dispatch` | Где можно | Что делает |
104
+ |---|---|---|
105
+ | `dry_run` (по умолчанию) | любой слот | план записывается, ничего не запускается |
106
+ | `live` | только `mode: "headless"` + `provider: "claude"`; только в `run` | `claude -p <задание> --output-format json --permission-mode default --allowedTools <DevOps MCP: request_deploy, deploy_status, list_deploys, list_deploy_targets, runner_status; git log/status/diff/show/rev-parse>` в `workspace` слота, без оболочки; один процесс на слот; таймаут `timeout_ms` (≤ `leaseMs`, по умолчанию = lease) → остановка и повтор; окружение — только имена из списка по умолчанию + `env_pass` слота; лог запуска (маскированный хвост) — `<stateDir>/live/J<n>-a<попытка>.json`; итог (`ORCHESTRATOR_RESULT`) → отчёт agent-events |
107
+ | `handoff` | только `mode: "session"` | `create_handoff` (#F73) в сессию человека (`handoff_agent` — id агента из `list_agents`, иначе провайдер); второй процесс в сессию не запускается; результат передачи с `ORCHESTRATOR_RESULT` завершает задание; невзятая к концу lease передача отменяется |
108
+
109
+ Любой план с флагом обхода (`--dangerously-skip-permissions`, `bypassPermissions`, иной `--permission-mode`, `--yolo`…),
110
+ лишним флагом (`--mcp-config` и т. п.), инструментом вне списка или чужим бинарником отклоняется **до** запуска
111
+ (`failed`). Одобрить выкатку оркестратор и запущенный агент не могут: такого вызова нет, одобряет человек ✅.
112
+
113
+ Переключить один слот на живой запуск (пример):
114
+
115
+ ```json
116
+ { "id": "claude-headless", "provider": "claude", "mode": "headless", "dispatch": "live",
117
+ "workspace": "~/proj/nativemind.net/consilium.nativemind.net", "projects": [37],
118
+ "claude_bin": "~/.local/bin/claude", "timeout_ms": 900000, "capabilities": ["deploy_check"] }
119
+ ```
120
+
121
+ затем `check` (покажет `claude-headless (live)`) и перезапуск службы; в workspace слота должен быть подключён DevOps
122
+ MCP под именем `consilium-devops` (инструменты `mcp__consilium-devops__*`), а `claude` — доступен по `claude_bin`.
123
+
124
+ ```
125
+ consilium-devops-orchestrator config --print --repo <dir> --project <id> > ~/.config/consilium-devops-orchestrator/config.json
126
+ consilium-devops-orchestrator check # проверить конфиг
127
+ consilium-devops-orchestrator agents # слоты агентов и их состояние сейчас
128
+ consilium-devops-orchestrator once # догнать события, один такт, напечатать статус
129
+ consilium-devops-orchestrator unit --print # юнит systemd (ничего не ставит)
130
+ consilium-devops-orchestrator status # последний status.json службы
131
+ ```
132
+
133
+ Учётные данные: `KONSILIUM_API_KEY` (ksk_… с `tasks:work`) или вход `npx @consilium108/mcp login`; в конфиге секретов нет.
134
+
135
+ ## Runner
136
+
137
+ <!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-23. -->
138
+
139
+ Тот же пакет — вторая точка входа: **`consilium-devops-runner`**, долгоживущая служба на сервере проекта (systemd).
140
+ Это **не** процесс MCP: MCP только просит выкатку (`request_deploy`) и смотрит статус (`runner_status`); одобряет
141
+ человек (✅ в боте); runner берёт у ядра только одобренные запросы своей цели и выполняет команды **из своего
142
+ локального конфига** — сервер команд не присылает. Код runner'а — только встроенные модули Node (`./runner`,
143
+ `src/runner/*`), MCP SDK ему не нужен.
144
+
145
+ | Что | Как |
146
+ |---|---|
147
+ | Точки входа | `consilium-devops-mcp` (stdio MCP, агентам), `consilium-devops-runner` (служба); `mcp-module-devops` = MCP (для `npx -y @consilium108/mcp-module-devops`) |
148
+ | Вход в ядро | токен цели `kdr_…` (создаёт владелец: `/deploytarget <ключ> <название>` в боте, показывается один раз); не ключ человека |
149
+ | API | `POST /api/deploy/runner/heartbeat`, `/claim`, `/:id/result` ядра (ядро проксирует в API модуля, `MODULE_DEVOPS=remote`) |
150
+ | Конфиг | вне репозитория: `$CONSILIUM_DEVOPS_RUNNER_CONFIG` → `~/.config/consilium-devops-runner/config.json` → `/etc/consilium-devops-runner/config.json`; права 600 (иначе отказ `config_perms`); токен — `tokenFile` (600), `token` или `CONSILIUM_RUNNER_TOKEN` |
151
+ | Переопределения | `KONSILIUM_API_URL`, `CONSILIUM_RUNNER_PATH`, `CONSILIUM_RUNNER_STATE_DIR`, `CONSILIUM_RUNNER_LOG_FORMAT` (`json`/`text`), `CONSILIUM_RUNNER_TELEGRAM_TOKEN` |
152
+ | PATH | явный (`path` в конфиге; по умолчанию `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin` + `~/development/flutter/bin`, если есть); перед выкаткой проверяется, что все команды на месте — иначе ничего не запускается, ошибка `command_not_found: «docker» not on PATH (PATH=…)` (11.11 было «spawn docker ENOENT») |
153
+ | Надёжность | одна выкатка за раз (lock-файл), heartbeat и во время выкатки, идемпотентный claim (`state.json`: запрос не выполняется дважды, недоставленный итог досылается, прерванный — сообщается как `interrupted`), полный лог каждой выкатки — `<stateDir>/logs/D<id>.log`, в ядро — хвост 4096 символов |
154
+ | Остановка | SIGTERM ждёт конца текущей выкатки (`stopTimeoutMs`, по умолчанию 20 мин; юнит `KillMode=mixed`, `TimeoutStopSec=1500`); повторный сигнал прерывает шаг, откат всё равно выполняется |
155
+ | Логи | JSON по строке в stdout (journald); токены маскируются |
156
+ | Сторож (`watch`) | диск и health раз в минуту; в Telegram — только с токеном из **своего** файла runner'а (`watch.envFile`, например `~/.config/consilium-devops-runner/runner.env`) или `CONSILIUM_RUNNER_TELEGRAM_TOKEN`; файлы `.env*` (окружение ядра) не читаются; без токена — только журнал |
157
+
158
+ Команды (ничего не устанавливают и не запускают, кроме `run` / `once`):
159
+
160
+ ```bash
161
+ consilium-devops-runner config --print --repo /path/to/consilium.nativemind.net > ~/.config/consilium-devops-runner/config.json
162
+ consilium-devops-runner doctor [--heartbeat] [--no-docker] # docker/git/node/flutter на PATH, compose-файлы, репозиторий, права, токен (без значения), доступность ядра
163
+ consilium-devops-runner install --print [--user] # печатает юнит systemd и все шаги установки
164
+ consilium-devops-runner unit --print [--user] # только юнит
165
+ consilium-devops-runner run # служба
166
+ consilium-devops-runner once # один цикл (heartbeat, claim, выполнить одобренное)
167
+ ```
168
+
169
+ Из рабочей копии без установки: `node packages/mcp-module-devops/bin/consilium-devops-runner.js …`; из npm (после
170
+ публикации): `npx -y -p @consilium108/mcp-module-devops consilium-devops-runner …`.
171
+
172
+ ### Цель и рецепт `konsilium-linux`
173
+
174
+ ```json
175
+ {
176
+ "server": "https://konsilium.nativemind.net",
177
+ "tokenFile": "~/.config/consilium-devops-runner/token",
178
+ "path": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/anton/development/flutter/bin",
179
+ "targets": {
180
+ "konsilium-prod": {
181
+ "recipe": "konsilium-linux",
182
+ "repoDir": "/path/to/consilium.nativemind.net",
183
+ "composeFiles": null,
184
+ "composeProfiles": [],
185
+ "services": ["app", "mcp"],
186
+ "tests": { "server": true, "flutter": true },
187
+ "buildWeb": true,
188
+ "backup": true,
189
+ "appUrl": "http://127.0.0.1:8090",
190
+ "mcpUrl": "http://127.0.0.1:8091"
191
+ }
192
+ },
193
+ "watch": { "diskPath": "/", "minFreeGb": 30, "health": "http://127.0.0.1:8090/api/health", "chatIds": [], "envFile": "~/.config/consilium-devops-runner/runner.env" }
194
+ }
195
+ ```
196
+
197
+ Шаги рецепта (процедура ведущего на Linux-проде):
198
+
199
+ 1. **до выкатки** (сбой → ничего не менялось, отката нет): `preSteps` (свои команды) → тесты сервера (vitest в
200
+ `node:22-bookworm` на копии `server/` + `packages/` в `<stateDir>/test-tree`, `npm ci` только при смене lock) →
201
+ `flutter analyze --no-fatal-infos` и `flutter test` в `app/konsilium_flutter` → `bash scripts/build-web.sh` →
202
+ `docker compose exec -T app node --no-deprecation scripts/db-backup.js`;
203
+ 2. **выкатка**: образ запущенного контейнера каждого сервиса → `konsilium-<svc>:prev`; `user_version` до;
204
+ `GIT_SHA=$(git rev-parse HEAD) docker compose up -d --build app mcp`; ожидание healthy (`healthyTimeoutMs`, 5 мин);
205
+ 3. **проверки**: `GET /api/health` 200, `POST /mcp` 401 без ключа, `POST /line/webhook` и `/max/webhook` 401,
206
+ `user_version` через node + better-sqlite3 внутри контейнера app (не меньше, чем до), ошибок в логах app/mcp с
207
+ начала выкатки 0 (`logErrorPattern`);
208
+ 4. **откат** при сбое шага 2–3 (и по кнопке «↩ Откатить»): `docker tag konsilium-<svc>:prev konsilium-<svc>:latest`,
209
+ `docker compose up -d --no-build app mcp`, ожидание healthy.
210
+
211
+ Настраивается: `composeFiles` (список `-f`; `null` — обычный `docker compose`, он сам берёт
212
+ `docker-compose.override.yml` и `COMPOSE_FILE` из `.env` проекта; на проде с профилем ИИ —
213
+ `["docker-compose.yml", "docker-compose.override.yml", "docker-compose.ai.yml"]` и `composeProfiles: ["ai"]`, если
214
+ `COMPOSE_FILE` в `.env` не задан), `services`, `imagePrefix`, `tests` (`false` — без тестов), `testImage`,
215
+ `flutterAnalyzeArgs`, `flutterTestArgs`, `buildWeb`, `backup`, `preSteps`, `httpChecks` (`[{ method, url, expect }]`),
216
+ `userVersion`, `logErrors`, `logErrorPattern`, `healthyTimeoutMs`, `stepTimeoutMs`, `health`. Цель без `recipe` со
217
+ своими `deploy` / `rollback` / `health` (формат старого `deploy-runner/config.json`) работает как раньше. `git pull`
218
+ runner не делает: выкатывается то, что лежит в рабочей копии (HEAD).
219
+
220
+ ### Установка на сервере (делает человек)
221
+
222
+ `consilium-devops-runner install --print` (или MCP `runner_setup`) печатает точные команды: токен цели через
223
+ `/deploytarget` → конфиг и `token` в `~/.config/consilium-devops-runner/` (700/600) → `doctor` → `doctor --heartbeat` →
224
+ юнит `/etc/systemd/system/consilium-devops-runner.service` (`User=` с доступом к docker, `KillMode=mixed`) →
225
+ `sudo systemctl enable --now consilium-devops-runner` → `journalctl -u consilium-devops-runner -f` → пробная выкатка
226
+ (`request_deploy` / `/deploy` → ✅). Остановить: `sudo systemctl stop consilium-devops-runner`; убрать:
227
+ `disable --now` и удалить юнит.
228
+
229
+ Старый каталог `deploy-runner/` монорепо — тонкая обёртка над `src/runner` (для прежнего запуска
230
+ `node deploy-runner/runner.js` с `deploy-runner/config.json` и тестов ядра).
231
+
232
+ Сборка и проверка: `npm install && npm test` (модуль + stdio-тест с поддельным ядром + runner с поддельным ядром и `docker`); `npm pack` — пакет;
233
+ публикация — `npm publish` (владелец/ведущий по «публикуй»).
234
+
28
235
  Лицензия: NativeMindNONC (см. LICENSE).
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ // generated by Claude (Opus 5.5), 2026-11-22; Konsilium #482 (TASK-P37-482): the standalone DevOps MCP on stdio.
3
+ // stdout is JSON-RPC only; every log line goes to stderr. No module or service secret is read here — only the person's
4
+ // Konsilium credential (KONSILIUM_API_KEY, or the sign-in of `npx @consilium108/mcp login` when that package is installed).
5
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
+ import { createDevopsMcp, DEFAULT_API_URL } from '../src/standalone.js';
7
+ import mod from '../src/index.js';
8
+
9
+ const USAGE = `consilium-devops-mcp — Konsilium DevOps MCP (stdio): deploy requests and their status, deploy targets, debug reports
10
+
11
+ npx -y @consilium108/mcp-module-devops [--project <id>] [--api <url>] [--devops-api <url>]
12
+
13
+ --project <id> active project (a choice, not a right; select_project changes it); default — the connection's default
14
+ --api <url> Konsilium core (default ${DEFAULT_API_URL})
15
+ --devops-api <url> the DevOps module API, only when it is reachable directly (default: through the core)
16
+
17
+ Environment:
18
+ KONSILIUM_API_KEY a Konsilium key (ksk_… from «Account → API»: the project + the right tasks:work) or an OAuth
19
+ access token; without it the sign-in of \`npx @consilium108/mcp login\` is used when available
20
+ KONSILIUM_PROJECT_ID the project (instead of --project)
21
+ KONSILIUM_API_URL the core (instead of --api)
22
+ DEVOPS_API_URL the module API (instead of --devops-api)
23
+ KONSILIUM_KEYCHAIN=off do not look into the OS credential store
24
+
25
+ Deploys are approved only by a person with the deploy right (✅ in the messenger); this MCP requests and watches.`;
26
+
27
+ const argv = process.argv.slice(2);
28
+ if (argv.includes('--help') || argv.includes('-h')) {
29
+ process.stdout.write(`${USAGE}\n`);
30
+ process.exit(0);
31
+ }
32
+ if (argv.includes('--version')) {
33
+ process.stdout.write(`${mod.version}\n`);
34
+ process.exit(0);
35
+ }
36
+ const opt = (name) => {
37
+ const i = argv.indexOf(name);
38
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : null;
39
+ };
40
+ const log = (m) => process.stderr.write(`[consilium-devops-mcp] ${m}\n`);
41
+ const env = process.env;
42
+ const apiUrl = (opt('--api') ?? env.KONSILIUM_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, '');
43
+ const devopsUrl = opt('--devops-api') ?? env.DEVOPS_API_URL ?? null;
44
+ const projectId = Number(opt('--project') ?? env.KONSILIUM_PROJECT_ID) || null;
45
+ const envKey = env.KONSILIUM_API_KEY || null;
46
+
47
+ /** The credential: the key from the environment, else the stored sign-in of @consilium108/mcp (optional peer). */
48
+ async function credentialsOf() {
49
+ if (envKey) return { bearer: async () => envKey, source: () => 'KONSILIUM_API_KEY' };
50
+ if (env.KONSILIUM_KEYCHAIN !== 'off') {
51
+ try {
52
+ const auth = await import('@consilium108/mcp/auth');
53
+ const store = await auth.openStore({ env, apiUrl });
54
+ const c = await auth.createCredentialProvider({ apiUrl, store, envKey: null }).init();
55
+ return { bearer: () => c.bearer(), ...(c.kind?.() === 'oauth' ? { refresh: (failed) => c.refresh(failed) } : {}), source: () => `sign-in (${store.backend})` };
56
+ } catch {
57
+ /* the host package is not installed or no store: tools answer auth_required */
58
+ }
59
+ }
60
+ return { bearer: async () => null, source: () => 'none' };
61
+ }
62
+
63
+ const credentials = await credentialsOf();
64
+ const { server } = createDevopsMcp({ apiUrl, devopsUrl, credentials, projectId });
65
+ await server.connect(new StdioServerTransport());
66
+ log(`${mod.name} ${mod.version}; core ${apiUrl}${devopsUrl ? `; module ${devopsUrl}` : ''}; project ${projectId ?? 'default of the connection'}; credential: ${credentials.source()}`);
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env node
2
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160: the local DevOps agent orchestrator of
3
+ // @consilium108/mcp-module-devops — a SEPARATE long-running service (a systemd user unit), not the MCP and not the runner.
4
+ // It listens to the project's agent events (#437 SSE + get_events), keeps a durable queue with a lock per target, picks a
5
+ // free compatible local agent (#470 turn-monitor facts) and dispatches a structured job — dry-run by default; per slot
6
+ // (2026-11-24, stage 3) "live" starts `claude -p` (headless claude slots, `run` only) and "handoff" hands the job to a
7
+ // person's session (create_handoff). It never approves a deploy. Credential: KONSILIUM_API_KEY or the
8
+ // `npx @consilium108/mcp login` sign-in.
9
+ import { readFileSync, existsSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { acquireLock, createLogger } from '../src/runner/index.js';
13
+ import {
14
+ createEventSource,
15
+ createOrchestrator,
16
+ createOrchestratorApi,
17
+ createOrchestratorStore,
18
+ createRegistry,
19
+ createLiveDispatcher,
20
+ defaultAdapters,
21
+ exampleOrchestratorConfig,
22
+ loadOrchestratorConfig,
23
+ orchestratorUnitText,
24
+ } from '../src/orchestrator/index.js';
25
+
26
+ const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
27
+ const BIN = fileURLToPath(import.meta.url);
28
+
29
+ const USAGE = `consilium-devops-orchestrator — Konsilium DevOps agent orchestrator (${PKG.name} ${PKG.version})
30
+
31
+ consilium-devops-orchestrator run the service: events → queue (lock per target) → free agent → dispatch
32
+ consilium-devops-orchestrator once catch up the events once, one tick, print the status (dry-run dispatch)
33
+ consilium-devops-orchestrator status the last status.json of the service (jobs, agents, cursors, metrics)
34
+ consilium-devops-orchestrator agents the agent slots and their state now (turn-monitor facts; changes nothing)
35
+ consilium-devops-orchestrator check validate the config (changes nothing)
36
+ consilium-devops-orchestrator config --print [--repo <dir>] [--project <id>] [--target <key>] PRINT an example config
37
+ consilium-devops-orchestrator unit --print PRINT the systemd user unit (installs nothing)
38
+ consilium-devops-orchestrator --version | --help
39
+
40
+ Options: --config <file>
41
+ Config (no secret inside): $CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG, else ~/.config/consilium-devops-orchestrator/config.json.
42
+ Environment: KONSILIUM_API_KEY (ksk_… with tasks:work, or an OAuth token) or the sign-in of \`npx @consilium108/mcp login\`;
43
+ KONSILIUM_API_URL, CONSILIUM_ORCHESTRATOR_STATE_DIR, CONSILIUM_ORCHESTRATOR_LOG_FORMAT (json|text), KONSILIUM_KEYCHAIN=off.
44
+ Dispatch is dry-run by default (the plan is recorded, nothing is started). Per agent slot: "dispatch": "live" (mode
45
+ headless, provider claude — \`claude -p\` with --permission-mode default and an explicit --allowedTools list, one job at a
46
+ time, timeout_ms ≤ leaseMs; only in \`run\`) or "handoff" (mode session — create_handoff into that session).
47
+ A deploy is approved only by a person with the deploy right (✅ in the bot); the orchestrator never approves.`;
48
+
49
+ const argv = process.argv.slice(2);
50
+ const has = (f) => argv.includes(f);
51
+ const opt = (name) => {
52
+ const i = argv.indexOf(name);
53
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : null;
54
+ };
55
+ const VALUED = new Set(['--config', '--repo', '--project', '--target']);
56
+ const cmd = argv.find((a, i) => !a.startsWith('-') && !VALUED.has(argv[i - 1])) ?? 'help';
57
+ const out = (s) => process.stdout.write(s.endsWith('\n') ? s : `${s}\n`);
58
+ const fail = (e, code = 1) => {
59
+ process.stderr.write(`consilium-devops-orchestrator: ${e.code ? `${e.code}: ` : ''}${e.message ?? e}\n`);
60
+ process.exit(code);
61
+ };
62
+
63
+ async function credentialsOf(env, apiUrl) {
64
+ if (env.KONSILIUM_API_KEY) return { bearer: async () => env.KONSILIUM_API_KEY, source: () => 'KONSILIUM_API_KEY' };
65
+ if (env.KONSILIUM_KEYCHAIN !== 'off') {
66
+ try {
67
+ const auth = await import('@consilium108/mcp/auth');
68
+ const store = await auth.openStore({ env, apiUrl });
69
+ const c = await auth.createCredentialProvider({ apiUrl, store, envKey: null }).init();
70
+ return { bearer: () => c.bearer(), source: () => `sign-in (${store.backend})` };
71
+ } catch {
72
+ /* no host package / no sign-in */
73
+ }
74
+ }
75
+ return { bearer: async () => null, source: () => 'none' };
76
+ }
77
+
78
+ /** G4: the read-only turn-monitor state of @consilium108/mcp ≥ 0.11.1, or null (the registry reads the files). */
79
+ async function turnMonitorOrNull() {
80
+ try {
81
+ const m = await import('@consilium108/mcp/turnmonitor');
82
+ return typeof m.turnMonitorState === 'function' ? m : null;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ async function subscribeSseOrNull() {
89
+ try {
90
+ return (await import('@nativemind108/mcp')).subscribeSse ?? null;
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ function build(config, { log, credentials, subscribeSse, turnMonitor, live = false }) {
97
+ const store = createOrchestratorStore({ dir: config.stateDir });
98
+ const adapters = defaultAdapters(config.agents.map((a) => a.provider));
99
+ const registry = createRegistry({ agents: config.agents, adapters, idleTtlMs: config.idleTtlMs, turnMonitor });
100
+ const api = createOrchestratorApi({ server: config.server, credentials, userAgent: `consilium-devops-orchestrator/${PKG.version}`, subscribeSse: config.sse ? subscribeSse : null });
101
+ const deps = { api, store, registry, adapters, log };
102
+ // stage 3: the live dispatcher only for `run` and only when a slot asks for it
103
+ if (live && config.agents.some((a) => a.dispatch === 'live')) deps.dispatcher = createLiveDispatcher({ logDir: join(config.stateDir, 'live'), log, onResult: (r) => deps.orc.onLiveResult(r) });
104
+ const orc = createOrchestrator(config, deps);
105
+ deps.orc = orc;
106
+ deps.source = createEventSource({ api, store, projects: config.projects, handle: orc.handle, log, sse: config.sse });
107
+ return { orc, store, registry, source: deps.source };
108
+ }
109
+
110
+ async function main() {
111
+ if (has('--version') || cmd === 'version') return out(PKG.version);
112
+ if (has('--help') || has('-h') || cmd === 'help') return out(USAGE);
113
+ if (cmd === 'config') {
114
+ if (!has('--print')) return fail({ message: 'config writes nothing; use: config --print > <file>' }, 2);
115
+ return out(JSON.stringify(exampleOrchestratorConfig({ repoDir: opt('--repo') ?? '/path/to/consilium.nativemind.net', projectId: Number(opt('--project')) || 1, target: opt('--target') ?? 'konsilium-prod' }), null, 2));
116
+ }
117
+ if (cmd === 'unit') {
118
+ if (!has('--print')) return fail({ message: 'unit installs nothing; use: unit --print' }, 2);
119
+ return out(orchestratorUnitText({ bin: BIN }));
120
+ }
121
+ let config;
122
+ try {
123
+ config = loadOrchestratorConfig({ file: opt('--config') });
124
+ } catch (e) {
125
+ return fail(e, 78);
126
+ }
127
+ if (cmd === 'check') return out(`ok: ${config.file}; projects ${config.projects.join(', ')}; targets ${Object.keys(config.targets).join(', ') || '—'}; agents ${config.agents.map((a) => `${a.id}${a.dispatch !== 'dry_run' ? ` (${a.dispatch})` : ''}`).join(', ') || '—'}; dispatch ${config.dispatch}`);
128
+ if (cmd === 'status') {
129
+ const f = join(config.stateDir, 'status.json');
130
+ if (!existsSync(f)) return fail({ code: 'no_status', message: `${f} does not exist (the service has not run yet)` });
131
+ return out(readFileSync(f, 'utf8'));
132
+ }
133
+ const log = createLogger({ format: config.logFormat, out: cmd === 'run' ? process.stdout : process.stderr });
134
+ if (cmd === 'agents') {
135
+ const adapters = defaultAdapters(config.agents.map((a) => a.provider));
136
+ const registry = createRegistry({ agents: config.agents, adapters, idleTtlMs: config.idleTtlMs, turnMonitor: await turnMonitorOrNull() });
137
+ return out(JSON.stringify(registry.snapshot(), null, 2));
138
+ }
139
+ if (cmd === 'run' || cmd === 'once') {
140
+ let lock;
141
+ try {
142
+ lock = acquireLock(config.stateDir, 'orchestrator.lock');
143
+ } catch (e) {
144
+ return fail(e, 75);
145
+ }
146
+ const credentials = await credentialsOf(process.env, config.server);
147
+ log.info('credential', { source: credentials.source() });
148
+ const { orc, source } = build(config, { log, credentials, subscribeSse: cmd === 'run' ? await subscribeSseOrNull() : null, turnMonitor: await turnMonitorOrNull(), live: cmd === 'run' });
149
+ if (cmd === 'once') {
150
+ try {
151
+ for (const pid of config.projects) await source.catchUp(pid);
152
+ await orc.tick();
153
+ out(JSON.stringify(orc.status(), null, 2));
154
+ } catch (e) {
155
+ log.error('once failed', { code: e.code ?? 'error', error: e.message });
156
+ process.exitCode = 1;
157
+ } finally {
158
+ lock.release();
159
+ }
160
+ return;
161
+ }
162
+ const onSignal = (sig) => orc.stop(sig);
163
+ process.on('SIGTERM', onSignal);
164
+ process.on('SIGINT', onSignal);
165
+ await orc.start();
166
+ lock.release();
167
+ return;
168
+ }
169
+ fail({ message: `unknown command «${cmd}» (--help)` }, 2);
170
+ }
171
+
172
+ main().catch((e) => fail(e));