@consilium108/mcp-module-devops 0.0.0-stage → 1.1.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 +31 -0
- package/LICENSE +289 -0
- package/README.md +171 -2
- package/bin/consilium-devops-mcp.js +66 -0
- package/bin/consilium-devops-runner.js +120 -0
- package/i18n/en.json +3 -0
- package/i18n/ru.json +3 -0
- package/i18n/th.json +3 -0
- package/i18n/zh.json +3 -0
- package/package.json +48 -4
- package/src/errors.js +12 -0
- package/src/groups/debug.js +44 -0
- package/src/groups/deploy.js +54 -0
- package/src/groups/ops.js +125 -0
- package/src/index.js +36 -0
- package/src/runner/client.js +42 -0
- package/src/runner/config.js +143 -0
- package/src/runner/daemon.js +162 -0
- package/src/runner/doctor.js +111 -0
- package/src/runner/index.js +12 -0
- package/src/runner/install.js +113 -0
- package/src/runner/log.js +33 -0
- package/src/runner/recipes.js +230 -0
- package/src/runner/state.js +84 -0
- package/src/runner/steps.js +196 -0
- package/src/runner/watchdog.js +113 -0
- package/src/standalone.js +227 -0
|
@@ -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';
|
|
@@ -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
|
+
}
|