@consilium108/mcp-module-devops 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §3): the event contract the
2
- // orchestrator consumes — ONLY what the server really sends today (project_events of #437 / #470), nothing assumed.
2
+ // orchestrator consumes (v2: inside the DevOps MCP — producer.js; unchanged rules) — ONLY what the server really sends today (project_events of #437 / #470), nothing assumed.
3
3
  // get_events (REST) { event_id, type, project_id, ref:{type,id}, agent, actor_user_id, summary, at, entity_type?,
4
4
  // entity_ref?, path?, version?, content_hash?, deleted?, via? }
5
5
  // projectEvents (SSE) { cursor, type, projectId, entity, ref, path, version, contentHash, deleted, at }
@@ -11,6 +11,7 @@
11
11
  // G1 (2026-11-24): deploy.* events of the journal (requested / approved / rejected / running / done / failed /
12
12
  // rolled_back / expired; ref = the deploy id, meta { deploy_id, target, kind, status, exit_code, health }) drive the jobs
13
13
  // that follow a deploy request — instead of polling GET /deploys/:id (kept as a fallback).
14
+ import { normalizeBusEvent as normalizeGeneric } from '@consilium108/mcp-agent-jobs';
14
15
  import { OWN_KEY_PREFIX, ORCHESTRATOR_PROVIDER } from './config.js';
15
16
 
16
17
  /** Agent event types that say something about an agent session's state (registry hints). */
@@ -26,18 +27,10 @@ export const STATE_HINTS = {
26
27
  'agent.task_completed': 'idle',
27
28
  };
28
29
 
