@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,145 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §6): the orchestrator's durable
2
+ // local state — ONE file state.json (tmp + rename after every change, 0600 in a 0700 directory) with
3
+ // cursors per project: the last event of get_events / SSE handled (saved AFTER the event was handled: at-least-once)
4
+ // seen dedup keys of handled events (p<project>:e<event id>) → time; pruned (30 days, at most 5000)
5
+ // jobs the queue: every job with its status, lock key, lease, attempts, sources and history
6
+ // outbox reports to Konsilium not delivered yet (retried with backoff; idempotent on the server)
7
+ // dispatches the last dry-run dispatch plans (what would have been started)
8
+ // The server stays the source of truth for tasks, deploy requests and approvals; this file only coordinates local agents.
9
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+
12
+ const SEEN_MAX = 5000;
13
+ const SEEN_TTL_MS = 30 * 24 * 3600_000;
14
+ const KEEP_FINISHED = 200;
15
+ const KEEP_DISPATCHES = 50;
16
+ const KEEP_HISTORY = 30;
17
+
18
+ export const JOB_STATUSES = ['queued', 'assigned', 'running', 'waiting_for_user', 'blocked', 'succeeded', 'failed', 'cancelled'];
19
+ /** Statuses that hold the lock of a target (one deploy-related job per project + environment + target at a time). */
20
+ export const LOCKING = new Set(['assigned', 'running', 'waiting_for_user']);
21
+ export const FINISHED = new Set(['succeeded', 'failed', 'cancelled', 'blocked']);
22
+
23
+ const empty = () => ({ version: 1, seq: 0, cursors: {}, seen: {}, jobs: [], outbox: [], dispatches: [] });
24
+
25
+ /** @param {{ dir: string, now?: () => number }} o */
26
+ export function createOrchestratorStore({ dir, now = Date.now }) {
27
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
28
+ const file = join(dir, 'state.json');
29
+ let s = empty();
30
+ let broken = false;
31
+ if (existsSync(file)) {
32
+ try {
33
+ s = { ...empty(), ...JSON.parse(readFileSync(file, 'utf8')) };
34
+ } catch {
35
+ broken = true; // a broken file: start clean (events are re-read from the server journal; deploys are on the server)
36
+ }
37
+ }
38
+ const save = () => {
39
+ const tmp = `${file}.${process.pid}.tmp`;
40
+ writeFileSync(tmp, JSON.stringify(s), { mode: 0o600 });
41
+ renameSync(tmp, file);
42
+ };
43
+ const iso = (t = now()) => new Date(t).toISOString();
44
+ const find = (id) => s.jobs.find((j) => j.id === id) ?? null;
45
+
46
+ function prune() {
47
+ const cut = now() - SEEN_TTL_MS;
48
+ let entries = Object.entries(s.seen).filter(([, t]) => t >= cut);
49
+ if (entries.length > SEEN_MAX) entries = entries.sort((a, b) => b[1] - a[1]).slice(0, SEEN_MAX);
50
+ s.seen = Object.fromEntries(entries);
51
+ const done = s.jobs.filter((j) => FINISHED.has(j.status));
52
+ if (done.length > KEEP_FINISHED) {
53
+ const drop = new Set(done.sort((a, b) => Date.parse(a.updatedAt) - Date.parse(b.updatedAt)).slice(0, done.length - KEEP_FINISHED).map((j) => j.id));
54
+ s.jobs = s.jobs.filter((j) => !drop.has(j.id));
55
+ }
56
+ }
57
+
58
+ return {
59
+ file,
60
+ dir,
61
+ recoveredFromBrokenFile: broken,
62
+ snapshot: () => JSON.parse(JSON.stringify(s)),
63
+ cursor: {
64
+ get: (pid) => (s.cursors[pid] ?? null),
65
+ set(pid, c) {
66
+ if (Number.isFinite(c) && c > (s.cursors[pid] ?? 0)) {
67
+ s.cursors[pid] = c;
68
+ save();
69
+ }
70
+ },
71
+ },
72
+ seen: {
73
+ has: (key) => !!s.seen[key],
74
+ add(key) {
75
+ if (s.seen[key]) return false;
76
+ s.seen[key] = now();
77
+ if (Object.keys(s.seen).length > SEEN_MAX * 1.1) prune();
78
+ save();
79
+ return true;
80
+ },
81
+ },
82
+ jobs: {
83
+ all: () => s.jobs.map((j) => ({ ...j })),
84
+ get: (id) => {
85
+ const j = find(id);
86
+ return j ? JSON.parse(JSON.stringify(j)) : null;
87
+ },
88
+ byIdempotency: (key) => s.jobs.find((j) => j.idempotencyKey === key) ?? null,
89
+ create(job) {
90
+ const id = `J${++s.seq}`;
91
+ const at = iso();
92
+ const j = { id, status: 'queued', attempts: 0, nextAttemptAt: 0, lease: null, agentId: null, deployId: null, deployStatus: null, result: null, createdAt: at, updatedAt: at, history: [{ at, status: 'queued', note: job.note ?? 'created' }], ...job };
93
+ delete j.note;
94
+ s.jobs.push(j);
95
+ save();
96
+ return { ...j };
97
+ },
98
+ /** patch + optional status change (recorded in history). */
99
+ update(id, patch = {}, note = null) {
100
+ const j = find(id);
101
+ if (!j) return null;
102
+ const prev = j.status;
103
+ Object.assign(j, patch);
104
+ j.updatedAt = iso();
105
+ if ((patch.status && patch.status !== prev) || note) j.history = [...j.history, { at: j.updatedAt, status: j.status, note: note ?? null }].slice(-KEEP_HISTORY);
106
+ if (FINISHED.has(j.status)) prune();
107
+ save();
108
+ return { ...j };
109
+ },
110
+ addSource(id, src) {
111
+ const j = find(id);
112
+ if (!j) return null;
113
+ if (!j.sources.some((x) => x.project_id === src.project_id && x.event_id === src.event_id)) j.sources = [...j.sources, src].slice(-20);
114
+ j.updatedAt = iso();
115
+ save();
116
+ return { ...j };
117
+ },
118
+ },
119
+ outbox: {
120
+ list: () => s.outbox.map((o) => ({ ...o })),
121
+ add(item) {
122
+ if (s.outbox.some((o) => o.id === item.id)) return false;
123
+ s.outbox.push({ attempts: 0, nextAt: 0, ...item });
124
+ save();
125
+ return true;
126
+ },
127
+ update(id, patch) {
128
+ const o = s.outbox.find((x) => x.id === id);
129
+ if (o) Object.assign(o, patch);
130
+ save();
131
+ },
132
+ remove(id) {
133
+ s.outbox = s.outbox.filter((x) => x.id !== id);
134
+ save();
135
+ },
136
+ },
137
+ dispatches: {
138
+ list: () => s.dispatches.map((d) => ({ ...d })),
139
+ add(d) {
140
+ s.dispatches = [...s.dispatches, d].slice(-KEEP_DISPATCHES);
141
+ save();
142
+ },
143
+ },
144
+ };
145
+ }
@@ -0,0 +1,42 @@
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: the runner's API client — POST /api/deploy/runner/{heartbeat,claim,:id/result} of the core with
3
+ // the target's runner token (kdr_…, never a person's key). The core proxies these to the DevOps module (MODULE_DEVOPS=remote).
4
+ // Errors are the package's coded DevopsMcpError; the token never appears in a message.
5
+ import { DevopsMcpError } from '../errors.js';
6
+
7
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
8
+
9
+ export function createClient({ server, token, fetchImpl = fetch, userAgent = 'consilium-devops-runner', timeoutMs = 30_000 }) {
10
+ const base = String(server ?? '').replace(/\/+$/, '');
11
+ const call = async (path, body) => {
12
+ let r;
13
+ try {
14
+ r = await fetchImpl(`${base}/api/deploy/runner${path}`, {
15
+ method: 'POST',
16
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': userAgent },
17
+ body: JSON.stringify(body ?? {}),
18
+ signal: AbortSignal.timeout(timeoutMs),
19
+ });
20
+ } catch (e) {
21
+ throw new DevopsMcpError('network_unavailable', `${path}: ${e?.cause?.code ?? e?.name ?? 'network error'}`, 0);
22
+ }
23
+ if (!r.ok) {
24
+ const code = r.status === 401 ? 'bad_runner_token' : r.status === 404 ? 'not_found' : r.status === 503 ? 'module_unavailable' : `http_${r.status}`;
25
+ throw new DevopsMcpError(code, `${path}: HTTP ${r.status}${r.status === 401 ? ' (the runner token is wrong or the target was deleted — the owner creates a target with /deploytarget)' : ''}`, r.status);
26
+ }
27
+ return r.json();
28
+ };
29
+ // #140: the app restarts during a deploy (or a rollback) — the result must survive a few 502s, else the request hangs in «running»
30
+ const result = async (id, res, { tries = 20, delayMs = 6000 } = {}) => {
31
+ const body = { exitCode: res.exitCode, logTail: res.logTail, health: res.health ?? null };
32
+ for (let i = 0; ; i++) {
33
+ try {
34
+ return await call(`/${id}/result`, body);
35
+ } catch (e) {
36
+ if (e.status === 404 || e.status === 401 || i >= tries - 1) throw e;
37
+ await sleep(delayMs);
38
+ }
39
+ }
40
+ };
41
+ return { heartbeat: () => call('/heartbeat'), claim: async () => (await call('/claim')).request, result };
42
+ }
@@ -0,0 +1,143 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops): the runner's
2
+ // config. It lives OUTSIDE the repository (it holds the runner token): $CONSILIUM_DEVOPS_RUNNER_CONFIG, else
3
+ // ~/.config/consilium-devops-runner/config.json, else /etc/consilium-devops-runner/config.json; mode 600 (refused if group
4
+ // or others can read it). Environment overrides: CONSILIUM_RUNNER_TOKEN, KONSILIUM_API_URL, CONSILIUM_RUNNER_PATH.
5
+ import { existsSync, readFileSync, statSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
8
+ import { DevopsMcpError } from '../errors.js';
9
+
10
+ export const DEFAULT_SERVER = 'https://konsilium.nativemind.net';
11
+ /** PATH of the steps when the config gives none: a service manager starts with a bare PATH (the 11.11 «spawn npx ENOENT»). */
12
+ export const DEFAULT_PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
13
+
14
+ export function defaultPath(home = homedir()) {
15
+ const flutter = join(home, 'development', 'flutter', 'bin'); // where the Linux prod keeps Flutter (scripts/build-web.sh)
16
+ return existsSync(flutter) ? `${DEFAULT_PATH}:${flutter}` : DEFAULT_PATH;
17
+ }
18
+
19
+ export function configCandidates(env = process.env, home = homedir()) {
20
+ if (env.CONSILIUM_DEVOPS_RUNNER_CONFIG) return [env.CONSILIUM_DEVOPS_RUNNER_CONFIG];
21
+ const xdg = env.XDG_CONFIG_HOME || join(home, '.config');
22
+ return [join(xdg, 'consilium-devops-runner', 'config.json'), '/etc/consilium-devops-runner/config.json'];
23
+ }
24
+
25
+ export function findConfig(env = process.env, home = homedir()) {
26
+ const c = configCandidates(env, home);
27
+ return c.find((p) => existsSync(p)) ?? null;
28
+ }
29
+
30
+ /** null when only the owner can read it; else a coded error with the fix. */
31
+ export function permsProblem(file) {
32
+ const mode = statSync(file).mode & 0o777;
33
+ if (mode & 0o077) return new DevopsMcpError('config_perms', `${file} is readable by group/others (mode ${mode.toString(8)}); it holds the runner token — run: chmod 600 ${file}`);
34
+ return null;
35
+ }
36
+
37
+ const expandHome = (p, home) => (p && p.startsWith('~/') ? join(home, p.slice(2)) : p);
38
+
39
+ /**
40
+ * Reads and normalizes the config. → { file, server, token, tokenSource, pollMs, path, stateDir, logFormat, targets, watch, stopTimeoutMs }
41
+ * The token value is returned for the client only — never log it (doctor prints `tokenSource` and a masked shape).
42
+ */
43
+ export function loadConfig({ file = null, env = process.env, home = homedir(), checkPerms = true, strictToken = true } = {}) {
44
+ const f = file ?? findConfig(env, home);
45
+ if (!f || !existsSync(f)) {
46
+ throw new DevopsMcpError('config_missing', `no runner config (looked at ${configCandidates(env, home).join(', ')}). Create it: consilium-devops-runner config --print > <file>; chmod 600 <file>`);
47
+ }
48
+ if (checkPerms) {
49
+ const p = permsProblem(f);
50
+ if (p) throw p;
51
+ }
52
+ let raw;
53
+ try {
54
+ raw = JSON.parse(readFileSync(f, 'utf8'));
55
+ } catch (e) {
56
+ throw new DevopsMcpError('config_invalid', `${f}: not valid JSON (${e.message})`);
57
+ }
58
+ const base = dirname(f);
59
+ let token = null;
60
+ let tokenSource = null;
61
+ if (env.CONSILIUM_RUNNER_TOKEN) {
62
+ token = env.CONSILIUM_RUNNER_TOKEN.trim();
63
+ tokenSource = 'env CONSILIUM_RUNNER_TOKEN';
64
+ } else if (raw.tokenFile) {
65
+ const tf = resolve(base, expandHome(raw.tokenFile, home));
66
+ if (!existsSync(tf)) {
67
+ if (strictToken) throw new DevopsMcpError('token_missing', `tokenFile ${tf} does not exist`);
68
+ tokenSource = `tokenFile ${tf} (missing)`;
69
+ } else {
70
+ if (checkPerms) {
71
+ const p = permsProblem(tf);
72
+ if (p) throw p;
73
+ }
74
+ token = readFileSync(tf, 'utf8').trim();
75
+ tokenSource = `tokenFile ${tf}`;
76
+ }
77
+ } else if (raw.token && /^kdr_/.test(raw.token)) {
78
+ token = String(raw.token).trim();
79
+ tokenSource = `config ${f}`;
80
+ }
81
+ const stateDir = resolve(base, expandHome(env.CONSILIUM_RUNNER_STATE_DIR ?? raw.stateDir ?? join(env.XDG_STATE_HOME || join(home, '.local', 'state'), 'consilium-devops-runner'), home));
82
+ const targets = Object.fromEntries(
83
+ Object.entries(raw.targets ?? {}).map(([k, t]) => {
84
+ const repoDir = t.repoDir ? expandHome(t.repoDir, home) : undefined;
85
+ const cwd = t.cwd ? expandHome(t.cwd, home) : undefined;
86
+ return [k, { ...t, ...(repoDir ? { repoDir: isAbsolute(repoDir) ? repoDir : resolve(base, repoDir) } : {}), ...(cwd ? { cwd } : {}) }];
87
+ }),
88
+ );
89
+ return {
90
+ file: f,
91
+ server: (env.KONSILIUM_API_URL ?? raw.server ?? DEFAULT_SERVER).replace(/\/+$/, ''),
92
+ token,
93
+ tokenSource,
94
+ pollMs: Number(raw.pollMs) || 10_000,
95
+ path: env.CONSILIUM_RUNNER_PATH ?? raw.path ?? defaultPath(home),
96
+ stateDir,
97
+ logFormat: env.CONSILIUM_RUNNER_LOG_FORMAT ?? raw.logFormat ?? 'json',
98
+ stopTimeoutMs: Number(raw.stopTimeoutMs) || 20 * 60_000,
99
+ targets,
100
+ watch: raw.watch ? { ...raw.watch, ...(raw.watch.envFile ? { envFile: resolve(base, expandHome(raw.watch.envFile, home)) } : {}) } : null,
101
+ };
102
+ }
103
+
104
+ /** Token shape for people: «kdr_…, 36 chars» — never the value. */
105
+ export function maskToken(t) {
106
+ if (!t) return 'missing';
107
+ return `${/^kdr_[A-Za-z0-9_-]{20,}$/.test(t) ? 'kdr_…' : 'unexpected format'}, ${t.length} chars`;
108
+ }
109
+
110
+ /** An example config for this host (printed by `consilium-devops-runner config --print`). No secret inside. */
111
+ export function exampleConfig({ repoDir = '/path/to/consilium.nativemind.net', target = 'konsilium-prod', home = homedir(), server = DEFAULT_SERVER } = {}) {
112
+ return {
113
+ server,
114
+ tokenFile: '~/.config/consilium-devops-runner/token',
115
+ pollMs: 10000,
116
+ path: defaultPath(home),
117
+ stateDir: '~/.local/state/consilium-devops-runner',
118
+ logFormat: 'json',
119
+ targets: {
120
+ [target]: {
121
+ recipe: 'konsilium-linux',
122
+ repoDir,
123
+ composeFiles: null,
124
+ composeProfiles: [],
125
+ services: ['app', 'mcp'],
126
+ tests: { server: true, flutter: true },
127
+ buildWeb: true,
128
+ backup: true,
129
+ appUrl: 'http://127.0.0.1:8090',
130
+ mcpUrl: 'http://127.0.0.1:8091',
131
+ },
132
+ },
133
+ watch: {
134
+ intervalMs: 60000,
135
+ diskPath: '/',
136
+ minFreeGb: 30,
137
+ health: 'http://127.0.0.1:8090/api/health',
138
+ failAfter: 3,
139
+ chatIds: [],
140
+ envFile: '~/.config/consilium-devops-runner/runner.env',
141
+ },
142
+ };
143
+ }
@@ -0,0 +1,162 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops): the long-running
2
+ // runner service. It is NOT part of the MCP process: `consilium-devops-runner run` under systemd. Loop: heartbeat → claim
3
+ // (only requests a PERSON approved, ✅ in the bot) → the steps of THIS host's config → result with the log tail.
4
+ // One deploy at a time (lock file + a sequential loop), heartbeats continue while a job runs, an idempotent claim (state.json),
5
+ // graceful stop (SIGTERM waits for the job; the second signal or stopTimeoutMs interrupts it and the rollback still runs).
6
+ import { childEnv, execute } from './steps.js';
7
+ import { expandTarget } from './recipes.js';
8
+ import { createWatchdog } from './watchdog.js';
9
+
10
+ const sleep = (ms, signal) =>
11
+ new Promise((r) => {
12
+ const t = setTimeout(r, ms);
13
+ signal?.addEventListener('abort', () => (clearTimeout(t), r()), { once: true });
14
+ });
15
+
16
+ /** The local description of a claimed target key (recipe expanded) or null. */
17
+ export function resolveTarget(config, key, deps = {}) {
18
+ const t = config.targets?.[key];
19
+ if (!t) return null;
20
+ return expandTarget({ path: config.path, ...t }, { stateDir: config.stateDir, ...deps });
21
+ }
22
+
23
+ /**
24
+ * One poll tick: (resend a pending result) → heartbeat → claim → run → report.
25
+ * Compatible with the old deploy-runner `tick(config, client)`; `deps.state` adds the idempotent claim.
26
+ */
27
+ export async function tick(config, client, { state = null, log = null, signal, env, healthOpts, onRunning, recipeDeps } = {}) {
28
+ const pending = state?.get().pending;
29
+ if (pending) {
30
+ await client.result(pending.id, pending.res);
31
+ state.reported(pending.id);
32
+ log?.info('result delivered after a retry', { deploy_id: pending.id });
33
+ }
34
+ await client.heartbeat();
35
+ const req = await client.claim();
36
+ if (!req) return null;
37
+ if (state?.isDone(req.id)) {
38
+ // the core gave us a job we already ran (a lost answer): never run it twice
39
+ const prev = state.get().done.find((d) => d.id === req.id);
40
+ log?.warn('claimed a job that already ran here — not running it again', { deploy_id: req.id });
41
+ const res = { exitCode: prev?.exitCode ?? 1, logTail: 'consilium-devops-runner: this request already ran on this host; the result is sent again, the steps are not repeated.', health: prev?.health ?? null };
42
+ await client.result(req.id, res);
43
+ return { id: req.id, ...res, repeated: true };
44
+ }
45
+ log?.info('claimed', { deploy_id: req.id, kind: req.kind, target: req.target });
46
+ state?.begin(req);
47
+ let target = null;
48
+ let res;
49
+ try {
50
+ target = resolveTarget(config, req.target, recipeDeps);
51
+ } catch (e) {
52
+ res = { exitCode: 1, logTail: `consilium-devops-runner: target «${req.target}»: ${e.message}`, health: 'skipped' };
53
+ }
54
+ if (!res) {
55
+ const stop = onRunning?.(req);
56
+ try {
57
+ res = target
58
+ ? await execute(req, target, { env: env ?? childEnv(process.env, target.path ?? config.path ?? null), signal, healthOpts, onStep: (r) => log?.info('step', { deploy_id: req.id, exit: r.code, optional: r.optional, step: r.out.split('\n')[0].slice(2, 200) }) })
59
+ : { exitCode: 1, logTail: `Цель «${req.target}» не описана в локальном config.json runner'а`, health: 'skipped' };
60
+ } finally {
61
+ stop?.();
62
+ }
63
+ }
64
+ if (state && res.log) {
65
+ const file = state.writeLog(req.id, res.log);
66
+ log?.info('full log saved', { deploy_id: req.id, file });
67
+ }
68
+ const out = { exitCode: res.exitCode, logTail: res.logTail, health: res.health };
69
+ state?.finish(req.id, out);
70
+ log?.[out.exitCode === 0 ? 'info' : 'warn']('finished', { deploy_id: req.id, exit: out.exitCode, health: out.health });
71
+ await client.result(req.id, out);
72
+ state?.reported(req.id);
73
+ return { id: req.id, ...out };
74
+ }
75
+
76
+ /**
77
+ * The service. deps: { client, state, log, lock, watchdogDeps, env, healthOpts }
78
+ * → { start(): Promise<void> (resolves when stopped), stop(reason), running(): job|null }
79
+ */
80
+ export function createRunner(config, { client, state, log, lock = null, watchdogDeps = {}, env, healthOpts, recipeDeps } = {}) {
81
+ let stopping = false;
82
+ const wake = new AbortController(); // ends the poll sleep at stop
83
+ const kill = new AbortController(); // interrupts the running job
84
+ let job = null;
85
+ let loopDone = null;
86
+ let watchTimer = null;
87
+
88
+ async function recover() {
89
+ const s = state?.get();
90
+ if (s?.current && s.current.id !== s.pending?.id) {
91
+ // stopped (or crashed) in the middle of a job: its outcome is unknown — report it, never run it again
92
+ const res = { exitCode: 1, logTail: `consilium-devops-runner: the runner stopped during this ${s.current.kind ?? 'job'} (started ${s.current.startedAt}); the result is unknown — check the host by hand (docker compose ps) and roll back with the button if needed.`, health: 'interrupted' };
93
+ state.finish(s.current.id, res);
94
+ log?.warn('a job was interrupted by the previous stop; reporting it as failed', { deploy_id: s.current.id });
95
+ }
96
+ }
97
+
98
+ async function loop() {
99
+ while (!stopping) {
100
+ try {
101
+ const done = await tick(config, client, {
102
+ state,
103
+ log,
104
+ signal: kill.signal,
105
+ env,
106
+ healthOpts,
107
+ recipeDeps,
108
+ onRunning: (req) => {
109
+ job = { ...req, startedAt: new Date().toISOString() };
110
+ const hb = setInterval(() => client.heartbeat().catch((e) => log?.warn('heartbeat during the job failed', { code: e.code ?? 'error' })), config.pollMs ?? 10_000);
111
+ return () => {
112
+ clearInterval(hb);
113
+ job = null;
114
+ };
115
+ },
116
+ });
117
+ if (done?.repeated) log?.info('repeated result sent', { deploy_id: done.id });
118
+ } catch (e) {
119
+ log?.error('tick failed', { code: e.code ?? 'error', error: e.message });
120
+ }
121
+ if (!stopping) await sleep(config.pollMs ?? 10_000, wake.signal);
122
+ }
123
+ }
124
+
125
+ return {
126
+ running: () => job,
127
+ async start() {
128
+ log?.info('runner started', { server: config.server, targets: Object.keys(config.targets ?? {}), poll_ms: config.pollMs, path: config.path, state_dir: config.stateDir, token: config.tokenSource ?? 'missing' });
129
+ await recover();
130
+ if (config.watch) {
131
+ const w = createWatchdog({ health: config.watch.health, ...config.watch }, { log, ...watchdogDeps });
132
+ watchTimer = w.start();
133
+ }
134
+ loopDone = loop();
135
+ await loopDone;
136
+ if (watchTimer) clearInterval(watchTimer);
137
+ lock?.release();
138
+ log?.info('runner stopped');
139
+ },
140
+ /** First call: finish the current job, then exit (up to stopTimeoutMs). Second call or timeout: interrupt the job. */
141
+ async stop(reason = 'stop') {
142
+ if (stopping) {
143
+ log?.warn('second stop signal — interrupting the job (the rollback still runs)', { deploy_id: job?.id ?? null });
144
+ kill.abort();
145
+ return loopDone;
146
+ }
147
+ stopping = true;
148
+ log?.info('stopping', { reason, job: job?.id ?? null });
149
+ wake.abort();
150
+ if (job) {
151
+ const t = setTimeout(() => {
152
+ log?.warn('stop timeout — interrupting the job', { deploy_id: job?.id ?? null });
153
+ kill.abort();
154
+ }, config.stopTimeoutMs ?? 20 * 60_000);
155
+ t.unref?.();
156
+ await loopDone;
157
+ clearTimeout(t);
158
+ }
159
+ return loopDone;
160
+ },
161
+ };
162
+ }
@@ -0,0 +1,111 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops): `doctor` — what the
2
+ // runner needs on this host, checked without changing anything: config and its mode, the token (present / shape — never the
3
+ // value), commands on the configured PATH, the repository, compose files, the state dir, the core's reachability. With
4
+ // `heartbeat: true` it sends ONE heartbeat (the target shows as online; nothing else changes).
5
+ import { accessSync, constants, existsSync, mkdirSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { configCandidates, findConfig, loadConfig, maskToken, permsProblem } from './config.js';
8
+ import { expandTarget } from './recipes.js';
9
+ import { commandsOf, execCmd, which } from './steps.js';
10
+ import { isCoreEnvFile } from './watchdog.js';
11
+ import { createClient } from './client.js';
12
+
13
+ /** → { ok, checks: [{ name, ok, detail, level }] } ; level 'warn' does not fail the run. */
14
+ export async function doctor({ file = null, env = process.env, fetchImpl = fetch, heartbeat = false, docker = true } = {}) {
15
+ const checks = [];
16
+ const add = (name, ok, detail, level = 'error') => checks.push({ name, ok: !!ok, detail, level: ok ? 'ok' : level });
17
+ const node = Number(process.versions.node.split('.')[0]);
18
+ add('node ≥ 22', node >= 22, `node ${process.versions.node} (${process.execPath})`);
19
+
20
+ const f = file ?? findConfig(env);
21
+ if (!f || !existsSync(f)) {
22
+ add('config', false, `not found (looked at ${configCandidates(env).join(', ')}); create: consilium-devops-runner config --print > <file>; chmod 600 <file>`);
23
+ return { ok: false, checks };
24
+ }
25
+ const perms = permsProblem(f);
26
+ add('config mode 600', !perms, perms ? perms.message : f);
27
+ let cfg;
28
+ try {
29
+ cfg = loadConfig({ file: f, env, checkPerms: false, strictToken: false });
30
+ } catch (e) {
31
+ add('config readable', false, `${e.code}: ${e.message}`);
32
+ return { ok: false, checks };
33
+ }
34
+ add('config readable', true, f);
35
+ const tf = /^tokenFile (.+?)( \(missing\))?$/.exec(cfg.tokenSource ?? '');
36
+ if (tf && !tf[2]) {
37
+ const p = permsProblem(tf[1]);
38
+ add('token file mode 600', !p, p ? p.message : tf[1]);
39
+ }
40
+ add('token present', !!cfg.token, cfg.token ? `${maskToken(cfg.token)} (from ${cfg.tokenSource})` : `no token${cfg.tokenSource ? ` — ${cfg.tokenSource}` : ''}: CONSILIUM_RUNNER_TOKEN, "tokenFile" or "token" (the owner creates it with /deploytarget)`);
41
+ if (cfg.token) add('token format', /^kdr_[A-Za-z0-9_-]{20,}$/.test(cfg.token), maskToken(cfg.token));
42
+ add('PATH', !!cfg.path, cfg.path);
43
+
44
+ const targets = Object.entries(cfg.targets ?? {});
45
+ add('targets', targets.length > 0, targets.length ? targets.map(([k, t]) => `${k}${t.recipe ? ` (${t.recipe})` : ''}`).join(', ') : 'no targets in the config');
46
+ const need = new Set(['git']);
47
+ for (const [key, raw] of targets) {
48
+ let t;
49
+ try {
50
+ t = expandTarget({ path: cfg.path, ...raw }, { stateDir: cfg.stateDir });
51
+ } catch (e) {
52
+ add(`target ${key}`, false, e.message);
53
+ continue;
54
+ }
55
+ const cwd = t.cwd;
56
+ add(`target ${key}: repository`, cwd && existsSync(cwd) && existsSync(join(cwd, '.git')), cwd ? `${cwd}${existsSync(join(cwd ?? '', '.git')) ? '' : ' — not a git checkout'}` : 'no cwd / repoDir');
57
+ for (const c of commandsOf([...(t.preDeploy ?? []), ...(t.deploy ?? []), ...(t.checks ?? []), ...(t.rollback ?? [])])) need.add(c);
58
+ if (t.options) {
59
+ const files = t.options.composeFiles ?? ['docker-compose.yml'];
60
+ for (const cf of files) add(`target ${key}: compose file ${cf}`, cwd && existsSync(join(cwd, cf)), join(cwd ?? '', cf));
61
+ if (!t.options.composeFiles && cwd && existsSync(join(cwd, 'docker-compose.override.yml'))) add(`target ${key}: docker-compose.override.yml`, true, 'present — used automatically (composeFiles is null)', 'warn');
62
+ for (const extra of ['docker-compose.ai.yml']) {
63
+ if (cwd && existsSync(join(cwd, extra)) && !(t.options.composeFiles ?? []).includes(extra)) {
64
+ add(`target ${key}: ${extra}`, false, `exists but is not in composeFiles — fine if COMPOSE_FILE in the project's .env lists it; otherwise add it (and composeProfiles ["ai"])`, 'warn');
65
+ }
66
+ }
67
+ if (t.options.buildWeb && cwd) add(`target ${key}: scripts/build-web.sh`, existsSync(join(cwd, 'scripts', 'build-web.sh')), join(cwd, 'scripts', 'build-web.sh'));
68
+ }
69
+ if (t.health) add(`target ${key}: health URL`, true, t.health, 'warn');
70
+ }
71
+ for (const c of [...need].sort()) {
72
+ const p = which(c, cfg.path);
73
+ add(`command ${c}`, !!p, p ?? `not on PATH (${cfg.path}) — add its directory to "path" in the config`);
74
+ }
75
+ if (docker && which('docker', cfg.path)) {
76
+ const r = await execCmd(['docker', 'version', '--format', '{{.Server.Version}}'], { env: { ...env, PATH: cfg.path }, timeoutMs: 15_000 });
77
+ add('docker daemon reachable', r.code === 0, r.code === 0 ? `server ${r.out.trim()}` : `${r.out.trim().split('\n').pop()} (is the user in the docker group?)`);
78
+ }
79
+ try {
80
+ mkdirSync(cfg.stateDir, { recursive: true, mode: 0o700 });
81
+ accessSync(cfg.stateDir, constants.W_OK);
82
+ add('state dir writable', true, cfg.stateDir);
83
+ } catch (e) {
84
+ add('state dir writable', false, `${cfg.stateDir}: ${e.code ?? e.message}`);
85
+ }
86
+ if (cfg.watch) {
87
+ const ef = cfg.watch.envFile;
88
+ if (ef && isCoreEnvFile(ef)) add('watchdog env file', false, `${ef} is the core's .env — the runner never reads it; use its own file (runner.env)`);
89
+ else add('watchdog telegram', !!(ef && existsSync(ef)) || !!env.CONSILIUM_RUNNER_TELEGRAM_TOKEN, ef ? (existsSync(ef) ? `${ef} (token not shown)` : `${ef} missing — alerts go to the log only`) : 'no envFile — alerts go to the log only', 'warn');
90
+ }
91
+ try {
92
+ const r = await fetchImpl(`${cfg.server}/api/health`, { signal: AbortSignal.timeout(10_000) });
93
+ add('core reachable', r.status === 200, `${cfg.server}/api/health → HTTP ${r.status}`);
94
+ } catch (e) {
95
+ add('core reachable', false, `${cfg.server}: ${e?.cause?.code ?? e?.message ?? e}`);
96
+ }
97
+ if (heartbeat && cfg.token) {
98
+ try {
99
+ const r = await createClient({ server: cfg.server, token: cfg.token, fetchImpl }).heartbeat();
100
+ add('heartbeat (token accepted)', true, `target ${r?.target ?? '?'}`);
101
+ } catch (e) {
102
+ add('heartbeat (token accepted)', false, `${e.code}: ${e.message}`);
103
+ }
104
+ }
105
+ return { ok: checks.every((c) => c.ok || c.level === 'warn'), checks };
106
+ }
107
+
108
+ export function formatDoctor({ ok, checks }) {
109
+ const mark = (c) => (c.ok ? 'ok ' : c.level === 'warn' ? 'warn' : 'FAIL');
110
+ return `${checks.map((c) => `[${mark(c)}] ${c.name}: ${c.detail}`).join('\n')}\n${ok ? 'doctor: ready' : 'doctor: not ready — fix the FAIL lines'}\n`;
111
+ }
@@ -0,0 +1,12 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-23; Konsilium: the deploy runner of @consilium108/mcp-module-devops (export
2
+ // "./runner"). Node built-ins only — it runs without the MCP SDK installed. The service: bin/consilium-devops-runner.js.
3
+ export { LOG_MAX, SECRET_ENV, childEnv, which, commandsOf, preflight, execCmd, runStep, runSteps, checkHealth, execute } from './steps.js';
4
+ export { RECIPES, expandTarget, httpCheck, konsiliumChecks } from './recipes.js';
5
+ export { createClient } from './client.js';
6
+ export { acquireLock, createState } from './state.js';
7
+ export { DEFAULT_SERVER, DEFAULT_PATH, defaultPath, configCandidates, findConfig, permsProblem, loadConfig, maskToken, exampleConfig } from './config.js';
8
+ export { createWatchdog, tokenFrom, freeGb, isCoreEnvFile } from './watchdog.js';
9
+ export { tick, resolveTarget, createRunner } from './daemon.js';
10
+ export { SERVICE_NAME, unitText, installSteps } from './install.js';
11
+ export { doctor, formatDoctor } from './doctor.js';
12
+ export { createLogger, redact } from './log.js';