@consilium108/mcp-module-devops 1.3.0 → 1.5.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,53 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.5.0 — 2026-11-25 (OPS-AUDIT-435)
4
+
5
+ <!-- generated by Claude (Opus 5.5), 2026-11-24; Konsilium OPS-AUDIT-435 (deploy audit #435 recommendations 7, 8). -->
6
+
7
+ - **`consilium-devops-runner record`** — a deploy made from the terminal goes into the Konsilium deploy journal
8
+ (`POST /api/deploy/runner/record` with the target's runner token; `requested_via = 'terminal'`; nothing runs, nothing is
9
+ approved; idempotent by summary + start time; `--dry-run` prints the body without the token). Needs a core / DevOps
10
+ module with that route (older → `not_supported`). Exported as `runRecord`, `recordDeploy`, `buildRecordBody`, … from
11
+ `./runner`; the monorepo wrapper is `scripts/record-deploy.mjs`.
12
+ - Recipe `konsilium-linux`: the first check is `GET /api/health?deep=1` (DB, migrations = newest file, remote modules;
13
+ `deepHealth: false` → the plain `/api/health`); the example config's watchdog health URL uses `?deep=1` too.
14
+
15
+ ## 1.4.0 — 2026-11-24
16
+
17
+ <!-- generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2, SDD-P37-160 IT-160-1 … IT-160-7 — owner
18
+ 2026-11-24: the orchestrator works INSIDE the running JS MCP; the separate daemon / systemd unit / CLI are cancelled. -->
19
+
20
+ - **The DevOps Orchestrator runs inside `consilium-devops-mcp`** (one process, one lifecycle): the event listener (#437
21
+ SSE `projectEvents` + `get_events` from the cursor, long poll fallback, first start = baseline) starts after the
22
+ transport is connected and stops with it (transport closed, stdin ended, SIGTERM / SIGINT); cursor, jobs and leases
23
+ stay on disk and the next start replays from the cursor. One listener per workspace (leader lock): a second DevOps MCP
24
+ of the same workspace (another session) serves the tools only and takes over when the leader exits.
25
+ - **Jobs instead of dispatch.** `agent.deploy_required` of a routed project → a job `devops.deploy_check` in the shared
26
+ job inbox of `@consilium108/mcp-agent-jobs` 0.1.0 (new dependency; envelope `konsilium.agent-job/1`, the same as the
27
+ Developer MCP's jobs). New tools `jobs_inbox`, `jobs_claim`, `jobs_ack`, `jobs_status`, `jobs_result`,
28
+ `jobs_release` (+ resource `konsilium-jobs://inbox`, `notifications/resources/updated` and a log message on change):
29
+ the session's main agent claims a job and starts its own built-in subagent (Agent tool) with the returned prompt; the
30
+ subagent acks (lease), may `request_deploy`, and reports. Kept rules: one active job per project + environment +
31
+ target, coalescing, lease / retry with backoff / max attempts, stale results ignored, deploy followed by `deploy.*`
32
+ (poll fallback only in the listener's process), the deploy id from `deploy.requested` (IT-14), reports through
33
+ `agent-events` (`orc:` keys; own events ignored), G2 routing by the named target, #470 session state (now shown in
34
+ `jobs_inbox` / `jobs_status`, never a gate). New options of the bin: `--orchestrator-config`, `--workspace`,
35
+ `--no-jobs` (`KONSILIUM_JOBS=off`).
36
+ - **Removed** (the separate service of 1.2.0 / 1.3.0): bin `consilium-devops-orchestrator` (run / once / status / agents /
37
+ check / config --print / unit --print), the systemd unit text, the daemon loop, agent slots, provider adapters,
38
+ dry-run / live (`claude -p`) / hand-off dispatch and their exports (`createOrchestrator`, `createLiveDispatcher`,
39
+ `validateLivePlan`, `orchestratorUnitText`, `createOrchestratorStore`, `createEventSource`, `createOrchestratorApi`, …).
40
+ Moved to `@consilium108/mcp-agent-jobs`: the listener, the store (now the inbox), the API client. The config keeps
41
+ `projects / targets / routes / leaseMs / maxAttempts / backoffMs / deployPollFallbackMs / idleTtlMs / report`; old keys
42
+ (`agents`, `dispatch`, `reportDryRun`, `pollMs`, `stateDir`, `sse`, `logFormat`, `stopTimeoutMs`) are ignored with a
43
+ warning. The deploy runner (`consilium-devops-runner`, #482) is unchanged — it is a different thing.
44
+ - Exports of `./orchestrator`: `createDevopsProducer`, `createSessionRegistry`, `findOrchestratorConfig`, `jobContext`,
45
+ `promptOf`, `DEPLOY_CHECK_TOOLS`, `LEGACY_KEYS` and the kept event / registry / config helpers.
46
+ - Tests: `test/orchestrator.test.js` rewritten (12, through the real MCP tools on an in-memory transport: hand-off flow,
47
+ replay / duplicates, MCP restart, busy session + several subagents + lease expiry, approval-required + conflicting
48
+ deploys + IT-14, runner failure, reporting retry, two MCP processes, diagnostics + #470, one inbox with Developer jobs);
49
+ `orchestrator-live.test.js` removed; `standalone.test.js` lists the job tools.
50
+
3
51
  ## 1.3.0 — 2026-11-24
4
52
 
5
53
  <!-- generated by Claude (Opus 5.5), 2026-11-24; Konsilium SDD-P37-160 — owner 2026-11-24 «Запускай все, добавь сразу».
package/README.md CHANGED
@@ -69,68 +69,70 @@ Object.keys(mod.groups);
69
69
  `forbidden_project`, `no_deploy_right`, `module_disabled`, `module_unavailable`, `network_unavailable`,
70
70
  `key_not_allowed` (ядро старше 1.1.0 — `list_deploy_targets` / `list_deploys` ещё не открыты для ключей), `rate_limited`.
71
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
- Переключить один слот на живой запуск (пример):
72
+ ## Оркестратор внутри MCP (1.4.0, #486 v2, SDD-P37-160)
114
73
 
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
- ```
74
+ <!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-24, по решению владельца: никакой отдельной службы. -->
120
75
 
121
- затем `check` (покажет `claude-headless (live)`) и перезапуск службы; в workspace слота должен быть подключён DevOps
122
- MCP под именем `consilium-devops` (инструменты `mcp__consilium-devops__*`), а `claude` — доступен по `claude_bin`.
76
+ DevOps Orchestrator работает **внутри уже запущенного процесса** `consilium-devops-mcp` — того, что Claude Code (или
77
+ другой клиент) стартует для сессии. Отдельной службы, systemd-юнита, команды `consilium-devops-orchestrator` и второго
78
+ процесса агента больше нет (1.2.0 / 1.3.0 удалены из пакета). Жизненный цикл один: MCP стартовал — слушатель событий
79
+ поднялся; MCP закрыт (клиент закрыл транспорт, stdin кончился, SIGTERM/SIGINT) — подписка закрыта, курсор и очередь
80
+ остались на диске; следующий старт MCP дочитывает журнал от курсора.
123
81
 
124
82
  ```
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 службы
83
+ Консилиум ── project_events (#437: SSE projectEvents + get_events от курсора) ──► consilium-devops-mcp (один процесс)
84
+ ├ слушатель (лидер рабочей папки)
85
+ ├ inbox заданий (общий для MCP папки)
86
+ └ jobs_inbox / jobs_claim / jobs_ack /
87
+ jobs_status / jobs_result / jobs_release
88
+ основной агент сессии ── jobs_claim ──► встроенный субагент (Agent tool, та же сессия) ── request_deploy ──► ✅ человека
89
+ ──► существующий runner #482 (выкатка)
90
+ ```
91
+
92
+ - **События → задания.** `agent.deploy_required` проекта с маршрутом → задание `devops.deploy_check` (конверт
93
+ `konsilium.agent-job/1` пакета `@consilium108/mcp-agent-jobs`). `DEPLOY_REQUIRED` — сигнал на **проверку**, не на
94
+ выкатку. Одна цель (`проект:окружение:цель` = `lock_key`) — одно активное задание; сигналы цели в очереди сливаются;
95
+ во время активного — один следующий, ждёт. Повторная доставка (SSE + догонка, повтор после рестарта) задание не
96
+ дублирует (ключ идемпотентности — проект + id события).
97
+ - **Кто выполняет.** MCP агента не запускает. Основной агент в безопасный момент смотрит `jobs_inbox`, берёт задание
98
+ `jobs_claim` (атомарно — одно выполнение на задание, даже при нескольких процессах MCP и сессиях в одной папке) и
99
+ запускает **своего** субагента штатным Agent tool с `subagent_prompt` (в фоне). Субагент: `jobs_ack` (старт и пульс
100
+ аренды), проверка изменений, при необходимости `request_deploy`, затем `jobs_result` (`requested` + `deploy_id`,
101
+ `not_needed`, `blocked`). Аренда (по умолчанию из конфига, `leaseMs`) без пульса истекает → задание в очередь с
102
+ отсрочкой, после `maxAttempts` — `failed`; поздний результат прежнего запуска (`stale_run`) ничего не меняет.
103
+ - **Выкатка.** После `requested` задание ждёт ✅ человека (`waiting_for_user`, держит цель, не истекает) и следует за
104
+ выкаткой по событиям `deploy.*` (`approved/running` → `running`, `done` → `succeeded`, `failed` → `failed`,
105
+ `rejected/expired` → `cancelled`); опрос `GET /deploys/:id` — запасной (только в процессе-слушателе, только при
106
+ тишине журнала). `deploy.requested` своей цели после взятия даёт номер выкатки, если субагент его не назвал.
107
+ Одобрить не может никто из MCP: такого инструмента и маршрута нет. Runner (#482) — отдельная служба на сервере
108
+ выкатки, исполняет только одобренное.
109
+ - **Отчёты в Консилиум** — `POST /api/projects/:id/agent-events` (идемпотентно, `provider: devops-orchestrator`):
110
+ ожидание ✅ → `NEEDS_APPROVAL` (blocking), `blocked` → `BLOCKED`, `failed` → `ERROR` (exit/health, без хвоста лога),
111
+ `succeeded/cancelled` → `TASK_COMPLETED`. При недоступности сервера — повтор с отсрочкой (на диске).
112
+ - **Состояние сессии (#470)** — `jobs_inbox.session` / `jobs_status.session`: idle / running / waiting_for_user /
113
+ blocked / unavailable по фактам монитора ходов рабочей папки; брать задание не мешает (субагенты идут параллельно).
114
+ - **Диагностика** — `jobs_status` без аргументов: слушатель каждого модуля (этот процесс / другой), проекты, транспорт,
115
+ курсор, счётчики, метрики, последняя ошибка.
116
+
117
+ Как занятая сессия узнаёт о задании (проверено 24.11, TASK-P36-531 и документация Claude Code): уведомления MCP
118
+ (`resources/updated`, лог) Claude Code хода не начинают — поэтому (1) основной агент смотрит `jobs_inbox` между
119
+ своими шагами (это сказано в instructions MCP), (2) по желанию человека — хук `konsilium-jobs-hook` пакета
120
+ `@consilium108/mcp-agent-jobs` на `UserPromptSubmit` / `SessionStart` / `PostToolUse` (добавляет в контекст «есть
121
+ задания»), или `konsilium-jobs-hook watch` в инструменте Monitor. Второй сессии / `claude -p` нет.
122
+
123
+ Конфиг (без секретов; без файла DevOps-заданий нет, инструменты inbox работают): `--orchestrator-config <file>`,
124
+ `$CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG` или `~/.config/consilium-devops-orchestrator/config.json`:
125
+
126
+ ```json
127
+ { "projects": [37],
128
+ "targets": { "konsilium-prod": { "project_id": 1, "environment": "production", "approval": "human" } },
129
+ "routes": [{ "event": "agent.deploy_required", "project_id": 37, "target": "konsilium-prod" }],
130
+ "leaseMs": 1800000, "maxAttempts": 3, "backoffMs": 60000, "report": "agent-events" }
131
131
  ```
132
132
 
133
- Учётные данные: `KONSILIUM_API_KEY` (ksk_… с `tasks:work`) или вход `npx @consilium108/mcp login`; в конфиге секретов нет.
133
+ Ключи прежней службы (`agents`, `dispatch`, `reportDryRun`, `pollMs`, `stateDir`, `sse`, `logFormat`, `stopTimeoutMs`)
134
+ игнорируются с предупреждением в stderr. Inbox — `$XDG_STATE_HOME/konsilium-mcp/<sha1(папки)>/jobs/` (общий с Developer
135
+ MCP той же папки; `KONSILIUM_JOBS_DIR` — иначе); выключить — `--no-jobs` / `KONSILIUM_JOBS=off`.
134
136
 
135
137
  ## Runner
136
138
 
@@ -190,7 +192,7 @@ consilium-devops-runner once # один цикл
190
192
  "mcpUrl": "http://127.0.0.1:8091"
191
193
  }
192
194
  },
193
- "watch": { "diskPath": "/", "minFreeGb": 30, "health": "http://127.0.0.1:8090/api/health", "chatIds": [], "envFile": "~/.config/consilium-devops-runner/runner.env" }
195
+ "watch": { "diskPath": "/", "minFreeGb": 30, "health": "http://127.0.0.1:8090/api/health?deep=1", "chatIds": [], "envFile": "~/.config/consilium-devops-runner/runner.env" }
194
196
  }
195
197
  ```
196
198
 
@@ -202,7 +204,7 @@ consilium-devops-runner once # один цикл
202
204
  `docker compose exec -T app node --no-deprecation scripts/db-backup.js`;
203
205
  2. **выкатка**: образ запущенного контейнера каждого сервиса → `konsilium-<svc>:prev`; `user_version` до;
204
206
  `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,
207
+ 3. **проверки**: `GET /api/health?deep=1` 200 (БД, миграции, модули; `deepHealth: false` — простой `/api/health`), `POST /mcp` 401 без ключа, `POST /line/webhook` и `/max/webhook` 401,
206
208
  `user_version` через node + better-sqlite3 внутри контейнера app (не меньше, чем до), ошибок в логах app/mcp с
207
209
  начала выкатки 0 (`logErrorPattern`);
208
210
  4. **откат** при сбое шага 2–3 (и по кнопке «↩ Откатить»): `docker tag konsilium-<svc>:prev konsilium-<svc>:latest`,
@@ -217,6 +219,20 @@ consilium-devops-runner once # один цикл
217
219
  своими `deploy` / `rollback` / `health` (формат старого `deploy-runner/config.json`) работает как раньше. `git pull`
218
220
  runner не делает: выкатывается то, что лежит в рабочей копии (HEAD).
219
221
 
222
+ ### Запись терминальной выкатки (`record`, OPS-AUDIT-435)
223
+
224
+ Если выкатка сделана из терминала, а не кнопкой, ведущий сразу после неё записывает её в тот же журнал:
225
+
226
+ ```bash
227
+ consilium-devops-runner record --summary "app + mcp: …, миграции …" --exit-code 0 --health ok \
228
+ --started-at 2026-11-24T10:00:00Z --approval "Антон: «выкатывай» в терминале" [--log-file deploy.log] [--dry-run]
229
+ ```
230
+
231
+ `POST /api/deploy/runner/record` с токеном цели (`CONSILIUM_RUNNER_TOKEN` или `tokenFile` конфига; не печатается):
232
+ запись `requested_via = 'terminal'`, `approved_by` пустой, текст одобрения — в сводке; повтор не дублирует; событие
233
+ `deploy.done` / `deploy.failed` в журнал проекта, людям сообщений нет. Ничего не выполняет. В монорепо то же —
234
+ `node scripts/record-deploy.mjs …`.
235
+
220
236
  ### Установка на сервере (делает человек)
221
237
 
222
238
  `consilium-devops-runner install --print` (или MCP `runner_setup`) печатает точные команды: токен цели через
@@ -3,7 +3,10 @@
3
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
4
  // Konsilium credential (KONSILIUM_API_KEY, or the sign-in of `npx @consilium108/mcp login` when that package is installed).
5
5
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
+ import { createJobRuntime, createKonsiliumApi, ROUTES, jobsDirOf, bindToProcess } from '@consilium108/mcp-agent-jobs';
6
7
  import { createDevopsMcp, DEFAULT_API_URL } from '../src/standalone.js';
8
+ import { findOrchestratorConfig, createDevopsProducer, createSessionRegistry } from '../src/orchestrator/index.js';
9
+ import { redact } from '../src/runner/log.js';
7
10
  import mod from '../src/index.js';
8
11
 
9
12
  const USAGE = `consilium-devops-mcp — Konsilium DevOps MCP (stdio): deploy requests and their status, deploy targets, debug reports
@@ -13,6 +16,10 @@ const USAGE = `consilium-devops-mcp — Konsilium DevOps MCP (stdio): deploy req
13
16
  --project <id> active project (a choice, not a right; select_project changes it); default — the connection's default
14
17
  --api <url> Konsilium core (default ${DEFAULT_API_URL})
15
18
  --devops-api <url> the DevOps module API, only when it is reachable directly (default: through the core)
19
+ --orchestrator-config <file> the DevOps Orchestrator's targets / routes (default: $CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG,
20
+ ~/.config/consilium-devops-orchestrator/config.json); without it no DevOps jobs are made
21
+ --workspace <dir> the workspace of the job inbox (default: the working directory = the repository of the session)
22
+ --no-jobs no job inbox (KONSILIUM_JOBS=off)
16
23
 
17
24
  Environment:
18
25
  KONSILIUM_API_KEY a Konsilium key (ksk_… from «Account → API»: the project + the right tasks:work) or an OAuth
@@ -22,7 +29,10 @@ Environment:
22
29
  DEVOPS_API_URL the module API (instead of --devops-api)
23
30
  KONSILIUM_KEYCHAIN=off do not look into the OS credential store
24
31
 
25
- Deploys are approved only by a person with the deploy right (✅ in the messenger); this MCP requests and watches.`;
32
+ The DevOps Orchestrator runs INSIDE this process (TASK-P37-486 v2): it listens to the Konsilium journal (#437), turns
33
+ agent.deploy_required of a routed project into a job of the workspace's job inbox and follows the deploy; the main agent
34
+ of the session claims the job (jobs_claim) and starts its own built-in subagent. No separate service, no second agent
35
+ process. Deploys are approved only by a person with the deploy right (✅ in the messenger); this MCP requests and watches.`;
26
36
 
27
37
  const argv = process.argv.slice(2);
28
38
  if (argv.includes('--help') || argv.includes('-h')) {
@@ -61,6 +71,40 @@ async function credentialsOf() {
61
71
  }
62
72
 
63
73
  const credentials = await credentialsOf();
64
- const { server } = createDevopsMcp({ apiUrl, devopsUrl, credentials, projectId });
74
+ const optional = async (name, pick) => {
75
+ try {
76
+ return pick(await import(name));
77
+ } catch {
78
+ return null;
79
+ }
80
+ };
81
+
82
+ /** TASK-P37-486 v2: the job inbox + the DevOps Orchestrator in THIS process (off: --no-jobs / KONSILIUM_JOBS=off). */
83
+ async function jobRuntime() {
84
+ if (argv.includes('--no-jobs') || env.KONSILIUM_JOBS === 'off') return null;
85
+ const logger = { info: (m, f) => log(`${m}${f ? ` ${JSON.stringify(f)}` : ''}`), warn: (m, f) => log(`warn: ${m}${f ? ` ${JSON.stringify(f)}` : ''}`), error: (m, f) => log(`error: ${m}${f ? ` ${JSON.stringify(f)}` : ''}`) };
86
+ try {
87
+ const workspace = opt('--workspace') ?? env.KONSILIUM_WORKSPACE ?? process.cwd();
88
+ const found = findOrchestratorConfig({ file: opt('--orchestrator-config') });
89
+ if (found.error) log(`orchestrator config ${found.error.file}: ${found.error.code}: ${found.error.message} — no DevOps jobs`);
90
+ const cfg = found.config;
91
+ for (const w of cfg?.warnings ?? []) log(`orchestrator config: ${w}`);
92
+ const signedIn = credentials.source() !== 'none';
93
+ const api = signedIn ? createKonsiliumApi({ server: cfg?.server ?? apiUrl, credentials, routes: [ROUTES.events, ROUTES.deploy, ROUTES.report], subscribeSse: await optional('@nativemind108/mcp', (m) => m.subscribeSse ?? null), userAgent: `consilium-devops-mcp/${mod.version}` }) : null;
94
+ const registry = createSessionRegistry({ workspace, idleTtlMs: cfg?.idleTtlMs, turnMonitor: await optional('@consilium108/mcp/turnmonitor', (m) => m) });
95
+ const producer = cfg ? createDevopsProducer({ config: cfg, api, log: logger, registry, redact }) : null;
96
+ return createJobRuntime({ dir: jobsDirOf(workspace), workspace, producers: producer ? [producer] : [], api, log: logger, leaseMs: cfg?.leaseMs, maxAttempts: cfg?.maxAttempts, backoffMs: cfg?.backoffMs, sessionState: () => registry.state() });
97
+ } catch (e) {
98
+ log(`job inbox off: ${e.code ?? 'error'}: ${e.message}`);
99
+ return null;
100
+ }
101
+ }
102
+
103
+ const jobs = await jobRuntime();
104
+ const { server } = createDevopsMcp({ apiUrl, devopsUrl, credentials, projectId, jobs });
65
105
  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()}`);
106
+ if (jobs) {
107
+ bindToProcess(jobs, { server, log });
108
+ await jobs.start();
109
+ }
110
+ log(`${mod.name} ${mod.version}; core ${apiUrl}${devopsUrl ? `; module ${devopsUrl}` : ''}; project ${projectId ?? 'default of the connection'}; credential: ${credentials.source()}; jobs: ${jobs ? `${jobs.dir} (DevOps jobs: ${jobs.modules().includes('devops') ? 'on' : 'off — no orchestrator config'})` : 'off'}`);
@@ -17,6 +17,9 @@ import {
17
17
  formatDoctor,
18
18
  installSteps,
19
19
  loadConfig,
20
+ RECORD_USAGE,
21
+ formatRecorded,
22
+ runRecord,
20
23
  tick,
21
24
  unitText,
22
25
  } from '../src/runner/index.js';
@@ -32,6 +35,8 @@ const USAGE = `consilium-devops-runner — Konsilium deploy runner (${PKG.name}
32
35
  consilium-devops-runner install --print [--user] [--repo <dir>] [--target <key>] PRINT the systemd unit and steps
33
36
  consilium-devops-runner unit --print [--user] [--repo <dir>] PRINT only the unit
34
37
  consilium-devops-runner config --print [--repo <dir>] [--target <key>] PRINT an example config (no secret)
38
+ consilium-devops-runner record --summary "…" [--exit-code N] [--approval "…"] [--dry-run] put a TERMINAL deploy into
39
+ the Konsilium deploy journal (after the fact; nothing runs; record --help)
35
40
  consilium-devops-runner --version | --help
36
41
 
37
42
  Options: --config <file>
@@ -59,6 +64,17 @@ const repoGuess = () => resolve(dirname(BIN), '..', '..', '..');
59
64
 
60
65
  async function main() {
61
66
  if (has('--version') || cmd === 'version') return out(PKG.version);
67
+ if (cmd === 'record') {
68
+ // OPS-AUDIT-435: its own flags (--summary "…" has free text) — parsed by runRecord, not by the generic parser above
69
+ if (has('--help') || has('-h')) return out(RECORD_USAGE);
70
+ try {
71
+ const r = await runRecord(argv.slice(argv.indexOf('record') + 1));
72
+ if (r.dryRun) return out(JSON.stringify({ server: r.server, token: r.tokenPresent ? 'present (not shown)' : 'missing', body: r.body }, null, 2));
73
+ return out(formatRecorded(r.row));
74
+ } catch (e) {
75
+ return fail(e, e.code === 'bad_argument' || e.code === 'summary_required' ? 2 : 1);
76
+ }
77
+ }
62
78
  if (has('--help') || has('-h') || cmd === 'help') return out(USAGE);
63
79
  const configFile = opt('--config');
64
80
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@consilium108/mcp-module-devops",
3
- "version": "1.3.0",
4
- "description": "DevOps module of the Konsilium MCP (#442): Deploy requests by button and their status; debug reports of apps. Loaded by the host @consilium108/mcp; also runs on its own (bin consilium-devops-mcp, #482); the deploy runner service (bin consilium-devops-runner); the local agent orchestrator (bin consilium-devops-orchestrator, #486).",
3
+ "version": "1.5.0",
4
+ "description": "DevOps module of the Konsilium MCP (#442): Deploy requests by button and their status; debug reports of apps. Loaded by the host @consilium108/mcp; also runs on its own (bin consilium-devops-mcp, #482) — with the DevOps Orchestrator inside that process (#486 v2: Konsilium events → jobs of the workspace's job inbox, claimed by the session's own subagents); the deploy runner service (bin consilium-devops-runner).",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "NativeMind",
7
7
  "homepage": "https://konsilium.nativemind.net",
@@ -19,8 +19,7 @@
19
19
  "bin": {
20
20
  "mcp-module-devops": "bin/consilium-devops-mcp.js",
21
21
  "consilium-devops-mcp": "bin/consilium-devops-mcp.js",
22
- "consilium-devops-runner": "bin/consilium-devops-runner.js",
23
- "consilium-devops-orchestrator": "bin/consilium-devops-orchestrator.js"
22
+ "consilium-devops-runner": "bin/consilium-devops-runner.js"
24
23
  },
25
24
  "files": [
26
25
  "src",
@@ -42,6 +41,7 @@
42
41
  }
43
42
  },
44
43
  "dependencies": {
44
+ "@consilium108/mcp-agent-jobs": "^0.1.0",
45
45
  "@modelcontextprotocol/sdk": "^1.32.2",
46
46
  "@nativemind108/mcp": "^1.13.0",
47
47
  "zod": "^4.6.7"
@@ -0,0 +1,46 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2 (SDD-P37-160, IT-160-5 / IT-160-6): what a
2
+ // subagent gets for a DevOps job — the job context (only verified fields; unknown ones named as unknown) and the brief.
3
+ // Kept from adapters.js of 1.2.0 / 1.3.0 (jobContext, promptOf, DEPLOY_CHECK_TOOLS); the provider adapters, the live
4
+ // `claude -p` plans and the ORCHESTRATOR_RESULT line are gone: the result now comes through jobs_result (or the
5
+ // AGENT_JOB_RESULT line of @consilium108/mcp-agent-jobs). Rules: the subagent may only analyse and REQUEST a deploy
6
+ // (request_deploy); a person approves it (✅); no secret in the brief — only refs, ids, the target key, the environment.
7
+
8
+ /** DevOps MCP tools a deploy_check may use (read + request; there is no approve tool and none is allowed). */
9
+ export const DEPLOY_CHECK_TOOLS = ['request_deploy', 'deploy_status', 'list_deploys', 'list_deploy_targets', 'runner_status'];
10
+
11
+ /** The structured job context: only verified fields; what is not known is listed in `unknown`. */
12
+ export function jobContext(job) {
13
+ const src = job.sources ?? [];
14
+ // G2: what the agents said about the deploy (branch / commit) — given when every signal agrees, else still unknown
15
+ const one = (k) => {
16
+ const v = [...new Set(src.map((s) => s[k]).filter(Boolean))];
17
+ return v.length === 1 && src.every((s) => s[k]) ? v[0] : null;
18
+ };
19
+ const branch = one('branch');
20
+ const commit = one('commit_sha');
21
+ return {
22
+ schema: 'konsilium.devops-job/2',
23
+ kind: job.kind,
24
+ project_id: job.projectId,
25
+ target: job.target,
26
+ environment: job.environment,
27
+ approval: { required: true, by: 'a person with the deploy right (✅ in the Konsilium bot)', orchestrator_may_approve: false, agent_may_approve: false },
28
+ signals: src.map((s) => ({ event_id: s.event_id, project_id: s.project_id, type: s.type, task_ref: s.task_ref ?? null, session: s.session ?? null, summary: s.summary ?? null, at: s.at ?? null, ...(s.branch ? { branch: s.branch } : {}), ...(s.commit_sha ? { commit_sha: s.commit_sha } : {}) })),
29
+ ...(branch ? { branch } : {}),
30
+ ...(commit ? { commit_sha: commit } : {}),
31
+ unknown: [...(branch ? [] : ['repository branch']), ...(commit ? [] : ['commit SHA']), 'what changed since the last deploy'],
32
+ };
33
+ }
34
+
35
+ export function promptOf(job) {
36
+ return [
37
+ `DevOps deploy check for the deploy target «${job.target}» (${job.environment}), Konsilium project ${job.projectId}.`,
38
+ 'An agent turn said a deploy may be needed (DEPLOY_REQUIRED). That is a signal, NOT a command to deploy.',
39
+ '1. Check what changed (git log / git status in this workspace) and whether those changes are committed and tested.',
40
+ `2. If a deploy is warranted, call the DevOps MCP tool request_deploy with target «${job.target}» and a one-line summary. That only creates a request: a person with the deploy right approves it with ✅ in the bot; the deploy runner then executes it. Never approve, never run the deploy steps yourself, never edit the runner config.`,
41
+ '3. If it is not warranted or you are unsure, do not request; say why.',
42
+ 'Report: outcome «requested» with deploy_id (the request id request_deploy returned), «not_needed», or «blocked» with the reason.',
43
+ 'The job context (JSON):',
44
+ JSON.stringify(jobContext(job)),
45
+ ].join('\n');
46
+ }
@@ -1,13 +1,14 @@
1
1
  // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §4): the orchestrator's config.
2
- // It holds NO secret: the Konsilium credential comes from KONSILIUM_API_KEY or the `@consilium108/mcp login` sign-in (as
3
- // in the DevOps MCP). Location: $CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG, else ~/.config/consilium-devops-orchestrator/
4
- // config.json, else /etc/consilium-devops-orchestrator/config.json. Validation refuses anything that could approve or
5
- // start a production deploy on its own. The global dispatch stays "dry_run"; stage 3 (2026-11-24, owner «Запускай все»)
6
- // turns starting agents on PER SLOT only: agents[].dispatch "live" (mode headless + provider claude: `claude -p` with the
7
- // default permission mode and an explicit tool list) or "handoff" (mode session: create_handoff into that session).
2
+ // v2 (owner, 2026-11-24): the orchestrator runs INSIDE the DevOps MCP (bin consilium-devops-mcp) — this file only says
3
+ // which projects it listens to and which targets / routes make jobs. It holds NO secret: the Konsilium credential is
4
+ // the MCP's (KONSILIUM_API_KEY or the `@consilium108/mcp login` sign-in). Location: --orchestrator-config <file>,
5
+ // $CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG, ~/.config/consilium-devops-orchestrator/config.json,
6
+ // /etc/consilium-devops-orchestrator/config.json; no file = the MCP makes no DevOps jobs (the inbox tools still work).
7
+ // Keys of the removed service (agents, dispatch, reportDryRun, pollMs, stateDir, sse, logFormat, stopTimeoutMs) are
8
+ // ignored with a warning: jobs go to the running session's own subagents through jobs_claim; nothing is started.
8
9
  import { existsSync, readFileSync } from 'node:fs';
9
10
  import { homedir } from 'node:os';
10
- import { dirname, join, resolve } from 'node:path';
11
+ import { join } from 'node:path';
11
12
  import { DevopsMcpError } from '../errors.js';
12
13
  import { DEFAULT_SERVER } from '../runner/config.js';
13
14
 
@@ -17,14 +18,6 @@ export const ORCHESTRATOR_PROVIDER = 'devops-orchestrator';
17
18
  /** Idempotency-key prefix of its own reports; the server stores it as content_hash «tm:orc:…». */
18
19
  export const OWN_KEY_PREFIX = 'orc:';
19
20
  export const JOB_KINDS = ['deploy_check'];
20
- export const DISPATCH_MODES = ['dry_run'];
21
- /** Per agent slot (stage 3): dry_run (default) · live (headless claude only) · handoff (session slots only). */
22
- export const SLOT_DISPATCH = ['dry_run', 'live', 'handoff'];
23
- /** Environment variables a live run inherits by default (names only; values never logged). Anything else is dropped. */
24
- export const LIVE_ENV_DEFAULT = ['PATH', 'HOME', 'USER', 'LOGNAME', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'TMPDIR', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'XDG_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR', 'ANTHROPIC_API_KEY', 'KONSILIUM_API_KEY', 'KONSILIUM_API_URL'];
25
- export const AGENT_MODES = ['session', 'headless'];
26
-
27
- const expandHome = (p, home) => (p && p.startsWith('~/') ? join(home, p.slice(2)) : p);
28
21
 
29
22
  export function orchestratorConfigCandidates(env = process.env, home = homedir()) {
30
23
  if (env.CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG) return [env.CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG];
@@ -32,19 +25,20 @@ export function orchestratorConfigCandidates(env = process.env, home = homedir()
32
25
  return [join(xdg, ORCHESTRATOR_NAME, 'config.json'), `/etc/${ORCHESTRATOR_NAME}/config.json`];
33
26
  }
34
27
 
28
+ /** Keys of the removed separate service (1.2.0 / 1.3.0) — ignored with a warning. */
29
+ export const LEGACY_KEYS = ['agents', 'dispatch', 'reportDryRun', 'pollMs', 'stateDir', 'sse', 'logFormat', 'stopTimeoutMs'];
30
+
35
31
  const bad = (msg) => new DevopsMcpError('config_invalid', msg);
36
32
 
37
33
  /**
38
34
  * Normalizes and validates a raw config object (already parsed). Throws config_invalid with the reason.
39
- * → { file, server, projects, stateDir, pollMs, leaseMs, maxAttempts, backoffMs, dispatch, report, reportDryRun,
40
- * logFormat, targets, routes, agents, stopTimeoutMs, idleTtlMs }
35
+ * → { file, server, projects, leaseMs, deployPollFallbackMs, maxAttempts, backoffMs, idleTtlMs, report, targets, routes,
36
+ * warnings }
41
37
  */
42
38
  export function normalizeOrchestratorConfig(raw, { file = null, env = process.env, home = homedir() } = {}) {
43
39
  if (!raw || typeof raw !== 'object') throw bad('the config must be a JSON object');
44
- const base = file ? dirname(file) : process.cwd();
45
40
  if ('token' in raw || 'apiKey' in raw || 'tokenFile' in raw) throw bad('the orchestrator config holds no credential: use KONSILIUM_API_KEY or `npx @consilium108/mcp login`');
46
- const dispatch = raw.dispatch ?? 'dry_run';
47
- if (!DISPATCH_MODES.includes(dispatch)) throw bad(`dispatch «${dispatch}» is not available globally (the global dispatch stays ${DISPATCH_MODES.join(', ')}); start agents per slot: agents[].dispatch "live" (mode headless, provider claude) or "handoff" (mode session)`);
41
+ const warnings = LEGACY_KEYS.filter((k) => k in raw).map((k) => `«${k}» is ignored: the orchestrator runs inside the DevOps MCP and hands jobs to the session's own subagents (jobs_claim); nothing is started or dispatched by it`);
48
42
  const leaseMs = Number(raw.leaseMs) || 30 * 60_000;
49
43
  const targets = {};
50
44
  for (const [key, t] of Object.entries(raw.targets ?? {})) {
@@ -65,75 +59,27 @@ export function normalizeOrchestratorConfig(raw, { file = null, env = process.en
65
59
  if (!JOB_KINDS.includes(kind)) throw bad(`routes[${i}].kind «${kind}»: one of ${JOB_KINDS.join(', ')}`);
66
60
  return { event, projectId, target: r.target, kind, priority: Number(r.priority) || 0 };
67
61
  });
68
- const ids = new Set();
69
- const agents = (raw.agents ?? []).map((a, i) => {
70
- const id = String(a?.id ?? '');
71
- if (!/^[a-z0-9][a-z0-9._-]{0,59}$/i.test(id)) throw bad(`agents[${i}].id: letters, digits, . _ - only`);
72
- if (ids.has(id)) throw bad(`agents: id «${id}» twice`);
73
- ids.add(id);
74
- const mode = a.mode ?? 'session';
75
- if (!AGENT_MODES.includes(mode)) throw bad(`agents[${i}].mode: ${AGENT_MODES.join(' | ')}`);
76
- if (!a.workspace) throw bad(`agents[${i}].workspace (the repository the agent works in) is required`);
77
- const projects = [].concat(a.projects ?? []).map(Number).filter((n) => Number.isInteger(n) && n > 0);
78
- if (!projects.length) throw bad(`agents[${i}].projects: at least one Konsilium project id`);
79
- const provider = String(a.provider ?? 'claude');
80
- // stage 3: starting an agent is per slot and narrow — never a second process in a person's session
81
- const slotDispatch = a.dispatch ?? 'dry_run';
82
- if (!SLOT_DISPATCH.includes(slotDispatch)) throw bad(`agents[${i}].dispatch: ${SLOT_DISPATCH.join(' | ')}`);
83
- if (slotDispatch === 'live' && (mode !== 'headless' || provider !== 'claude')) throw bad(`agents[${i}].dispatch "live" is allowed only for mode "headless" with provider "claude" (a session slot gets "handoff")`);
84
- if (slotDispatch === 'handoff' && mode !== 'session') throw bad(`agents[${i}].dispatch "handoff" is for mode "session" slots (a headless claude slot may be "live")`);
85
- const timeoutMs = a.timeout_ms == null ? leaseMs : Number(a.timeout_ms);
86
- if (!Number.isFinite(timeoutMs) || timeoutMs < 1000 || timeoutMs > leaseMs) throw bad(`agents[${i}].timeout_ms: 1000 … leaseMs (${leaseMs}) — a live run never outlives its lease`);
87
- const claudeBin = a.claude_bin == null ? 'claude' : String(a.claude_bin);
88
- if (!/(^|\/)claude$/.test(claudeBin)) throw bad(`agents[${i}].claude_bin: a path to the \`claude\` binary (…/claude)`);
89
- const envPass = [].concat(a.env_pass ?? []).map(String);
90
- for (const n of envPass) if (!/^[A-Z_][A-Z0-9_]{0,63}$/.test(n)) throw bad(`agents[${i}].env_pass: variable names only (${n})`);
91
- const handoffAgent = a.handoff_agent == null ? null : String(a.handoff_agent);
92
- if (handoffAgent && !/^[a-z0-9][a-z0-9._-]{1,39}$/i.test(handoffAgent)) throw bad(`agents[${i}].handoff_agent: an agent id from list_agents (e.g. claude-1a2b3c) or a provider`);
93
- return {
94
- id,
95
- provider,
96
- mode,
97
- dispatch: slotDispatch,
98
- timeoutMs,
99
- claudeBin: claudeBin.startsWith('~/') || claudeBin.includes('/') ? resolve(base, expandHome(claudeBin, home)) : claudeBin,
100
- envPass,
101
- handoffAgent,
102
- workspace: resolve(base, expandHome(String(a.workspace), home)),
103
- projects,
104
- capabilities: [].concat(a.capabilities ?? JOB_KINDS).map(String),
105
- sessionId: a.session_id ? String(a.session_id).slice(0, 120) : null,
106
- };
107
- });
108
62
  const projects = [...new Set([...(raw.projects ?? []).map(Number), ...routes.map((r) => r.projectId)])].filter((n) => Number.isInteger(n) && n > 0);
109
63
  if (!projects.length) throw bad('projects: at least one project id to listen to (or a route)');
110
- const stateDir = resolve(base, expandHome(env.CONSILIUM_ORCHESTRATOR_STATE_DIR ?? raw.stateDir ?? join(env.XDG_STATE_HOME || join(home, '.local', 'state'), ORCHESTRATOR_NAME), home));
111
64
  return {
112
65
  file,
113
66
  server: String(env.KONSILIUM_API_URL ?? raw.server ?? DEFAULT_SERVER).replace(/\/+$/, ''),
114
67
  projects,
115
- stateDir,
116
- pollMs: Number(raw.pollMs) || 5_000,
117
68
  leaseMs,
118
69
  deployPollFallbackMs: Number(raw.deployPollFallbackMs) || 5 * 60_000,
119
70
  maxAttempts: Number(raw.maxAttempts) || 3,
120
71
  backoffMs: Number(raw.backoffMs) || 60_000,
121
72
  idleTtlMs: Number(raw.idleTtlMs) || 6 * 3600_000,
122
- stopTimeoutMs: Number(raw.stopTimeoutMs) || 30_000,
123
- dispatch,
124
73
  report: raw.report === 'off' ? 'off' : 'agent-events',
125
- reportDryRun: raw.reportDryRun === true,
126
- sse: raw.sse !== false,
127
- logFormat: env.CONSILIUM_ORCHESTRATOR_LOG_FORMAT ?? raw.logFormat ?? 'json',
128
74
  targets,
129
75
  routes,
130
- agents,
76
+ warnings,
131
77
  };
132
78
  }
133
79
 
134
80
  export function loadOrchestratorConfig({ file = null, env = process.env, home = homedir() } = {}) {
135
81
  const f = file ?? orchestratorConfigCandidates(env, home).find((p) => existsSync(p)) ?? null;
136
- if (!f || !existsSync(f)) throw new DevopsMcpError('config_missing', `no orchestrator config (looked at ${orchestratorConfigCandidates(env, home).join(', ')}). Create it: ${ORCHESTRATOR_NAME} config --print > <file>`);
82
+ if (!f || !existsSync(f)) throw new DevopsMcpError('config_missing', `no orchestrator config (looked at ${orchestratorConfigCandidates(env, home).join(', ')}). see README «Orchestrator inside the MCP»`);
137
83
  let raw;
138
84
  try {
139
85
  raw = JSON.parse(readFileSync(f, 'utf8'));
@@ -143,22 +89,27 @@ export function loadOrchestratorConfig({ file = null, env = process.env, home =
143
89
  return normalizeOrchestratorConfig(raw, { file: f, env, home });
144
90
  }
145
91
 
146
- /** An example config (printed by `consilium-devops-orchestrator config --print`). No secret inside. */
147
- export function exampleOrchestratorConfig({ repoDir = '/path/to/consilium.nativemind.net', projectId = 1, target = 'konsilium-prod' } = {}) {
92
+ /** An example config (README «Orchestrator inside the MCP»). No secret inside. */
93
+ export function exampleOrchestratorConfig({ projectId = 1, target = 'konsilium-prod' } = {}) {
148
94
  return {
149
95
  server: DEFAULT_SERVER,
150
96
  projects: [projectId],
151
- stateDir: `~/.local/state/${ORCHESTRATOR_NAME}`,
152
- dispatch: 'dry_run',
153
97
  report: 'agent-events',
154
- pollMs: 5000,
155
98
  leaseMs: 1800000,
156
99
  maxAttempts: 3,
157
100
  backoffMs: 60000,
158
101
  targets: { [target]: { project_id: projectId, environment: 'production', approval: 'human', title: 'Консилиум (прод)' } },
159
102
  routes: [{ event: 'agent.deploy_required', project_id: projectId, target, kind: 'deploy_check' }],
160
- // dispatch per slot: "dry_run" (default) · "handoff" (a session slot: create_handoff into it) · "live" (mode
161
- // "headless" + provider "claude" only: `claude -p`, timeout_ms ≤ leaseMs)
162
- agents: [{ id: 'claude-main', provider: 'claude', mode: 'session', dispatch: 'dry_run', workspace: repoDir, projects: [projectId], capabilities: ['deploy_check'] }],
163
103
  };
164
104
  }
105
+
106
+ /** The config file of the MCP start, or { config: null } when there is none (no DevOps jobs; never an MCP failure). */
107
+ export function findOrchestratorConfig({ file = null, env = process.env, home = homedir() } = {}) {
108
+ const f = file ?? orchestratorConfigCandidates(env, home).find((p) => existsSync(p)) ?? null;
109
+ if (!f) return { config: null, error: null, looked: orchestratorConfigCandidates(env, home) };
110
+ try {
111
+ return { config: loadOrchestratorConfig({ file: f, env, home }), error: null };
112
+ } catch (e) {
113
+ return { config: null, error: { code: e.code ?? 'config_invalid', message: e.message, file: f } };
114
+ }
115
+ }