29
- const metaOf = (m) => (m && typeof m === 'object' && !Array.isArray(m) ? m : null);
30
-
31
- /** One event of either shape → { cursor, type, projectId, agent, summary, entityRef, session, contentHash, at, refType, refId, meta, own } | null. */
30
+ /** One event of either shape (normalizeBusEvent of @consilium108/mcp-agent-jobs) + `own`: the orchestrator's own report. */
32
31
  export function normalizeBusEvent(e) {
33
- if (!e || typeof e !== 'object') return null;
34
- let ev;
35
- if ('event_id' in e) {
36
- ev = { cursor: Number(e.event_id), type: e.type ?? null, projectId: e.project_id ?? null, agent: e.agent ?? null, summary: e.summary ?? null, entityRef: e.entity_ref ?? null, session: e.path ?? null, contentHash: e.content_hash ?? null, at: e.at ?? null, refType: e.ref?.type ?? null, refId: e.ref?.id ?? null, meta: metaOf(e.meta) };
37
- } else {
38
- ev = { cursor: Number(e.cursor), type: e.type ?? e.kind ?? null, projectId: e.projectId ?? null, agent: e.agent ?? null, summary: e.summary ?? null, entityRef: typeof e.ref === 'string' ? e.ref : (e.entity_ref ?? null), session: e.path ?? null, contentHash: e.contentHash ?? null, at: e.at ?? null, refType: e.entity?.type ?? null, refId: e.entity?.id ?? null, meta: metaOf(e.meta) };
39
- }
40
- if (!Number.isFinite(ev.cursor) || !ev.type) return null;
32
+ const ev = normalizeGeneric(e);
33
+ if (!ev) return null;
41
34
  // loop guard: the orchestrator's own reports come back through the same journal
42
35
  ev.own = ev.agent === ORCHESTRATOR_PROVIDER || String(ev.contentHash ?? '').startsWith(`tm:${OWN_KEY_PREFIX}`);
43
36
  return ev;
@@ -1,13 +1,10 @@
1
- // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160: the local DevOps Agent Orchestrator of
2
- // @consilium108/mcp-module-devops (export "./orchestrator"). Node built-ins only; the SSE stream uses subscribeSse of
3
- // @nativemind108/mcp when the bin passes it. The service: bin/consilium-devops-orchestrator.js.
4
- export { ORCHESTRATOR_NAME, ORCHESTRATOR_PROVIDER, OWN_KEY_PREFIX, JOB_KINDS, DISPATCH_MODES, SLOT_DISPATCH, LIVE_ENV_DEFAULT, AGENT_MODES, orchestratorConfigCandidates, normalizeOrchestratorConfig, loadOrchestratorConfig, exampleOrchestratorConfig } from './config.js';
5
- export { createOrchestratorStore, JOB_STATUSES, LOCKING, FINISHED } from './store.js';
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2, SDD-P37-160: the DevOps Orchestrator of
2
+ // @consilium108/mcp-module-devops (export "./orchestrator") — INSIDE the DevOps MCP since 1.4.0: the producer of DevOps
3
+ // jobs for the shared job inbox of @consilium108/mcp-agent-jobs; the MCP bin starts and stops it with the process.
4
+ // The separate service of 1.2.0 / 1.3.0 (bin consilium-devops-orchestrator, systemd unit, agent slots, dry-run / live /
5
+ // hand-off dispatch) is removed.
6
+ export { ORCHESTRATOR_NAME, ORCHESTRATOR_PROVIDER, OWN_KEY_PREFIX, JOB_KINDS, LEGACY_KEYS, orchestratorConfigCandidates, normalizeOrchestratorConfig, loadOrchestratorConfig, findOrchestratorConfig, exampleOrchestratorConfig } from './config.js';
6
7
  export { normalizeBusEvent, intentOf, summaryHead, STATE_HINTS, DEPLOY_EVENT_STATUS } from './events.js';
7
- export { createRegistry, pickAgent, readTurnJournal, sessionStateOf, turnMonitorDirOf, AGENT_STATES } from './registry.js';
8
- export { claudeAdapter, codexAdapter, genericAdapter, defaultAdapters, jobContext, promptOf, parseResult, bypassesPermissions, validateLivePlan, RESULT_MARK, DEPLOY_CHECK_TOOLS, FORBIDDEN_FLAGS, READ_ONLY_GIT, LIVE_ALLOWED_TOOLS } from './adapters.js';
9
- export { createLiveDispatcher, resultTextOf, liveEnvOf, maskSecrets } from './live.js';
10
- export { createOrchestratorApi, PROJECT_EVENTS_QUERY, ALLOWED_ROUTES } from './api.js';
11
- export { createEventSource } from './source.js';
12
- export { createOrchestrator } from './daemon.js';
13
- export { orchestratorUnitText } from './install.js';
8
+ export { createRegistry, createSessionRegistry, readTurnJournal, sessionStateOf, turnMonitorDirOf, AGENT_STATES } from './registry.js';
9
+ export { DEPLOY_CHECK_TOOLS, jobContext, promptOf } from './brief.js';
10
+ export { createDevopsProducer, isOwnEvent, DEVOPS_MCP, DEVOPS_KINDS, DEVOPS_EVENT_TYPES } from './producer.js';
@@ -0,0 +1,193 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2 (SDD-P37-160, IT-160-2 … IT-160-6): the DevOps
2
+ // Orchestrator INSIDE the DevOps MCP process — the producer of DevOps jobs for the shared job inbox of
3
+ // @consilium108/mcp-agent-jobs (envelope konsilium.agent-job/1). It replaces the separate service of 1.2.0 / 1.3.0
4
+ // (daemon loop, agent slots, dry-run / live / hand-off dispatch, systemd unit, CLI): what stayed is the logic —
5
+ // events (events.js intents, unchanged) agent.deploy_required of a routed project → a job devops.deploy_check for the
6
+ // target (DEPLOY_REQUIRED is a signal, not a deploy); state hints → the registry
7
+ // queue rules (now the inbox) one active job per project + environment + target (lock_key), signals of a
8
+ // target coalesce into its queued job, lease / retry / backoff / max attempts
9
+ // deploy lifecycle (G1) deploy.* of the journal move the job that follows a request; GET /deploys/:id
10
+ // as the fallback (only the leader, only when the journal is silent)
11
+ // correlation (IT-14) a deploy.requested of the job's target after the claim gives the deploy id
12
+ // when the subagent's result has none
13
+ // reports (#470 route) waiting_for_user → NEEDS_APPROVAL (blocking), blocked → BLOCKED, failed →
14
+ // ERROR, succeeded / cancelled → TASK_COMPLETED; idempotent keys «orc:…» (the
15
+ // loop guard ignores them when they come back)
16
+ // Who runs a job: the main agent of the running session claims it (jobs_claim) and starts its own built-in subagent
17
+ // (Agent tool); the subagent may call request_deploy — a person approves it (✅); the existing runner of #482 executes
18
+ // only the approved deploy. Nothing here can approve, start an agent or a process.
19
+ import { intentOf, DEPLOY_EVENT_STATUS } from './events.js';
20
+ import { ORCHESTRATOR_PROVIDER, OWN_KEY_PREFIX } from './config.js';
21
+ import { DEPLOY_CHECK_TOOLS, jobContext, promptOf } from './brief.js';
22
+
23
+ export const DEVOPS_MCP = 'consilium-devops';
24
+ export const DEVOPS_KINDS = ['devops.deploy_check'];
25
+ export const DEVOPS_EVENT_TYPES = ['agent.', 'deploy.'];
26
+ /** deploy request status → job status (the job holds the target's lock until the deploy is final). */
27
+ const DEPLOY_STATUS = { pending: 'waiting_for_user', approved: 'running', running: 'running', done: 'succeeded', failed: 'failed', rejected: 'cancelled', expired: 'cancelled' };
28
+ const FOLLOWING = new Set(['waiting_for_user', 'running', 'claimed']);
29
+ const REPORT_TYPE = { waiting_for_user: 'NEEDS_APPROVAL', blocked: 'BLOCKED', failed: 'ERROR', succeeded: 'TASK_COMPLETED', cancelled: 'TASK_COMPLETED' };
30
+ const serverTime = (s) => (s ? Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : `${String(s).replace(' ', 'T')}Z`) : NaN);
31
+ const clip = (s, n) => (s == null ? null : String(s).length > n ? `${String(s).slice(0, n - 1)}…` : String(s));
32
+ /** The loop guard: the orchestrator's own reports come back through the same journal. */
33
+ export const isOwnEvent = (ev) => ev.agent === ORCHESTRATOR_PROVIDER || String(ev.contentHash ?? '').startsWith(`tm:${OWN_KEY_PREFIX}`);
34
+
35
+ /**
36
+ * @param {{ config: object, api: object|null, log?: object, now?: () => number, registry?: object|null, redact?: (s: string) => string }} o
37
+ * config — normalizeOrchestratorConfig (targets, routes, projects, report, deployPollFallbackMs, idleTtlMs)
38
+ */
39
+ export function createDevopsProducer({ config, api, log = { info() {}, warn() {}, error() {} }, now = Date.now, registry = null, redact = (s) => s }) {
40
+ const metrics = { events: 0, ignored: 0, own_ignored: 0, baseline_skipped: 0, hints: 0, enqueued: 0, coalesced: 0, duplicates: 0, deploy_events: 0, deploy_polls: 0, deploy_poll_errors: 0, reports_sent: 0, reports_suppressed: 0 };
41
+ const deployEventProjects = new Set(); // projects whose journal is seen sending deploy.* (G1) — polling becomes a fallback
42
+ const DEPLOY_NOTE = (id, s, d = {}) =>
43
+ ({
44
+ pending: `deploy request #${id} waits for a person's ✅`,
45
+ approved: `deploy #${id} approved by a person; waiting for the runner`,
46
+ running: `deploy #${id} is running on the runner`,
47
+ done: `deploy #${id} done (health ${d.health ?? '—'})`,
48
+ failed: `deploy #${id} failed on the runner (exit ${d.exitCode ?? '?'}, health ${d.health ?? '—'}); see deploy_status`,
49
+ rejected: `deploy request #${id} rejected by a person`,
50
+ expired: `deploy request #${id} expired without an approval`,
51
+ })[s] ?? `deploy #${id}: ${s}`;
52
+
53
+ function jobInput(intent) {
54
+ const src = intent.source;
55
+ const sources = [src];
56
+ const ctxJob = { id: '(this job)', kind: 'deploy_check', projectId: intent.projectId, target: intent.target, environment: intent.environment, sources, attempts: 1 };
57
+ return {
58
+ module: 'devops',
59
+ kind: 'devops.deploy_check',
60
+ mcp: DEVOPS_MCP,
61
+ project_id: intent.projectId,
62
+ title: `Deploy check: ${intent.target} (${intent.environment})`,
63
+ brief: promptOf(ctxJob),
64
+ context: jobContext(ctxJob),
65
+ correlation: { idempotency_key: `deploy_check:${src.project_id}:${src.event_id}`, events: [{ project_id: src.project_id, event_id: src.event_id, type: src.type }], task_ref: src.task_ref ?? null },
66
+ priority: intent.priority,
67
+ lock_key: `${intent.projectId}:${intent.environment}:${intent.target}`,
68
+ delegation: { mode: 'subagent', isolation: 'none', reason: 'an independent check; one deploy-related job per target at a time (lock_key)' },
69
+ approval: { required: true, by: 'a person with the deploy right (✅ in the Konsilium bot)' },
70
+ tools: DEPLOY_CHECK_TOOLS,
71
+ meta: { target: intent.target, environment: intent.environment, event_project_id: intent.eventProjectId },
72
+ note: `signal ${src.type} #${src.event_id}`,
73
+ // a later signal for the same queued job: its context lists every signal
74
+ mergeContext: (ctx, add) => ({ ...ctx, signals: [...(ctx?.signals ?? []), ...(add?.signals ?? [])].slice(-20) }),
75
+ };
76
+ }
77
+
78
+ /** Move the job that follows a deploy to the status the deploy now has (event or poll). */
79
+ function followDeploy(inbox, j, s, d = {}) {
80
+ const want = DEPLOY_STATUS[s];
81
+ const meta = { ...j.meta, deployFactAt: now() };
82
+ if (!want || (want === j.status && s === j.meta?.deployStatus)) return inbox.update(j.id, { meta });
83
+ return inbox.update(j.id, { status: want, lease: null, meta: { ...meta, deployStatus: s } }, DEPLOY_NOTE(j.correlation.deploy_id, s, d));
84
+ }
85
+
86
+ function applyDeployEvent(inbox, it) {
87
+ deployEventProjects.add(it.projectId);
88
+ const jobs = inbox.list({ module: 'devops' });
89
+ const j = jobs.find((x) => x.correlation.deploy_id === it.deployId && x.projectId === it.projectId && FOLLOWING.has(x.status));
90
+ if (j) return followDeploy(inbox, j, it.status, { health: it.health, exitCode: it.exitCode });
91
+ // IT-14: a request of the job's target made after the claim, before the subagent's result names it
92
+ if (it.event === 'deploy.requested' && it.target) {
93
+ const at = serverTime(it.at);
94
+ const c = jobs.find((x) => !x.correlation.deploy_id && x.lease && ['claimed', 'running'].includes(x.status) && x.projectId === it.projectId && x.meta?.target === it.target && (!Number.isFinite(at) || at >= Date.parse(x.claimedAt ?? 0) - 60_000));
95
+ if (c) inbox.update(c.id, { meta: { ...c.meta, candidateDeployId: it.deployId } }, `deploy request #${it.deployId} of ${it.target} seen in the journal`);
96
+ }
97
+ return null;
98
+ }
99
+
100
+ return {
101
+ module: 'devops',
102
+ mcp: DEVOPS_MCP,
103
+ kinds: DEVOPS_KINDS,
104
+ types: DEVOPS_EVENT_TYPES,
105
+ projects: () => config.projects,
106
+ metrics: () => ({ ...metrics }),
107
+
108
+ async handle(ev, { baseline = false, inbox }) {
109
+ metrics.events++;
110
+ const intent = intentOf({ ...ev, own: isOwnEvent(ev) }, config);
111
+ if (intent.action === 'deploy') {
112
+ metrics.deploy_events++;
113
+ applyDeployEvent(inbox, intent);
114
+ } else if (intent.action === 'hint') {
115
+ const at = serverTime(ev.at);
116
+ registry?.hint(intent.session, intent.state, Number.isFinite(at) ? new Date(at).toISOString() : null, `bus: ${ev.type}`);
117
+ metrics.hints++;
118
+ } else if (intent.action === 'enqueue') {
119
+ if (baseline) metrics.baseline_skipped++;
120
+ else {
121
+ const r = inbox.enqueue(jobInput(intent), { coalesce: true });
122
+ if (r.duplicate) metrics.duplicates++;
123
+ else if (r.coalesced) metrics.coalesced++;
124
+ else {
125
+ metrics.enqueued++;
126
+ log.info?.('devops job queued', { job: r.job.id, target: intent.target, environment: intent.environment, event_id: intent.source.event_id });
127
+ }
128
+ }
129
+ } else if (intent.reason === 'own_report') metrics.own_ignored++;
130
+ else metrics.ignored++;
131
+ },
132
+
133
+ /** The subagent's result → the job status: a requested deploy is followed until it is final (holds the target). */
134
+ decide(job, result) {
135
+ if (result.outcome !== 'requested') return null; // the inbox default
136
+ const id = result.deploy_id ?? (Number.isInteger(job.meta?.candidateDeployId) ? job.meta.candidateDeployId : null);
137
+ if (!id) return { status: 'blocked', note: 'the subagent said «requested» but gave no deploy id (and none of this target was seen in the journal)' };
138
+ return { status: 'waiting_for_user', patch: { correlation: { ...job.correlation, deploy_id: id }, meta: { ...job.meta, deployStatus: 'pending', deployFactAt: now() } }, note: `deploy request #${id} waits for a person's ✅${result.deploy_id ? '' : ' (id from the journal)'}` };
139
+ },
140
+
141
+ /** G1 fallback: GET /deploys/:id of followed deploys — only the listener's process, only when the journal is silent. */
142
+ async tick({ leader, inbox }) {
143
+ if (!leader || !api?.deploy) return;
144
+ for (const j of inbox.list({ module: 'devops' })) {
145
+ const id = j.correlation.deploy_id;
146
+ if (!id || !FOLLOWING.has(j.status)) continue;
147
+ if (deployEventProjects.has(j.projectId) && now() - (j.meta?.deployFactAt ?? 0) < config.deployPollFallbackMs) continue;
148
+ let d;
149
+ try {
150
+ metrics.deploy_polls++;
151
+ d = await api.deploy(j.projectId, id);
152
+ } catch (e) {
153
+ metrics.deploy_poll_errors++;
154
+ log.warn?.('deploy status unavailable', { job: j.id, deploy_id: id, code: e.code ?? 'error' });
155
+ continue;
156
+ }
157
+ followDeploy(inbox, j, d?.status, { health: d?.health, exitCode: d?.exitCode });
158
+ }
159
+ },
160
+
161
+ /** Server effects: status reports through the #470 agent-event route (idempotent; nobody is notified by it). */
162
+ async effect(job, name, ef = {}) {
163
+ const status = name === 'result' ? (ef.status ?? job.status) : name;
164
+ const type = REPORT_TYPE[status];
165
+ if (!type || !api?.report) return;
166
+ if (config.report === 'off') {
167
+ metrics.reports_suppressed++;
168
+ return;
169
+ }
170
+ const deployId = job.correlation.deploy_id ?? 0;
171
+ const text = job.result?.summary ?? job.history?.at(-1)?.note ?? null;
172
+ await api.report(job.meta?.event_project_id ?? job.projectId, {
173
+ idempotency_key: `${OWN_KEY_PREFIX}${job.id}:${status}:${ef.attempt ?? job.attempts}:${deployId}`,
174
+ type,
175
+ basis: 'lifecycle',
176
+ confidence: 1,
177
+ provider: ORCHESTRATOR_PROVIDER,
178
+ via: DEVOPS_MCP,
179
+ session_id: `orc-${job.id}`,
180
+ blocking: status === 'waiting_for_user',
181
+ reason: clip(`DevOps job ${job.id} (${job.kind} ${job.meta?.target}/${job.meta?.environment}) → ${status}`, 500),
182
+ ...(text ? { text: clip(redact(text), 500) } : {}),
183
+ ...(job.correlation.task_ref ? { task_ref: clip(job.correlation.task_ref, 120) } : {}),
184
+ at: new Date(now()).toISOString(),
185
+ });
186
+ metrics.reports_sent++;
187
+ },
188
+
189
+ status: () => ({ targets: Object.keys(config.targets), routes: config.routes.length, deploy_event_projects: [...deployEventProjects], report: config.report, warnings: config.warnings ?? [], metrics: { ...metrics } }),
190
+ };
191
+ }
192
+
193
+ export { DEPLOY_EVENT_STATUS };
@@ -11,7 +11,7 @@
11
11
  // RESOLVED (the person answered; the agent goes on) → running
