@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.
@@ -0,0 +1,113 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops): the systemd unit
2
+ // and the install steps as TEXT. Nothing here installs, starts or writes anything: `consilium-devops-runner install --print`
3
+ // and the MCP tool `runner_setup` only print what a person runs on the host.
4
+ import { homedir, userInfo } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { DEFAULT_PATH, defaultPath } from './config.js';
7
+
8
+ export const SERVICE_NAME = 'consilium-devops-runner';
9
+
10
+ /**
11
+ * @param {object} o
12
+ * @param {'system'|'user'} [o.mode] system service with User= (recommended: starts at boot without a login) or a user service
13
+ * @param {string} [o.user] the account that runs it (must be in the docker group and own the repository)
14
+ * @param {string} [o.node] absolute path of node
15
+ * @param {string} [o.bin] absolute path of bin/consilium-devops-runner.js
16
+ * @param {string} [o.configPath]
17
+ * @param {string} [o.repoDir] working directory (the Konsilium checkout)
18
+ * @param {string} [o.path] PATH of the service
19
+ */
20
+ export function unitText({ mode = 'system', user = safeUser(), node = process.execPath, bin = '/usr/local/lib/node_modules/@consilium108/mcp-module-devops/bin/consilium-devops-runner.js', configPath = null, repoDir = null, path = DEFAULT_PATH } = {}) {
21
+ const home = mode === 'system' ? `/home/${user}` : '%h';
22
+ const cfg = configPath ?? `${home}/.config/${SERVICE_NAME}/config.json`;
23
+ return [
24
+ '[Unit]',
25
+ 'Description=Konsilium DevOps deploy runner (runs deploys a person approved in Konsilium)',
26
+ 'Documentation=https://www.npmjs.com/package/@consilium108/mcp-module-devops',
27
+ 'After=network-online.target docker.service',
28
+ 'Wants=network-online.target',
29
+ ...(repoDir ? [`RequiresMountsFor=${repoDir}`] : []),
30
+ '',
31
+ '[Service]',
32
+ 'Type=simple',
33
+ ...(mode === 'system' ? [`User=${user}`, `Group=${user}`, 'SupplementaryGroups=docker'] : []),
34
+ ...(repoDir ? [`WorkingDirectory=${repoDir}`] : []),
35
+ `Environment=CONSILIUM_DEVOPS_RUNNER_CONFIG=${cfg}`,
36
+ `Environment=PATH=${path}`,
37
+ `ExecStart=${node} ${bin} run`,
38
+ 'Restart=on-failure',
39
+ 'RestartSec=15',
40
+ // SIGTERM only to the runner: it lets the running deploy finish (docker compose must not be killed mid-way)
41
+ 'KillMode=mixed',
42
+ 'KillSignal=SIGTERM',
43
+ 'TimeoutStopSec=1500',
44
+ 'NoNewPrivileges=true',
45
+ 'StandardOutput=journal',
46
+ 'StandardError=journal',
47
+ '',
48
+ '[Install]',
49
+ `WantedBy=${mode === 'system' ? 'multi-user.target' : 'default.target'}`,
50
+ '',
51
+ ].join('\n');
52
+ }
53
+
54
+ function safeUser() {
55
+ try {
56
+ return userInfo().username;
57
+ } catch {
58
+ return 'konsilium';
59
+ }
60
+ }
61
+
62
+ /** The whole procedure for a person, as text (Russian comments, commands as is). */
63
+ export function installSteps({ mode = 'system', target = 'konsilium-prod', title = 'Консилиум (прод)', repoDir = '/path/to/consilium.nativemind.net', user = safeUser(), node = process.execPath, bin, path = null } = {}) {
64
+ const home = mode === 'system' ? `/home/${user}` : homedir();
65
+ path = path ?? defaultPath(home);
66
+ const dir = join(home, '.config', SERVICE_NAME);
67
+ const binPath = bin ?? `${repoDir}/packages/mcp-module-devops/bin/consilium-devops-runner.js`;
68
+ const unitPath = mode === 'system' ? `/etc/systemd/system/${SERVICE_NAME}.service` : `~/.config/systemd/user/${SERVICE_NAME}.service`;
69
+ const sc = mode === 'system' ? 'sudo systemctl' : 'systemctl --user';
70
+ const jc = mode === 'system' ? `journalctl -u ${SERVICE_NAME}` : `journalctl --user -u ${SERVICE_NAME}`;
71
+ const unit = unitText({ mode, user, node, bin: binPath, configPath: `${dir}/config.json`, repoDir, path });
72
+ const R = `${node} ${binPath}`;
73
+ return `# Runner выкаток Консилиума — установка (делает человек; эта команда ничего не устанавливает)
74
+ # Runner — отдельная служба, не процесс MCP. Выполняет только запросы, которые человек одобрил (✅ в боте).
75
+
76
+ # 1. Токен цели (один раз, владелец проекта, в личке бота):
77
+ # /deploytarget ${target} ${title}
78
+ # Бот покажет kdr_… один раз. Если цель «${target}» уже есть (бот ответит «Такая цель уже есть»), возьмите её
79
+ # прежний токен или создайте цель с новым ключом (например ${target}-linux) и укажите этот ключ в targets ниже.
80
+ # Токен — только в файл token (шаг 2), не в чат, не в git.
81
+
82
+ # 2. Конфиг вне репозитория (права 600):
83
+ install -d -m 700 ${dir}
84
+ ${R} config --print --repo ${repoDir} --target ${target} > ${dir}/config.json
85
+ chmod 600 ${dir}/config.json
86
+ ( umask 077; read -rsp 'kdr token: ' T; echo; printf '%s\\n' "$T" > ${dir}/token )
87
+ # Проверьте в config.json: composeFiles / composeProfiles (на этом сервере есть docker-compose.override.yml и
88
+ # профиль ai — если выкатываете с -f …ai.yml, перечислите файлы), tests, appUrl/mcpUrl.
89
+ # Сторож (watch): токен Telegram — только в СВОЙ файл ${dir}/runner.env (TELEGRAM_BOT_TOKEN=…, chmod 600)
90
+ # и chatIds; .env ядра runner не читает. Без токена сторож пишет только в журнал.
91
+
92
+ # 3. Проверка (ничего не меняет; токен не печатается):
93
+ ${R} doctor
94
+ ${R} doctor --heartbeat # один heartbeat: цель станет «на связи» в Консилиуме
95
+
96
+ # 4. Служба systemd (${mode}):
97
+ ${mode === 'system' ? `sudo tee ${unitPath} >/dev/null <<'UNIT'` : `mkdir -p ~/.config/systemd/user && tee ${unitPath} >/dev/null <<'UNIT'`}
98
+ ${unit}UNIT
99
+ ${sc} daemon-reload
100
+ ${sc} enable --now ${SERVICE_NAME}
101
+ ${mode === 'user' ? `sudo loginctl enable-linger ${user} # чтобы служба жила без входа в систему\n` : ''}${sc} status ${SERVICE_NAME}
102
+ ${jc} -f # журнал (JSON по строке)
103
+
104
+ # 5. Пробная выкатка: ИИ — MCP request_deploy (target ${target}), человек — /deploy в боте → «✅» в боте →
105
+ # runner: тесты → сборка web → бэкап БД → :prev → up -d --build app mcp → healthy → проверки; итог — в бот.
106
+ # Статус runner: MCP runner_status (на связи / нет, текущая выкатка).
107
+
108
+ # Остановить: ${sc} stop ${SERVICE_NAME} (ждёт конца текущей выкатки; повторный stop — прерывает, откат всё равно выполняется)
109
+ # Убрать: ${sc} disable --now ${SERVICE_NAME} && ${mode === 'system' ? 'sudo ' : ''}rm ${unitPath} && ${sc} daemon-reload
110
+ # Откат выкатки: кнопка «↩ Откатить» в боте; вручную — docker tag konsilium-app:prev konsilium-app:latest (и mcp),
111
+ # docker compose up -d --no-build app mcp.
112
+ `;
113
+ }
@@ -0,0 +1,33 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops): structured logs.
2
+ // One JSON object per line on stdout (journald keeps it as is) or plain text. Secrets are never passed here: callers log
3
+ // paths, ids and codes only; `redact` is a last safety net for anything that looks like a runner or bot token.
4
+
5
+ const TOKENISH = /\b(kdr_[A-Za-z0-9_-]{6})[A-Za-z0-9_-]*|\b(\d{6,12}:)[A-Za-z0-9_-]{30,}/g;
6
+
7
+ /** Masks runner tokens (kdr_…) and Telegram bot tokens (123:ABC…) in a string. */
8
+ export function redact(s) {
9
+ return String(s).replace(TOKENISH, (_m, kdr, bot) => (kdr ? `${kdr}…` : `${bot}…`));
10
+ }
11
+
12
+ /**
13
+ * @param {{ format?: 'json'|'text', out?: { write: (s: string) => void }, err?: { write: (s: string) => void }, now?: () => Date }} [o]
14
+ * @returns {{ info: Function, warn: Function, error: Function, log: Function }}
15
+ */
16
+ export function createLogger({ format = 'json', out = process.stdout, err = process.stderr, now = () => new Date() } = {}) {
17
+ const write = (level, msg, fields = {}) => {
18
+ const ts = now().toISOString();
19
+ const clean = Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, typeof v === 'string' ? redact(v) : v]));
20
+ const line =
21
+ format === 'text'
22
+ ? `${ts} ${level.toUpperCase()} ${redact(msg)}${Object.keys(clean).length ? ` ${JSON.stringify(clean)}` : ''}\n`
23
+ : `${JSON.stringify({ ts, level, msg: redact(msg), ...clean })}\n`;
24
+ (level === 'error' ? err : out).write(line);
25
+ };
26
+ return {
27
+ info: (m, f) => write('info', m, f),
28
+ warn: (m, f) => write('warn', m, f),
29
+ error: (m, f) => write('error', m, f),
30
+ // console-compatible pair for the watchdog (log.log / log.error)
31
+ log: (m) => write('info', m),
32
+ };
33
+ }
@@ -0,0 +1,230 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops): built-in deploy
2
+ // recipes. A target with `"recipe": "konsilium-linux"` gets the steps the lead runs by hand on the Linux prod host
3
+ // (ubuntu24consilium, 2026-11): tests → web build → DB backup → tag :prev → `up -d --build app mcp` → healthy → checks;
4
+ // rollback = :prev → latest, `up -d --no-build`. Everything is configurable in the target; the core never sends commands.
5
+ import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+
8
+ export const RECIPES = ['konsilium-linux'];
9
+
10
+ const KONSILIUM_DEFAULTS = {
11
+ composeFiles: null, // null → plain `docker compose` (compose itself reads docker-compose.yml + docker-compose.override.yml, COMPOSE_FILE from the project .env)
12
+ composeProfiles: [],
13
+ imagePrefix: 'konsilium', // images konsilium-<service>:latest / :prev (compose project «konsilium»)
14
+ services: ['app', 'mcp'],
15
+ tests: { server: true, flutter: true },
16
+ testImage: 'node:22-bookworm',
17
+ flutterAnalyzeArgs: ['analyze', '--no-fatal-infos'],
18
+ flutterTestArgs: ['test'],
19
+ buildWeb: true,
20
+ backup: true,
21
+ preSteps: [],
22
+ appUrl: 'http://127.0.0.1:8090',
23
+ mcpUrl: 'http://127.0.0.1:8091',
24
+ healthyTimeoutMs: 300_000,
25
+ userVersion: true,
26
+ logErrors: true,
27
+ logErrorPattern: '"level":(50|60)\\b|UnhandledPromiseRejection|Uncaught(Exception)?\\b|FATAL',
28
+ stepTimeoutMs: 20 * 60_000,
29
+ };
30
+
31
+ const USER_VERSION_JS =
32
+ "const D=require('better-sqlite3');const d=new D(process.env.DB_PATH||'/data/konsilium.db',{readonly:true,fileMustExist:true});console.log(d.pragma('user_version',{simple:true}));d.close()";
33
+
34
+ /** HTTP check step: `method url` must answer `expect`. */
35
+ export function httpCheck({ method = 'GET', url, expect = 200, headers = {}, body }, { fetchImpl = fetch } = {}) {
36
+ return {
37
+ label: `check ${method} ${url} → ${expect}`,
38
+ run: async () => {
39
+ try {
40
+ const r = await fetchImpl(url, { method, headers, body, signal: AbortSignal.timeout(10_000) });
41
+ return { code: r.status === expect ? 0 : 1, out: `HTTP ${r.status}${r.status === expect ? '' : ` (expected ${expect})`}` };
42
+ } catch (e) {
43
+ return { code: 1, out: `no answer: ${e?.cause?.code ?? e?.message ?? e}` };
44
+ }
45
+ },
46
+ };
47
+ }
48
+
49
+ /** The default checks of the Konsilium prod host (the lead's list). */
50
+ export function konsiliumChecks(o, deps) {
51
+ const json = { 'content-type': 'application/json', accept: 'application/json, text/event-stream' };
52
+ return [
53
+ { method: 'GET', url: `${o.appUrl}/api/health`, expect: 200 },
54
+ { method: 'POST', url: `${o.mcpUrl}/mcp`, expect: 401, headers: json, body: '{}' },
55
+ { method: 'POST', url: `${o.appUrl}/line/webhook`, expect: 401, headers: json, body: '{}' },
56
+ { method: 'POST', url: `${o.appUrl}/max/webhook`, expect: 401, headers: json, body: '{}' },
57
+ ].map((c) => httpCheck(c, deps));
58
+ }
59
+
60
+ /**
61
+ * Expands `{ recipe: 'konsilium-linux', repoDir, … }` into { cwd, preDeploy, deploy, checks, rollback, health, stepTimeoutMs }.
62
+ * A target that already lists `deploy` (the old config) is returned unchanged.
63
+ */
64
+ export function expandTarget(t, { stateDir = null, uid = process.getuid?.() ?? 0, gid = process.getgid?.() ?? 0, fetchImpl } = {}) {
65
+ if (!t?.recipe) return t;
66
+ if (t.recipe !== 'konsilium-linux') throw new Error(`unknown recipe «${t.recipe}» (known: ${RECIPES.join(', ')})`);
67
+ const o = { ...KONSILIUM_DEFAULTS, ...t, tests: t.tests === false ? { server: false, flutter: false } : { ...KONSILIUM_DEFAULTS.tests, ...(t.tests ?? {}) } };
68
+ if (!o.repoDir) throw new Error('target with recipe konsilium-linux needs "repoDir" (the Konsilium checkout on this host)');
69
+ const compose = ['docker', 'compose', ...(o.composeFiles ?? []).flatMap((f) => ['-f', f]), ...(o.composeProfiles ?? []).flatMap((p) => ['--profile', p])];
70
+ const svc = o.services;
71
+ const image = (s) => `${o.imagePrefix}-${s}`;
72
+ const containerOf = async (exec, s) => {
73
+ const r = await exec([...compose, 'ps', '-q', s]);
74
+ return r.code === 0 ? r.out.trim().split('\n')[0] || null : null;
75
+ };
76
+
77
+ const preDeploy = [...(o.preSteps ?? [])];
78
+ if (o.tests.server) {
79
+ preDeploy.push({
80
+ label: `server tests (vitest in ${o.testImage}, a copy of server/ + packages/)`,
81
+ needs: ['docker'],
82
+ timeoutMs: o.testTimeoutMs ?? 30 * 60_000,
83
+ run: async ({ exec }) => {
84
+ if (!stateDir) return { code: 1, out: 'no stateDir for the test copy' };
85
+ const tree = join(stateDir, 'test-tree');
86
+ const cache = join(stateDir, 'npm-cache');
87
+ mkdirSync(cache, { recursive: true });
88
+ for (const part of ['server', 'packages']) {
89
+ const dst = join(tree, part);
90
+ mkdirSync(dst, { recursive: true });
91
+ // keep node_modules between runs (reinstalled only when package-lock.json changes); everything else is fresh
92
+ for (const e of readdirSync(dst)) if (!(part === 'server' && e === 'node_modules')) rmSync(join(dst, e), { recursive: true, force: true });
93
+ const src = join(o.repoDir, part);
94
+ if (!existsSync(src)) continue;
95
+ const skip = (rel) => /(^|\/)node_modules(\/|$)/.test(rel) || /(^|\/)\.env[^/]*$/.test(rel) || (part === 'server' && /^\/data(\/|$)/.test(rel));
96
+ cpSync(src, dst, { recursive: true, filter: (p) => !skip(p.slice(src.length)) });
97
+ }
98
+ const script =
99
+ 'if ! cmp -s package-lock.json node_modules/.runner-lock 2>/dev/null; then rm -rf node_modules && npm ci --no-audit --no-fund --loglevel=error && cp package-lock.json node_modules/.runner-lock; fi; npx vitest run 2>&1 | tail -60; exit ${PIPESTATUS[0]}';
100
+ return exec(['docker', 'run', '--rm', '-u', `${uid}:${gid}`, '-e', 'HOME=/tmp', '-v', `${tree}:/w`, '-v', `${cache}:/tmp/.npm`, '-w', '/w/server', o.testImage, 'bash', '-c', script]);
101
+ },
102
+ });
103
+ }
104
+ if (o.tests.flutter) {
105
+ preDeploy.push({ cmd: ['flutter', ...o.flutterAnalyzeArgs], cwd: 'app/konsilium_flutter', timeoutMs: o.testTimeoutMs ?? 30 * 60_000 });
106
+ preDeploy.push({ cmd: ['flutter', ...o.flutterTestArgs], cwd: 'app/konsilium_flutter', timeoutMs: o.testTimeoutMs ?? 30 * 60_000 });
107
+ }
108
+ if (o.buildWeb) preDeploy.push({ cmd: ['bash', 'scripts/build-web.sh'], timeoutMs: o.buildTimeoutMs ?? 30 * 60_000 });
109
+ if (o.backup) preDeploy.push([...compose, 'exec', '-T', 'app', 'node', '--no-deprecation', 'scripts/db-backup.js']);
110
+
111
+ const userVersion = async (exec) => {
112
+ const r = await exec([...compose, 'exec', '-T', 'app', 'node', '-e', USER_VERSION_JS]);
113
+ const v = Number(String(r.out).trim().split('\n').pop());
114
+ return { r, v: r.code === 0 && Number.isInteger(v) ? v : null };
115
+ };
116
+
117
+ const waitHealthy = (label) => ({
118
+ label,
119
+ needs: ['docker'],
120
+ run: async ({ exec, sleep, signal }) => {
121
+ const until = Date.now() + o.healthyTimeoutMs;
122
+ const status = {};
123
+ for (;;) {
124
+ for (const s of svc) {
125
+ const cid = await containerOf(exec, s);
126
+ if (!cid) {
127
+ status[s] = 'missing';
128
+ continue;
129
+ }
130
+ const r = await exec(['docker', 'inspect', '-f', '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}', cid]);
131
+ status[s] = r.out.trim() || 'unknown';
132
+ }
133
+ const line = svc.map((s) => `${s}=${status[s]}`).join(' ');
134
+ if (svc.every((s) => status[s] === 'healthy' || status[s] === 'running')) return { code: 0, out: line };
135
+ const bad = svc.filter((s) => ['unhealthy', 'exited', 'dead'].includes(status[s]));
136
+ if (bad.length) return { code: 1, out: `${line} — ${bad.join(', ')} failed` };
137
+ if (Date.now() > until || signal?.aborted) return { code: 1, out: `${line} — not healthy in ${Math.round(o.healthyTimeoutMs / 1000)} s` };
138
+ await sleep(3000);
139
+ }
140
+ },
141
+ });
142
+
143
+ const deploy = [
144
+ ...svc.map((s) => ({
145
+ label: `tag the running ${s} image as ${image(s)}:prev`,
146
+ optional: true, // the first deploy has nothing to keep
147
+ needs: ['docker'],
148
+ run: async ({ exec }) => {
149
+ const cid = await containerOf(exec, s);
150
+ if (!cid) return { code: 1, out: `no running ${s} container — nothing to keep as :prev (a rollback will not be possible)` };
151
+ const img = await exec(['docker', 'inspect', '-f', '{{.Image}}', cid]);
152
+ if (img.code !== 0) return img;
153
+ return exec(['docker', 'tag', img.out.trim(), `${image(s)}:prev`]);
154
+ },
155
+ })),
156
+ ...(o.userVersion
157
+ ? [
158
+ {
159
+ label: 'DB user_version before',
160
+ optional: true,
161
+ needs: ['docker', 'node'],
162
+ run: async ({ exec, vars }) => {
163
+ const { r, v } = await userVersion(exec);
164
+ vars.userVersionBefore = v;
165
+ return { code: v == null ? 1 : 0, out: v == null ? r.out : `user_version=${v}` };
166
+ },
167
+ },
168
+ ]
169
+ : []),
170
+ {
171
+ label: `GIT_SHA=$(git rev-parse HEAD) docker compose up -d --build ${svc.join(' ')}`,
172
+ needs: ['git', 'docker'],
173
+ timeoutMs: o.buildTimeoutMs ?? 30 * 60_000,
174
+ run: async ({ exec, vars }) => {
175
+ const sha = await exec(['git', 'rev-parse', 'HEAD']);
176
+ if (sha.code !== 0) return sha;
177
+ vars.upStartedAt = new Date().toISOString();
178
+ const r = await exec([...compose, 'up', '-d', '--build', ...svc], { env: { GIT_SHA: sha.out.trim() } });
179
+ return { code: r.code, out: `GIT_SHA=${sha.out.trim()}\n${r.out}` };
180
+ },
181
+ },
182
+ waitHealthy(`wait until ${svc.join(', ')} are healthy`),
183
+ ];
184
+
185
+ const checks = [...(t.httpChecks ? t.httpChecks.map((c) => httpCheck(c, { fetchImpl })) : konsiliumChecks(o, { fetchImpl }))];
186
+ if (o.userVersion) {
187
+ checks.push({
188
+ label: 'DB user_version after (better-sqlite3 inside the app container)',
189
+ needs: ['docker'],
190
+ run: async ({ exec, vars }) => {
191
+ const { r, v } = await userVersion(exec);
192
+ if (v == null || v <= 0) return { code: 1, out: `user_version not read: ${r.out.slice(-500)}` };
193
+ if (vars.userVersionBefore != null && v < vars.userVersionBefore) return { code: 1, out: `user_version went down: ${vars.userVersionBefore} → ${v}` };
194
+ return { code: 0, out: `user_version=${v}${vars.userVersionBefore != null ? ` (before ${vars.userVersionBefore})` : ''}` };
195
+ },
196
+ });
197
+ }
198
+ if (o.logErrors) {
199
+ checks.push({
200
+ label: `no errors in the logs of ${svc.join(', ')} since the deploy`,
201
+ needs: ['docker'],
202
+ run: async ({ exec, vars }) => {
203
+ const r = await exec([...compose, 'logs', '--no-color', ...(vars.upStartedAt ? ['--since', vars.upStartedAt] : ['--tail', '300']), ...svc]);
204
+ if (r.code !== 0) return r;
205
+ const re = new RegExp(o.logErrorPattern, 'i');
206
+ const bad = r.out.split('\n').filter((l) => re.test(l));
207
+ return { code: bad.length ? 1 : 0, out: bad.length ? `${bad.length} error line(s):\n${bad.slice(0, 5).join('\n')}` : 'errors: 0' };
208
+ },
209
+ });
210
+ }
211
+
212
+ const rollback = [
213
+ ...svc.map((s) => ['docker', 'tag', `${image(s)}:prev`, `${image(s)}:latest`]),
214
+ [...compose, 'up', '-d', '--no-build', ...svc],
215
+ waitHealthy(`wait until ${svc.join(', ')} are healthy after the rollback`),
216
+ ];
217
+
218
+ return {
219
+ cwd: o.repoDir,
220
+ stepTimeoutMs: o.stepTimeoutMs,
221
+ path: t.path,
222
+ preDeploy,
223
+ deploy,
224
+ checks,
225
+ rollback,
226
+ health: t.health ?? `${o.appUrl}/api/health`,
227
+ recipe: t.recipe,
228
+ options: { ...o, composeCommand: compose },
229
+ };
230
+ }
@@ -0,0 +1,84 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops): the runner's
2
+ // local state — one deploy at a time (a lock file), an idempotent claim (the current job and the result that has not reached
3
+ // the core yet survive a restart; a job is never run twice) and the full logs of the last jobs.
4
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, writeSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { DevopsMcpError } from '../errors.js';
7
+
8
+ const KEEP_DONE = 50;
9
+ const KEEP_LOGS = 30;
10
+
11
+ const alive = (pid) => {
12
+ try {
13
+ process.kill(pid, 0);
14
+ return true;
15
+ } catch (e) {
16
+ return e.code === 'EPERM';
17
+ }
18
+ };
19
+
20
+ /** A lock file with our pid (O_EXCL); a stale lock of a dead process is taken over. `name`: the orchestrator uses its own. */
21
+ export function acquireLock(dir, name = 'runner.lock') {
22
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
23
+ const file = join(dir, name);
24
+ for (let i = 0; i < 2; i++) {
25
+ try {
26
+ const fd = openSync(file, 'wx', 0o600);
27
+ writeSync(fd, String(process.pid));
28
+ closeSync(fd);
29
+ return { file, release: () => rmSync(file, { force: true }) };
30
+ } catch (e) {
31
+ if (e.code !== 'EEXIST') throw e;
32
+ const pid = Number(readFileSync(file, 'utf8').trim());
33
+ if (pid && pid !== process.pid && alive(pid)) throw new DevopsMcpError('already_running', `another ${name === 'runner.lock' ? 'runner' : 'process'} (pid ${pid}) holds ${file}${name === 'runner.lock' ? ' — one deploy at a time' : ''}`);
34
+ rmSync(file, { force: true });
35
+ }
36
+ }
37
+ throw new DevopsMcpError('already_running', `cannot take ${file}`);
38
+ }
39
+
40
+ /** state.json: { current: { id, kind, target, startedAt } | null, pending: { id, res } | null, done: [{ id, exitCode, health }] } */
41
+ export function createState(dir) {
42
+ mkdirSync(join(dir, 'logs'), { recursive: true, mode: 0o700 });
43
+ const file = join(dir, 'state.json');
44
+ let s = { current: null, pending: null, done: [] };
45
+ if (existsSync(file)) {
46
+ try {
47
+ s = { ...s, ...JSON.parse(readFileSync(file, 'utf8')) };
48
+ } catch {
49
+ /* a broken file: start clean (the core keeps the truth) */
50
+ }
51
+ }
52
+ const save = () => {
53
+ const tmp = `${file}.tmp`;
54
+ writeFileSync(tmp, JSON.stringify(s, null, 2), { mode: 0o600 });
55
+ renameSync(tmp, file);
56
+ };
57
+ return {
58
+ dir,
59
+ get: () => JSON.parse(JSON.stringify(s)),
60
+ begin(req) {
61
+ s.current = { id: req.id, kind: req.kind, target: req.target, startedAt: new Date().toISOString() };
62
+ save();
63
+ },
64
+ /** The job finished locally: keep its result until the core has it. */
65
+ finish(id, res) {
66
+ s.current = null;
67
+ s.pending = { id, res: { exitCode: res.exitCode, logTail: res.logTail, health: res.health } };
68
+ s.done = [{ id, exitCode: res.exitCode, health: res.health }, ...s.done.filter((d) => d.id !== id)].slice(0, KEEP_DONE);
69
+ save();
70
+ },
71
+ reported(id) {
72
+ if (s.pending?.id === id) s.pending = null;
73
+ save();
74
+ },
75
+ isDone: (id) => s.done.some((d) => d.id === id),
76
+ writeLog(id, text) {
77
+ const logs = join(dir, 'logs');
78
+ writeFileSync(join(logs, `D${id}.log`), text, { mode: 0o600 });
79
+ const all = readdirSync(logs).filter((f) => /^D\d+\.log$/.test(f)).sort((a, b) => Number(b.slice(1, -4)) - Number(a.slice(1, -4)));
80
+ for (const f of all.slice(KEEP_LOGS)) rmSync(join(logs, f), { force: true });
81
+ return join(logs, `D${id}.log`);
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,196 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops). Ported from
2
+ // deploy-runner/runner.js (sdd-konsilium-deploy, #140): local steps with execFile (no shell), health, rollback on failure.
3
+ // Added: an explicit PATH and a preflight that names a missing command (the 11.11 «spawn docker ENOENT» under a service
4
+ // manager), built-in steps of recipes ({ run }), a pre-deploy phase that never needs a rollback, post-deploy checks,
5
+ // cancellation (graceful stop) and the full log next to the tail.
6
+ import { execFile } from 'node:child_process';
7
+ import { accessSync, constants, statSync } from 'node:fs';
8
+ import { delimiter, isAbsolute, join, resolve } from 'node:path';
9
+
10
+ export const LOG_MAX = 4096; // the core keeps the last 4096 characters (server/src/domain/deploys.js)
11
+ export const DEFAULT_STEP_TIMEOUT_MS = 15 * 60_000;
12
+ const sleep = (ms, signal) =>
13
+ new Promise((r) => {
14
+ const t = setTimeout(r, ms);
15
+ signal?.addEventListener('abort', () => (clearTimeout(t), r()), { once: true });
16
+ });
17
+
18
+ /** Variables a step's child process must never see (the runner's own secrets). */
19
+ export const SECRET_ENV = ['CONSILIUM_RUNNER_TOKEN', 'CONSILIUM_RUNNER_TELEGRAM_TOKEN'];
20
+
21
+ /** The child environment: the runner's environment with PATH replaced (when given) and the runner's secrets removed. */
22
+ export function childEnv(base = process.env, path = null) {
23
+ const env = { ...base };
24
+ for (const k of SECRET_ENV) delete env[k];
25
+ if (path) env.PATH = path;
26
+ return env;
27
+ }
28
+
29
+ /** `cmd` on `path` (or an absolute / relative path that exists and is executable) → its full path, else null. */
30
+ export function which(cmd, path = process.env.PATH ?? '', cwd = process.cwd()) {
31
+ const ok = (p) => {
32
+ try {
33
+ accessSync(p, constants.X_OK);
34
+ return statSync(p).isFile();
35
+ } catch {
36
+ return false;
37
+ }
38
+ };
39
+ if (cmd.includes('/')) {
40
+ const p = isAbsolute(cmd) ? cmd : resolve(cwd, cmd);
41
+ return ok(p) ? p : null;
42
+ }
43
+ for (const dir of String(path).split(delimiter).filter(Boolean)) {
44
+ const p = join(dir, cmd);
45
+ if (ok(p)) return p;
46
+ }
47
+ return null;
48
+ }
49
+
50
+ const normalize = (step) => (Array.isArray(step) ? { cmd: step } : step);
51
+ const labelOf = (s) => s.label ?? (s.cmd ? s.cmd.join(' ') : 'step');
52
+
53
+ /** Every command a list of steps needs (built-in steps declare theirs in `needs`). */
54
+ export function commandsOf(steps) {
55
+ const out = new Set();
56
+ for (const raw of steps ?? []) {
57
+ const s = normalize(raw);
58
+ if (s.cmd?.[0]) out.add(s.cmd[0]);
59
+ for (const c of s.needs ?? []) out.add(c);
60
+ }
61
+ return [...out];
62
+ }
63
+
64
+ /** Missing commands of a target (preDeploy, deploy, checks, rollback) on `path` → [] when all are there. */
65
+ export function preflight(target, { path = process.env.PATH, cwd } = {}) {
66
+ const all = commandsOf([...(target.preDeploy ?? []), ...(target.deploy ?? []), ...(target.checks ?? []), ...(target.rollback ?? [])]);
67
+ return all.filter((c) => !which(c, path, cwd ?? target.cwd ?? process.cwd()));
68
+ }
69
+
70
+ /** Runs one command → { code, out } (never throws). ENOENT → code 127 with a readable message. */
71
+ export function execCmd(argv, { cwd, timeoutMs = DEFAULT_STEP_TIMEOUT_MS, env = childEnv(), signal } = {}) {
72
+ const [cmd, ...args] = argv;
73
+ return new Promise((res) => {
74
+ execFile(cmd, args, { cwd, timeout: timeoutMs, maxBuffer: 20 * 1024 * 1024, env, signal, killSignal: 'SIGTERM' }, (err, stdout, stderr) => {
75
+ let code = err ? (typeof err.code === 'number' ? err.code : 1) : 0;
76
+ let extra = '';
77
+ if (err?.code === 'ENOENT') {
78
+ code = 127;
79
+ extra = `command_not_found: «${cmd}» is not on PATH (PATH=${env?.PATH ?? ''}). Set "path" in the runner config or install it.`;
80
+ } else if (err?.name === 'AbortError' || err?.code === 'ABORT_ERR') {
81
+ code = 130;
82
+ extra = 'interrupted: the runner is stopping';
83
+ } else if (err?.killed && err?.signal) {
84
+ extra = `killed by ${err.signal} (timeout ${Math.round(timeoutMs / 1000)} s?)`;
85
+ } else if (err && !stdout && !stderr) {
86
+ extra = String(err.message);
87
+ }
88
+ res({ code, out: `${stdout ?? ''}${stderr ?? ''}${extra}` });
89
+ });
90
+ });
91
+ }
92
+
93
+ /**
94
+ * One step → { code, optional, out }. A step is [cmd, ...args], { cmd, cwd?, env?, optional?, timeoutMs?, label? } or a
95
+ * built-in { run: async (ctx) => ({ code, out }), label, optional?, needs? } (recipes).
96
+ */
97
+ export async function runStep(step, { cwd, timeoutMs = DEFAULT_STEP_TIMEOUT_MS, env = childEnv(), signal, vars = {} } = {}) {
98
+ const s = normalize(step);
99
+ const label = labelOf(s);
100
+ if (signal?.aborted) return { code: 130, optional: !!s.optional, out: `$ ${label}\ninterrupted: the runner is stopping` };
101
+ const stepCwd = s.cwd ? resolve(cwd ?? '.', s.cwd) : cwd;
102
+ const stepEnv = s.env ? { ...env, ...s.env } : env;
103
+ const t = s.timeoutMs ?? timeoutMs;
104
+ if (typeof s.run === 'function') {
105
+ const exec = (argv, o = {}) => execCmd(argv, { cwd: o.cwd ? resolve(stepCwd ?? '.', o.cwd) : stepCwd, timeoutMs: o.timeoutMs ?? t, env: o.env ? { ...stepEnv, ...o.env } : stepEnv, signal });
106
+ try {
107
+ const r = await s.run({ exec, cwd: stepCwd, env: stepEnv, signal, vars, timeoutMs: t, sleep: (ms) => sleep(ms, signal) });
108
+ return { code: r?.code ?? 0, optional: !!s.optional, out: `$ ${label}\n${r?.out ?? ''}` };
109
+ } catch (e) {
110
+ return { code: 1, optional: !!s.optional, out: `$ ${label}\n${e?.message ?? e}` };
111
+ }
112
+ }
113
+ const r = await execCmd(s.cmd, { cwd: stepCwd, timeoutMs: t, env: stepEnv, signal });
114
+ return { code: r.code, optional: !!s.optional, out: `$ ${s.cmd.join(' ')}\n${r.out}` };
115
+ }
116
+
117
+ /** Steps in order; a failing non-optional step stops. → { code, log } */
118
+ export async function runSteps(steps, opts) {
119
+ let log = '';
120
+ for (const st of steps ?? []) {
121
+ const r = await runStep(st, opts);
122
+ log += `${r.out}\n[exit ${r.code}${r.optional && r.code ? ', optional — continue' : ''}]\n`;
123
+ opts?.onStep?.(r);
124
+ if (r.code !== 0 && !r.optional) return { code: r.code, log };
125
+ }
126
+ return { code: 0, log };
127
+ }
128
+
129
+ export async function checkHealth(url, { retries = 10, delayMs = 3000, fetchImpl = fetch, signal } = {}) {
130
+ if (!url) return 'skipped';
131
+ for (let i = 0; i < retries; i++) {
132
+ try {
133
+ const r = await fetchImpl(url, { signal: AbortSignal.timeout(5000) });
134
+ if (r.status === 200) return 'ok';
135
+ } catch {
136
+ /* not up yet */
137
+ }
138
+ if (i < retries - 1) await sleep(delayMs, signal);
139
+ if (signal?.aborted) return 'fail';
140
+ }
141
+ return 'fail';
142
+ }
143
+
144
+ /**
145
+ * Execute one claimed request against a target's LOCAL description → { exitCode, logTail, health, log }.
146
+ * target: { cwd, stepTimeoutMs, preDeploy?, deploy, checks?, rollback, health, path? }
147
+ * - preDeploy (tests, web build, backup): a failure stops and changes nothing — no rollback;
148
+ * - deploy, then health, then checks: any failure → rollback steps.
149
+ * health: ok | fail (health URL) | skipped | rolled_back (deploy step or a check failed, rollback ok) | rollback_failed |
150
+ * missing_commands | interrupted — the log says which step failed
151
+ */
152
+ export async function execute(req, target, { healthOpts, env, signal, onStep } = {}) {
153
+ const path = target.path ?? env?.PATH ?? process.env.PATH;
154
+ const cenv = env ?? childEnv(process.env, target.path ?? null);
155
+ const vars = {};
156
+ const opts = { cwd: target.cwd, timeoutMs: target.stepTimeoutMs, env: cenv, signal, vars, onStep };
157
+ const done = (exitCode, log, health) => ({ exitCode, logTail: log.slice(-LOG_MAX), health, log });
158
+
159
+ const missing = preflight(target, { path, cwd: target.cwd });
160
+ if (missing.length) {
161
+ return done(127, `command_not_found: ${missing.map((c) => `«${c}»`).join(', ')} not on PATH (PATH=${path}). Nothing was run. Set "path" in the runner config (consilium-devops-runner doctor shows what is missing).\n`, 'missing_commands');
162
+ }
163
+ if (req.kind === 'rollback') {
164
+ const r = await runSteps(target.rollback, opts);
165
+ const health = r.code === 0 ? await checkHealth(target.health, { ...healthOpts, signal }) : 'skipped';
166
+ return done(r.code, r.log, health);
167
+ }
168
+ let log = '';
169
+ if (target.preDeploy?.length) {
170
+ const p = await runSteps(target.preDeploy, opts);
171
+ log += p.log;
172
+ if (p.code !== 0) return done(p.code, `${log}\n--- pre-deploy step failed: nothing was changed, no rollback ---\n`, signal?.aborted ? 'interrupted' : 'skipped');
173
+ }
174
+ const d = await runSteps(target.deploy, opts);
175
+ log += d.log;
176
+ let code = d.code;
177
+ let health = d.code === 0 ? await checkHealth(target.health, { ...healthOpts, signal }) : 'skipped';
178
+ if (code === 0 && health !== 'fail' && target.checks?.length) {
179
+ const c = await runSteps(target.checks, opts);
180
+ log += `--- checks ---\n${c.log}`;
181
+ if (c.code !== 0) {
182
+ code = c.code;
183
+ health = 'checks_failed'; // becomes rolled_back / rollback_failed below
184
+ }
185
+ }
186
+ if (code !== 0 || health === 'fail') {
187
+ log += '\n--- deploy failed → rollback ---\n';
188
+ // the rollback must run even when the runner is stopping: no signal here
189
+ const rb = await runSteps(target.rollback, { ...opts, signal: undefined });
190
+ log += rb.log;
191
+ if (code === 0) code = 1;
192
+ if (health !== 'fail') health = rb.code === 0 ? 'rolled_back' : 'rollback_failed';
193
+ if (signal?.aborted && health === 'rolled_back') health = 'interrupted';
194
+ }
195
+ return done(code, log, health);
196
+ }