12
12
  // TURN_COMPLETED / TASK_COMPLETED / DEPLOY_REQUIRED (not blocking) within idleTtlMs → idle
13
13
  // nothing seen, or the last fact is older than idleTtlMs → unavailable
14
- // «headless» slots (a process the orchestrator itself would own) are idle unless leased.
14
+ // (v2: one slot = the workspace of the running session — createSessionRegistry; «headless» slots are gone.)
15
15
  // G4 (2026-11-24): with @consilium108/mcp ≥ 0.11.1 the facts come from its read-only export `@consilium108/mcp/turnmonitor`
16
16
  // (turnMonitorState — the monitor's own reading, incl. TURN_STARTED of G3); without it (older host package, not
17
17
  // installed) the files are read directly as before.
@@ -144,7 +144,19 @@ export function createRegistry({ agents, adapters, idleTtlMs, now = Date.now, re
144
144
  };
145
145
  }
146
146
 
147
- /** A free compatible agent for a job, or null. Prefers an agent that serves the target's project first, then by config order. */
148
- export function pickAgent(snapshot, job, taken = new Set()) {
149
- return snapshot.find((a) => a.state === 'idle' && !taken.has(a.id) && a.capabilities.includes(job.kind) && (a.projects.includes(job.projectId) || a.projects.includes(job.eventProjectId))) ?? null;
147
+ /**
148
+ * v2 (inside the MCP, 2026-11-24): the state of THIS session's workspace — shown by jobs_inbox / jobs_status so the main
149
+ * agent sees whether it is waiting for a person or blocked. It never gates a claim: subagents of the session run in
150
+ * parallel with the main agent; the registry keeps its facts (#470) and the bus hints of the listener.
151
+ */
152
+ export function createSessionRegistry({ workspace, provider = 'claude', idleTtlMs = 6 * 3600_000, now = Date.now, turnMonitor = null, readJournal, readOpen, dirOf } = {}) {
153
+ const slot = { id: 'this-session', provider, mode: 'session', workspace, projects: [], capabilities: [] };
154
+ const reg = createRegistry({ agents: [slot], adapters: { [provider]: { available: () => ({ ok: true }) } }, idleTtlMs, now, turnMonitor, ...(readJournal ? { readJournal } : {}), ...(readOpen ? { readOpen } : {}), ...(dirOf ? { dirOf } : {}) });
155
+ return {
156
+ hint: (...a) => reg.hint(...a),
157
+ state() {
158
+ const s = reg.snapshot()[0];
159
+ return { workspace, state: s.state, reason: s.reason, session: s.session ?? null, at: s.at ?? null };
160
+ },
161
+ };
150
162
  }
@@ -134,7 +134,7 @@ export function exampleConfig({ repoDir = '/path/to/consilium.nativemind.net', t
134
134
  intervalMs: 60000,
135
135
  diskPath: '/',
136
136
  minFreeGb: 30,
137
- health: 'http://127.0.0.1:8090/api/health',
137
+ health: 'http://127.0.0.1:8090/api/health?deep=1', // OPS-AUDIT-435: DB + migrations + modules, 503 when broken
138
138
  failAfter: 3,
139
139
  chatIds: [],
140
140
  envFile: '~/.config/consilium-devops-runner/runner.env',
@@ -10,3 +10,4 @@ export { tick, resolveTarget, createRunner } from './daemon.js';
10
10
  export { SERVICE_NAME, unitText, installSteps } from './install.js';
11
11
  export { doctor, formatDoctor } from './doctor.js';
12
12
  export { createLogger, redact } from './log.js';
13
+ export { RECORD_USAGE, parseRecordArgs, buildRecordBody, gitHead, logTailOf, recordDeploy, formatRecorded, runRecord } from './record.js'; // OPS-AUDIT-435
@@ -24,6 +24,7 @@ const KONSILIUM_DEFAULTS = {
24
24
  healthyTimeoutMs: 300_000,
25
25
  userVersion: true,
26
26
  logErrors: true,
27
+ deepHealth: true, // OPS-AUDIT-435: the first check is GET /api/health?deep=1
27
28
  logErrorPattern: '"level":(50|60)\\b|UnhandledPromiseRejection|Uncaught(Exception)?\\b|FATAL',
28
29
  stepTimeoutMs: 20 * 60_000,
29
30
  };
@@ -50,7 +51,8 @@ export function httpCheck({ method = 'GET', url, expect = 200, headers = {}, bod
50
51
  export function konsiliumChecks(o, deps) {
51
52
  const json = { 'content-type': 'application/json', accept: 'application/json, text/event-stream' };
52
53
  return [
53
- { method: 'GET', url: `${o.appUrl}/api/health`, expect: 200 },
54
+ // OPS-AUDIT-435: deep=1 — DB, migrations = newest file, remote modules (an older core ignores the query and answers 200)
55
+ { method: 'GET', url: `${o.appUrl}/api/health${o.deepHealth === false ? '' : '?deep=1'}`, expect: 200 },
54
56
  { method: 'POST', url: `${o.mcpUrl}/mcp`, expect: 401, headers: json, body: '{}' },
55
57
  { method: 'POST', url: `${o.appUrl}/line/webhook`, expect: 401, headers: json, body: '{}' },
56
58
  { method: 'POST', url: `${o.appUrl}/max/webhook`, expect: 401, headers: json, body: '{}' },
@@ -0,0 +1,140 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24 — OPS-AUDIT-435 (аудит выкаток #435, рекомендация 8): a deploy made from
2
+ // the TERMINAL goes into the same journal as the button ones (deploy_requests, requested_via 'terminal'). The lead calls
3
+ // `consilium-devops-runner record …` (or scripts/record-deploy.mjs in the Konsilium checkout) right after a terminal
4
+ // deploy. It POSTs /api/deploy/runner/record with the target's runner token through the Konsilium API (the core proxies it
5
+ // to the DevOps module with MODULE_DEVOPS=remote) — it never opens a database, never runs a step, never approves anything.
6
+ // The token comes from CONSILIUM_RUNNER_TOKEN or the runner config's tokenFile and is never printed.
7
+ import { readFileSync } from 'node:fs';
8
+ import { execFileSync } from 'node:child_process';
9
+ import { DevopsMcpError } from '../errors.js';
10
+ import { DEFAULT_SERVER, findConfig, loadConfig } from './config.js';
11
+ import { LOG_MAX } from './steps.js';
12
+
13
+ export const RECORD_USAGE = `record — put a terminal deploy into the Konsilium deploy journal (after the fact; nothing runs)
14
+
15
+ record --summary "<what changed>" [--exit-code N | --status done|failed] [--health ok|fail|<text>]
16
+ [--started-at <ISO>] [--finished-at <ISO>] [--approval "<who approved, where, when>"]
17
+ [--git-sha <sha> | --repo <dir>] [--log-file <file>] [--kind deploy|rollback]
18
+ [--server <url>] [--config <file>] [--dry-run]
19
+
20
+ The token: CONSILIUM_RUNNER_TOKEN, else "tokenFile" of the runner config (never printed).
21
+ The server: --server, else KONSILIUM_API_URL, else the runner config's "server" (e.g. http://127.0.0.1:8090 on the prod host).
22
+ --dry-run prints the request body (without the token) and sends nothing.`;
23
+
24
+ const VALUED = ['--summary', '--exit-code', '--status', '--health', '--started-at', '--finished-at', '--approval', '--git-sha', '--repo', '--log-file', '--kind', '--server', '--config'];
25
+
26
+ /** argv (after the command) → options; unknown flags are an error. */
27
+ export function parseRecordArgs(argv) {
28
+ const o = { dryRun: false };
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const a = argv[i];
31
+ if (a === 'record') continue;
32
+ if (a === '--dry-run') {
33
+ o.dryRun = true;
34
+ continue;
35
+ }
36
+ if (!VALUED.includes(a)) throw new DevopsMcpError('bad_argument', `unknown argument ${a} (record --help)`);
37
+ const v = argv[i + 1];
38
+ if (v == null || (v.startsWith('--') && VALUED.includes(v))) throw new DevopsMcpError('bad_argument', `${a} needs a value`);
39
+ o[a.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = v;
40
+ i++;
41
+ }
42
+ return o;
43
+ }
44
+
45
+ /** Options → the request body. Pure (gitSha / logTail are passed in). */
46
+ export function buildRecordBody(o, { gitSha = null, logTail = '' } = {}) {
47
+ const summary = String(o.summary ?? '').trim();
48
+ if (!summary) throw new DevopsMcpError('summary_required', '--summary is required (what was deployed: services, migrations, commits)');
49
+ let exitCode = null;
50
+ if (o.exitCode != null) {
51
+ exitCode = Number(o.exitCode);
52
+ if (!Number.isInteger(exitCode)) throw new DevopsMcpError('bad_argument', '--exit-code must be an integer');
53
+ }
54
+ if (o.status != null && !['done', 'failed'].includes(o.status)) throw new DevopsMcpError('bad_argument', '--status: done | failed');
55
+ if (o.kind != null && !['deploy', 'rollback'].includes(o.kind)) throw new DevopsMcpError('bad_argument', '--kind: deploy | rollback');
56
+ for (const k of ['startedAt', 'finishedAt']) if (o[k] != null && Number.isNaN(new Date(o[k]).getTime())) throw new DevopsMcpError('bad_argument', `--${k === 'startedAt' ? 'started-at' : 'finished-at'}: not a date/time`);
57
+ const body = { summary: summary.slice(0, 2000) };
58
+ if (o.status) body.status = o.status;
59
+ if (o.kind) body.kind = o.kind;
60
+ if (exitCode != null) body.exitCode = exitCode;
61
+ if (o.health) body.health = String(o.health).slice(0, 200);
62
+ if (o.startedAt) body.startedAt = new Date(o.startedAt).toISOString();
63
+ if (o.finishedAt) body.finishedAt = new Date(o.finishedAt).toISOString();
64
+ if (o.approval) body.approval = String(o.approval).slice(0, 300);
65
+ const sha = o.gitSha ?? gitSha;
66
+ if (sha) {
67
+ if (!/^[0-9a-f]{7,40}$/i.test(sha)) throw new DevopsMcpError('bad_argument', '--git-sha: 7–40 hex characters');
68
+ body.gitSha = sha;
69
+ }
70
+ if (logTail) body.logTail = String(logTail).slice(-LOG_MAX);
71
+ return body;
72
+ }
73
+
74
+ /** HEAD of a checkout, or null. */
75
+ export function gitHead(repo) {
76
+ try {
77
+ return execFileSync('git', ['-C', repo, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ /** The last LOG_MAX bytes of a log file. */
84
+ export function logTailOf(file) {
85
+ return readFileSync(file, 'utf8').slice(-LOG_MAX);
86
+ }
87
+
88
+ /** POST /api/deploy/runner/record → the journal row ({ id, status, via: 'terminal', … , already? }). */
89
+ export async function recordDeploy({ server, token, body, fetchImpl = fetch, userAgent = 'consilium-devops-runner record', timeoutMs = 30_000 }) {
90
+ if (!token) throw new DevopsMcpError('token_missing', 'no runner token (CONSILIUM_RUNNER_TOKEN or "tokenFile" in the runner config)');
91
+ const base = String(server ?? '').replace(/\/+$/, '');
92
+ if (!/^https?:\/\//.test(base)) throw new DevopsMcpError('bad_argument', 'no server URL (--server, KONSILIUM_API_URL or "server" in the runner config)');
93
+ let r;
94
+ try {
95
+ r = await fetchImpl(`${base}/api/deploy/runner/record`, {
96
+ method: 'POST',
97
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': userAgent },
98
+ body: JSON.stringify(body),
99
+ signal: AbortSignal.timeout(timeoutMs),
100
+ });
101
+ } catch (e) {
102
+ throw new DevopsMcpError('network_unavailable', `record: ${e?.cause?.code ?? e?.name ?? 'network error'}`, 0);
103
+ }
104
+ const text = await r.text();
105
+ let json = null;
106
+ try {
107
+ json = JSON.parse(text);
108
+ } catch {
109
+ /* not JSON */
110
+ }
111
+ if (!r.ok) {
112
+ const code = r.status === 401 ? 'bad_runner_token' : r.status === 404 ? 'not_supported' : json?.error?.code ?? `http_${r.status}`;
113
+ const hint = r.status === 404 ? ' (the server is older than OPS-AUDIT-435 — deploy it first, then record)' : '';
114
+ throw new DevopsMcpError(code, `record: HTTP ${r.status}${json?.error?.message ? ` — ${json.error.message}` : ''}${hint}`, r.status);
115
+ }
116
+ return json;
117
+ }
118
+
119
+ /** One line for people: «#D97 done (terminal) …». */
120
+ export function formatRecorded(r) {
121
+ return `${r.already ? 'already recorded' : 'recorded'}: #D${r.id} ${r.status} (via ${r.via}) → ${r.target ?? '?'}${r.startedAt ? ` · ${r.startedAt}–${r.finishedAt ?? ''}` : ''}`;
122
+ }
123
+
124
+ /**
125
+ * The whole command: argv → body → POST. Config is optional when CONSILIUM_RUNNER_TOKEN is set.
126
+ * @returns {Promise<{ dryRun: true, server: string, body: object } | { dryRun: false, server: string, row: object }>}
127
+ */
128
+ export async function runRecord(argv, { env = process.env, fetchImpl = fetch, cwd = process.cwd(), load = loadConfig, find = findConfig } = {}) {
129
+ const o = parseRecordArgs(argv);
130
+ let cfg = null;
131
+ const file = o.config ?? env.CONSILIUM_DEVOPS_RUNNER_CONFIG ?? find(env);
132
+ if (file || !env.CONSILIUM_RUNNER_TOKEN) cfg = load({ file: o.config ?? null, env, strictToken: !o.dryRun });
133
+ const token = env.CONSILIUM_RUNNER_TOKEN?.trim() || cfg?.token || null;
134
+ const server = String(o.server ?? env.KONSILIUM_API_URL ?? cfg?.server ?? DEFAULT_SERVER).replace(/\/+$/, '');
135
+ const repo = o.repo ?? cwd;
136
+ const body = buildRecordBody(o, { gitSha: o.gitSha ? null : gitHead(repo), logTail: o.logFile ? logTailOf(o.logFile) : '' });
137
+ if (o.dryRun) return { dryRun: true, server, tokenPresent: !!token, body };
138
+ const row = await recordDeploy({ server, token, body, fetchImpl });
139
+ return { dryRun: false, server, row };
140
+ }
package/src/standalone.js CHANGED
@@ -12,11 +12,14 @@ import { z } from 'zod';
12
12
  import mod from './index.js';
13
13
  import { OPS_TOOLS, registerOpsTools } from './groups/ops.js';
14
14
  import { DevopsMcpError } from './errors.js';
15
+ import { registerJobTools, JOB_TOOLS, JOBS_INSTRUCTIONS } from '@consilium108/mcp-agent-jobs';
15
16
 
16
17
  export const DEFAULT_API_URL = 'https://konsilium.nativemind.net';
17
18
  export const SESSION_TOOLS = ['devops_session', 'select_project'];
18
19
  /** Every tool of the standalone server, in registration order. */
19
20
  export const STANDALONE_TOOLS = [...SESSION_TOOLS, ...Object.values(mod.groups).flatMap((g) => g.tools), ...OPS_TOOLS];
21
+ /** + the job inbox tools when the job runtime runs (the default of the bin; TASK-P37-486 v2). */
22
+ export { JOB_TOOLS };
20
23
 
21
24
  export { DevopsMcpError }; // src/errors.js — shared with the deploy runner
22
25
 
@@ -68,8 +71,10 @@ export function fillPath(path, args = {}) {
68
71
  * @param {number|null} [o.projectId] the project chosen at start (--project / KONSILIUM_PROJECT_ID)
69
72
  * @param {string} [o.version] the client version for User-Agent
70
73
  * @param {typeof fetch} [o.fetch]
74
+ * @param {object|null} [o.jobs] the job runtime of @consilium108/mcp-agent-jobs (TASK-P37-486 v2: the DevOps
75
+ * Orchestrator inside this MCP) → the six jobs_* tools, the inbox resource and change notifications
71
76
  */
72
- export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, credentials = null, projectId = null, version = mod.version, fetch: f = globalThis.fetch, timeoutMs = 60_000 } = {}) {
77
+ export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, credentials = null, projectId = null, version = mod.version, fetch: f = globalThis.fetch, timeoutMs = 60_000, jobs = null } = {}) {
73
78
  const core = String(apiUrl).replace(/\/+$/, '');
74
79
  const direct = devopsUrl ? String(devopsUrl).replace(/\/+$/, '') : null;
75
80
  let active = Number(projectId) || null;
@@ -170,7 +175,7 @@ export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, cr
170
175
  client: () => 'MCP',
171
176
  };
172
177
 
173
- const server = new McpServer({ name: 'consilium-devops', version }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
178
+ const server = new McpServer({ name: 'consilium-devops', version }, { capabilities: { tools: {}, ...(jobs ? { resources: {}, logging: {} } : {}) }, instructions: jobs ? `${INSTRUCTIONS}\n${JOBS_INSTRUCTIONS}` : INSTRUCTIONS });
174
179
  const ro = { readOnlyHint: true, openWorldHint: false };
175
180
 
176
181
  server.registerTool(
@@ -216,12 +221,13 @@ export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, cr
216
221
  );
217
222
  for (const g of Object.values(mod.groups)) g.register(server, h);
218
223
  registerOpsTools(server, h);
224
+ if (jobs) registerJobTools(server, { runtime: jobs, z, mcp: 'consilium-devops' });
219
225
 
220
226
  return { server, helpers: h, activeProject: () => active, loadSession };
221
227
  }
222
228
 
223
229
  export const INSTRUCTIONS = `Konsilium DevOps MCP (${mod.name} ${mod.version}): deploy requests by button and their status, deploy targets and the runner's heartbeat, Job Copilot debug reports — for the projects of your Konsilium sign-in.
224
230
  Start with devops_session (who, projects, rights, active project); select_project switches the project.
225
- runner_status shows whether the deploy runner of each target is online and what it runs; runner_setup gives a person the steps to install it (text only — the runner is a separate service, bin consilium-devops-runner).
231
+ runner_status shows whether the deploy runner of each target is online and what it runs; runner_setup gives a person the steps to install it (text only — the runner is a separate service on the deploy host, bin consilium-devops-runner; it executes only approved deploys).
226
232
  request_deploy asks the people with the deploy right to approve (✅ in the messenger); you cannot approve, reject or roll back — a person does. Then poll deploy_status(deploy_id): pending → approved → running → done | failed (rejected / expired), exit code, health, log tail.
227
233
  Errors come as «code: message» (auth_required, auth_invalid, project_not_chosen, no_deploy_right, module_disabled, module_unavailable, network_unavailable …).`;