@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,494 +0,0 @@
1
- // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §6–§9): the orchestrator — a
2
- // SEPARATE long-running local service (`consilium-devops-orchestrator run`), never inside an MCP process, never in the
3
- // runner. Loop:
4
- // events (source.js) → seen? → intent (events.js) → enqueue / coalesce (one queued job per target lock) | state hint
5
- // tick: lease expiry → agent states (registry.js) → job ↔ agent sync → deploy status poll → schedule (lock per
6
- // project + environment + target, one job per agent) → dispatch through the provider adapter (dry-run here)
7
- // → reports (outbox → POST agent-events, idempotent) → status.json
8
- // It never approves anything: a deploy an agent REQUESTS waits for a person's ✅; the job then follows the request's status
9
- // on the server (pending → waiting_for_user, approved / running → running, done → succeeded, failed → failed (runner),
10
- // rejected / expired → cancelled) and holds the target lock until then — no parallel deploy of one target.
11
- // 2026-11-24 (owner «Запускай все, добавь сразу»): G1 — the deploy.* events of the journal move those jobs (polling stays
12
- // as a fallback: every tick until the server is seen sending deploy.* for the project, then only after
13
- // deployPollFallbackMs without a fact); G2 — routes by the target / environment an agent event names; stage 3 — a slot
14
- // with dispatch "live" (headless claude) is STARTED through live.js (one job per slot, timeout ≤ lease, the result →
15
- // complete → report), a «session» slot with dispatch "handoff" gets a create_handoff and its result comes back from the
16
- // hand-off; every other slot stays dry-run. The global default is dry-run; nothing here can approve.
17
- import { writeFileSync, renameSync } from 'node:fs';
18
- import { join } from 'node:path';
19
- import { ORCHESTRATOR_NAME, ORCHESTRATOR_PROVIDER, OWN_KEY_PREFIX } from './config.js';
20
- import { intentOf } from './events.js';
21
- import { pickAgent } from './registry.js';
22
- import { bypassesPermissions, parseResult, validateLivePlan } from './adapters.js';
23
- import { LOCKING, JOB_STATUSES } from './store.js';
24
- import { redact } from '../runner/log.js';
25
-
26
- const LEASED = new Set(['assigned', 'running', 'waiting_for_user']);
27
- const DEPLOY_STATUS = { pending: 'waiting_for_user', approved: 'running', running: 'running', done: 'succeeded', failed: 'failed', rejected: 'cancelled', expired: 'cancelled' };
28
- const REPORT_TYPE = { waiting_for_user: 'NEEDS_APPROVAL', blocked: 'BLOCKED', failed: 'ERROR', succeeded: 'TASK_COMPLETED', cancelled: 'TASK_COMPLETED' };
29
- const serverTime = (s) => (s ? Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : `${String(s).replace(' ', 'T')}Z`) : NaN);
30
- const clip = (s, n) => (s == null ? null : String(s).length > n ? `${String(s).slice(0, n - 1)}…` : String(s));
31
-
32
- /**
33
- * @param {object} config normalized (config.js)
34
- * @param {{ api: object, store: object, registry: object, adapters: Record<string, object>, source?: object,
35
- * createSource?: (handle: Function) => object, log?: object, now?: () => number, lock?: { release: () => void } | null,
36
- * sleep?: Function, dispatcher?: { start: Function, busy: Function, list: Function, stop: Function } | null }} deps
37
- * dispatcher — the live dispatcher (live.js) of `run`; without it a "live" slot is dispatched dry-run
38
- */
39
- export function createOrchestrator(config, deps) {
40
- const { api, store, registry, adapters } = deps;
41
- const log = deps.log ?? { info() {}, warn() {}, error() {} };
42
- const now = deps.now ?? Date.now;
43
- const iso = () => new Date(now()).toISOString();
44
- const metrics = { events: 0, duplicates: 0, ignored: 0, own_ignored: 0, baseline_skipped: 0, hints: 0, enqueued: 0, coalesced: 0, dispatched: 0, refused: 0, lease_expired: 0, stale_results: 0, deploy_events: 0, deploy_polls: 0, deploy_poll_errors: 0, live_started: 0, live_finished: 0, live_timeouts: 0, live_refused: 0, handoffs_created: 0, handoff_polls: 0, handoff_poll_errors: 0, reports_sent: 0, report_errors: 0, reports_suppressed: 0, last_event_lag_ms: null, tick_errors: 0 };
45
- const dispatcher = deps.dispatcher ?? null;
46
- const deployEventProjects = new Set(); // projects whose journal is seen sending deploy.* (G1) — polling becomes a fallback
47
- const cancels = []; // hand-offs to cancel (their lease expired while still pending): { projectId, handoffId }
48
- let lastSnapshot = [];
49
- let lastError = null;
50
- let lastTickAt = null;
51
- let startedAt = null;
52
- let stopping = false;
53
- let loopDone = null;
54
- const wake = new AbortController();
55
- const sleep = deps.sleep ?? ((ms, signal) => new Promise((r) => {
56
- const t = setTimeout(r, ms);
57
- signal?.addEventListener('abort', () => (clearTimeout(t), r()), { once: true });
58
- }));
59
-
60
- // ── reports back to Konsilium (the #470 agent-event route; idempotent by key; nobody is notified by it)
61
- function report(job, status, text) {
62
- const type = REPORT_TYPE[status];
63
- if (!type || config.report === 'off') return;
64
- if ((job.dispatchMode ?? config.dispatch) === 'dry_run' && !config.reportDryRun) {
65
- metrics.reports_suppressed++;
66
- return;
67
- }
68
- const body = {
69
- idempotency_key: `${OWN_KEY_PREFIX}${job.id}:${status}:${job.attempts}:${job.deployId ?? 0}`,
70
- type,
71
- basis: 'lifecycle',
72
- confidence: 1,
73
- provider: ORCHESTRATOR_PROVIDER,
74
- via: ORCHESTRATOR_NAME,
75
- session_id: `orc-${job.id}`,
76
- blocking: status === 'waiting_for_user',
77
- reason: clip(`orchestrator job ${job.id} (${job.kind} ${job.target}/${job.environment}) → ${status}`, 500),
78
- text: clip(redact(text ?? ''), 500) || undefined,
79
- ...(job.sources?.[0]?.task_ref ? { task_ref: clip(job.sources[0].task_ref, 120) } : {}),
80
- at: iso(),
81
- };
82
- store.outbox.add({ id: body.idempotency_key, projectId: job.eventProjectId ?? job.projectId, body });
83
- }
84
-
85
- async function flushOutbox() {
86
- for (const o of store.outbox.list()) {
87
- if (o.nextAt > now()) continue;
88
- try {
89
- await api.report(o.projectId, o.body);
90
- store.outbox.remove(o.id);
91
- metrics.reports_sent++;
92
- } catch (e) {
93
- metrics.report_errors++;
94
- const attempts = o.attempts + 1;
95
- if (attempts >= 10 || [400, 403, 404].includes(e.status)) {
96
- store.outbox.remove(o.id);
97
- log.error('report dropped', { report: o.id, code: e.code ?? 'error', attempts });
98
- } else {
99
- store.outbox.update(o.id, { attempts, nextAt: now() + Math.min(3600_000, 5000 * 2 ** attempts) });
100
- log.warn('report failed, retrying', { report: o.id, code: e.code ?? 'error', attempts });
101
- }
102
- }
103
- }
104
- }
105
-
106
- function setStatus(job, status, patch = {}, note = null, reportText = null) {
107
- const j = store.jobs.update(job.id, { ...patch, status }, note);
108
- log.info('job', { job: job.id, status, note, target: job.target, agent: j.agentId ?? null, deploy_id: j.deployId ?? null });
109
- if (status !== job.status || reportText) report(j, status, reportText ?? note);
110
- return j;
111
- }
112
-
113
- // ── events
114
- function enqueue(intent) {
115
- const src = intent.source;
116
- const lockKey = `${intent.projectId}:${intent.environment}:${intent.target}`;
117
- const jobs = store.jobs.all();
118
- if (jobs.some((j) => j.sources.some((s) => s.project_id === src.project_id && s.event_id === src.event_id))) {
119
- metrics.duplicates++;
120
- return null;
121
- }
122
- const queued = jobs.find((j) => j.status === 'queued' && j.lockKey === lockKey && j.kind === intent.kind);
123
- if (queued) {
124
- // several signals for one target: one queued job carries them all
125
- store.jobs.addSource(queued.id, src);
126
- metrics.coalesced++;
127
- log.info('signal joined a queued job', { job: queued.id, event_id: src.event_id, target: intent.target });
128
- return queued.id;
129
- }
130
- const j = store.jobs.create({ kind: intent.kind, projectId: intent.projectId, eventProjectId: intent.eventProjectId, target: intent.target, environment: intent.environment, approval: intent.approval, lockKey, priority: intent.priority, idempotencyKey: `${intent.kind}:${src.project_id}:${src.event_id}`, sources: [src], note: `signal ${src.type} #${src.event_id}` });
131
- metrics.enqueued++;
132
- log.info('job queued', { job: j.id, target: j.target, environment: j.environment, event_id: src.event_id });
133
- return j.id;
134
- }
135
-
136
- async function handle(ev, { baseline = false } = {}) {
137
- const key = `p${ev.projectId}:e${ev.cursor}`;
138
- if (store.seen.has(key)) {
139
- metrics.duplicates++;
140
- return;
141
- }
142
- metrics.events++;
143
- const at = serverTime(ev.at);
144
- if (Number.isFinite(at)) metrics.last_event_lag_ms = Math.max(0, now() - at);
145
- const intent = intentOf(ev, config);
146
- if (intent.action === 'deploy') {
147
- metrics.deploy_events++;
148
- applyDeployEvent(intent);
149
- } else if (intent.action === 'hint') {
150
- registry.hint(intent.session, intent.state, Number.isFinite(at) ? new Date(at).toISOString() : null, `bus: ${ev.type}`);
151
- metrics.hints++;
152
- } else if (intent.action === 'enqueue') {
153
- if (baseline) metrics.baseline_skipped++;
154
- else enqueue(intent);
155
- } else if (intent.reason === 'own_report') metrics.own_ignored++;
156
- else metrics.ignored++;
157
- store.seen.add(key);
158
- }
159
-
160
- // ── G1: the deploy lifecycle from the journal
161
- const DEPLOY_NOTE = (j, s, d = {}) =>
162
- ({
163
- pending: `deploy request #${j.deployId} waits for a person's ✅`,
164
- approved: `deploy #${j.deployId} approved by a person; waiting for the runner`,
165
- running: `deploy #${j.deployId} is running on the runner`,
166
- done: `deploy #${j.deployId} done (health ${d.health ?? '—'})`,
167
- failed: `deploy #${j.deployId} failed on the runner (exit ${d.exitCode ?? '?'}, health ${d.health ?? '—'}); see deploy_status`,
168
- rejected: `deploy request #${j.deployId} rejected by a person`,
169
- expired: `deploy request #${j.deployId} expired without an approval`,
170
- })[s];
171
-
172
- /** Move the job that follows deploy `d.id` to the status the deploy now has (event or poll). */
173
- function followDeploy(j, s, d = {}) {
174
- const want = DEPLOY_STATUS[s];
175
- store.jobs.update(j.id, { deployFactAt: now() });
176
- if (!want || (want === j.status && s === j.deployStatus)) return;
177
- setStatus(j, want, { deployStatus: s }, DEPLOY_NOTE(j, s, d));
178
- }
179
-
180
- function applyDeployEvent(it) {
181
- deployEventProjects.add(it.projectId);
182
- const jobs = store.jobs.all();
183
- const j = jobs.find((x) => x.deployId === it.deployId && x.projectId === it.projectId && LEASED.has(x.status));
184
- if (j) return followDeploy(j, it.status, { health: it.health, exitCode: it.exitCode });
185
- // IT-14: a request of the job's target made after the assignment, before the agent's result line names it
186
- if (it.event === 'deploy.requested' && it.target) {
187
- const at = serverTime(it.at);
188
- const c = jobs.find((x) => !x.deployId && x.lease && LEASED.has(x.status) && x.projectId === it.projectId && x.target === it.target && (!Number.isFinite(at) || at >= Date.parse(x.assignedAt ?? 0) - 60_000));
189
- if (c) store.jobs.update(c.id, { candidateDeployId: it.deployId }, `deploy request #${it.deployId} of ${it.target} seen in the journal`);
190
- }
191
- }
192
-
193
- // ── results of agents
194
- /** An agent's result for its job. Stale results (lease lost / another agent) change nothing. */
195
- function complete(jobId, result, { agentId = null } = {}) {
196
- const j = store.jobs.get(jobId);
197
- if (!j) return { ok: false, reason: 'unknown_job' };
198
- if (!LEASED.has(j.status) || !j.lease || (agentId && j.lease.agentId !== agentId) || j.deployId) {
199
- metrics.stale_results++;
200
- log.warn('stale result ignored', { job: jobId, agent: agentId, status: j.status });
201
- return { ok: false, reason: 'stale_result' };
202
- }
203
- const note = clip(result?.note ?? null, 300);
204
- const deployId = Number.isInteger(result?.deploy_id) ? result.deploy_id : result?.outcome === 'requested' && Number.isInteger(j.candidateDeployId) ? j.candidateDeployId : null;
205
- if (result?.outcome === 'requested' && deployId) {
206
- const n = setStatus(j, 'waiting_for_user', { lease: null, deployId, deployStatus: 'pending', deployFactAt: now(), result: { outcome: 'requested', note } }, `deploy request #${deployId} waits for a person's ✅${Number.isInteger(result.deploy_id) ? '' : ' (id from the journal)'}`);
207
- return { ok: true, job: n };
208
- }
209
- if (result?.outcome === 'not_needed') return { ok: true, job: setStatus(j, 'succeeded', { lease: null, result: { outcome: 'not_needed', note } }, note ?? 'no deploy needed') };
210
- const why = result?.outcome === 'requested' ? 'the agent said «requested» but gave no deploy id' : (note ?? 'the agent could not finish');
211
- return { ok: true, job: setStatus(j, 'blocked', { lease: null, result: { outcome: 'blocked', note } }, why) };
212
- }
213
-
214
- /** The output of an agent process → complete() through its ORCHESTRATOR_RESULT line. */
215
- function completeFromOutput(text, { agentId = null } = {}) {
216
- const r = parseResult(text);
217
- if (!r) return { ok: false, reason: 'no_result_line' };
218
- return complete(r.job, r, { agentId });
219
- }
220
-
221
- // ── the tick
222
- /** The agent did not finish the job (lease expired, live run timed out / crashed, hand-off refused): retry or fail. */
223
- function requeueOrFail(j, note) {
224
- if (j.handoffId && j.handoffProjectId) cancels.push({ projectId: j.handoffProjectId, handoffId: j.handoffId });
225
- const patch = { lease: null, agentId: null, handoffId: null, handoffProjectId: null, candidateDeployId: null };
226
- if (j.attempts >= config.maxAttempts) return setStatus(j, 'failed', patch, `${note} (attempt ${j.attempts}/${config.maxAttempts})`);
227
- return setStatus(j, 'queued', { ...patch, nextAttemptAt: now() + config.backoffMs * 2 ** Math.max(0, j.attempts - 1) }, `${note} (attempt ${j.attempts}/${config.maxAttempts})`);
228
- }
229
-
230
- function expireLeases() {
231
- for (const j of store.jobs.all()) {
232
- if (!LEASED.has(j.status) || !j.lease || j.lease.until > now()) continue;
233
- if (j.dispatchMode === 'live' && dispatcher?.busy(j.lease.agentId)) continue; // its own timeout (≤ lease) ends it
234
- metrics.lease_expired++;
235
- requeueOrFail(j, `lease of ${j.lease.agentId} expired without a result`);
236
- }
237
- }
238
-
239
- async function flushCancels() {
240
- while (cancels.length) {
241
- const c = cancels.shift();
242
- try {
243
- await api.cancelHandoff?.(c.projectId, c.handoffId);
244
- } catch (e) {
245
- log.warn('hand-off not cancelled', { handoff: c.handoffId, code: e.code ?? 'error' });
246
- }
247
- }
248
- }
249
-
250
- function syncLeasedWithAgents(raw) {
251
- for (const j of store.jobs.all()) {
252
- if (!LEASED.has(j.status) || !j.lease) continue;
253
- const a = raw.find((x) => x.id === j.lease.agentId);
254
- if (!a || !a.at || Date.parse(a.at) <= Date.parse(j.assignedAt ?? 0)) continue; // only facts NEWER than the assignment
255
- if (a.state === 'running' || a.state === 'waiting_for_user') {
256
- const want = a.state === 'running' ? 'running' : 'waiting_for_user';
257
- const lease = { ...j.lease, until: now() + config.leaseMs }; // the agent is alive: the lease is renewed
258
- if (j.status !== want) setStatus(j, want, { lease }, `agent ${a.id}: ${a.reason}`);
259
- else store.jobs.update(j.id, { lease });
260
- } else if (a.state === 'blocked') setStatus(j, 'blocked', { lease: null }, `agent ${a.id}: ${a.reason}`);
261
- }
262
- }
263
-
264
- async function pollDeploys() {
265
- for (const j of store.jobs.all()) {
266
- if (!j.deployId || !LEASED.has(j.status)) continue;
267
- // G1: the journal sends deploy.* for this project — poll only when no fact came for deployPollFallbackMs
268
- if (deployEventProjects.has(j.projectId) && now() - (j.deployFactAt ?? 0) < config.deployPollFallbackMs) continue;
269
- let d;
270
- try {
271
- metrics.deploy_polls++;
272
- d = await api.deploy(j.projectId, j.deployId);
273
- } catch (e) {
274
- metrics.deploy_poll_errors++;
275
- log.warn('deploy status unavailable', { job: j.id, deploy_id: j.deployId, code: e.code ?? 'error' });
276
- continue;
277
- }
278
- followDeploy(j, d?.status, { health: d?.health, exitCode: d?.exitCode });
279
- }
280
- }
281
-
282
- // ── stage 3: live runs and hand-offs
283
- /** The result of a live run (live.js onResult). Stale (another attempt / lease lost) changes nothing. */
284
- function onLiveResult(r) {
285
- metrics.live_finished++;
286
- const j = store.jobs.get(r.jobId);
287
- if (!j || !LEASED.has(j.status) || !j.lease || j.lease.agentId !== r.agentId || j.attempts !== r.attempt || j.deployId) {
288
- metrics.stale_results++;
289
- log.warn('stale live result ignored', { job: r.jobId, agent: r.agentId, attempt: r.attempt });
290
- return { ok: false, reason: 'stale_result' };
291
- }
292
- if (r.timedOut) {
293
- metrics.live_timeouts++;
294
- return { ok: true, job: requeueOrFail(j, `live run of ${r.agentId} timed out after ${Math.round(r.ms / 1000)} s and was stopped`) };
295
- }
296
- if (r.error) return { ok: true, job: requeueOrFail(j, `live run of ${r.agentId} could not start (${r.error})`) };
297
- if (stopping) return { ok: true, job: requeueOrFail(j, 'the orchestrator stopped during the live run') };
298
- const parsed = parseResult(r.text);
299
- if (parsed && parsed.job === j.id) return complete(j.id, parsed, { agentId: r.agentId });
300
- if (r.exitCode !== 0) return { ok: true, job: requeueOrFail(j, `live run of ${r.agentId} exited ${r.exitCode ?? r.signal ?? '?'} without a result line`) };
301
- return complete(j.id, { outcome: 'blocked', note: `the agent finished without a valid ${'ORCHESTRATOR_RESULT'} line for ${j.id}` }, { agentId: r.agentId });
302
- }
303
-
304
- /** Session slots (dispatch "handoff"): follow the hand-off; its result carries the ORCHESTRATOR_RESULT line. */
305
- async function pollHandoffs() {
306
- for (const j of store.jobs.all()) {
307
- if (!j.handoffId || !LEASED.has(j.status) || !j.lease || j.deployId) continue;
308
- let h;
309
- try {
310
- metrics.handoff_polls++;
311
- h = await api.getHandoff(j.handoffProjectId, j.handoffId);
312
- } catch (e) {
313
- metrics.handoff_poll_errors++;
314
- log.warn('hand-off status unavailable', { job: j.id, handoff: j.handoffId, code: e.code ?? 'error' });
315
- continue;
316
- }
317
- const st = h?.status;
318
- if (st === 'received' || st === 'in_progress') {
319
- const lease = { ...j.lease, until: now() + config.leaseMs }; // the session took it: alive
320
- if (j.status !== 'running') setStatus(j, 'running', { lease }, `hand-off #${j.handoffId} ${st} by the session`);
321
- else store.jobs.update(j.id, { lease });
322
- } else if (st === 'completed') {
323
- const parsed = parseResult(h.result ?? '');
324
- if (parsed && parsed.job === j.id) complete(j.id, parsed, { agentId: j.lease.agentId });
325
- else complete(j.id, { outcome: 'blocked', note: `hand-off #${j.handoffId} completed without a valid ORCHESTRATOR_RESULT line` }, { agentId: j.lease.agentId });
326
- } else if (st === 'failed' || st === 'cancelled') {
327
- complete(j.id, { outcome: 'blocked', note: `hand-off #${j.handoffId} ${st}${h.result ? `: ${clip(redact(h.result), 200)}` : ''}` }, { agentId: j.lease.agentId });
328
- }
329
- }
330
- }
331
-
332
- const slotOf = (id) => config.agents.find((a) => a.id === id) ?? null;
333
- /** How this slot is dispatched now: live / handoff only when configured AND possible here, else dry_run. */
334
- function modeOf(slot) {
335
- if (slot?.dispatch === 'live' && dispatcher) return 'live';
336
- if (slot?.dispatch === 'handoff' && api.handoff) return 'handoff';
337
- return 'dry_run';
338
- }
339
-
340
- async function schedule(snapshot) {
341
- const jobs = store.jobs.all();
342
- const locked = new Map(jobs.filter((j) => LOCKING.has(j.status)).map((j) => [j.lockKey, j.id]));
343
- const taken = new Set([...jobs.filter((j) => j.lease).map((j) => j.lease.agentId), ...(dispatcher?.list() ?? []).map((x) => x.agent)]); // a slot still running a process is never free
344
- const ready = jobs.filter((j) => j.status === 'queued' && (j.nextAttemptAt ?? 0) <= now()).sort((a, b) => b.priority - a.priority || Date.parse(a.createdAt) - Date.parse(b.createdAt) || Number(a.id.slice(1)) - Number(b.id.slice(1)));
345
- for (const j of ready) {
346
- if (locked.has(j.lockKey)) {
347
- if (j.waitReason !== `target busy (${locked.get(j.lockKey)})`) store.jobs.update(j.id, { waitReason: `target busy (${locked.get(j.lockKey)})` });
348
- continue;
349
- }
350
- const agent = pickAgent(snapshot, j, taken);
351
- if (!agent) {
352
- if (j.waitReason !== 'no free compatible agent') store.jobs.update(j.id, { waitReason: 'no free compatible agent' });
353
- continue;
354
- }
355
- const adapter = adapters[agent.provider];
356
- const slot = slotOf(agent.id) ?? agent;
357
- const mode = modeOf(slot);
358
- const attempt = j.attempts + 1;
359
- const plan = adapter.plan({ ...j, attempts: attempt }, { ...slot, ...agent, claudeBin: slot.claudeBin });
360
- if (bypassesPermissions(plan)) {
361
- metrics.refused++;
362
- setStatus(j, 'failed', { dispatchMode: mode }, `refused: the ${agent.provider} plan would bypass a permission gate`);
363
- continue;
364
- }
365
- if (mode === 'live') {
366
- const v = validateLivePlan(plan, slot);
367
- if (!v.ok) {
368
- metrics.refused++;
369
- metrics.live_refused++;
370
- setStatus(j, 'failed', { dispatchMode: mode }, `refused live run on ${agent.id}: ${v.reason}`);
371
- continue;
372
- }
373
- }
374
- store.dispatches.add({ at: iso(), job: j.id, agent: agent.id, attempt, dispatch: mode, dry_run: mode === 'dry_run', plan: { ...plan, prompt: clip(plan.prompt, 4000) } });
375
- let n = setStatus(j, 'assigned', { agentId: agent.id, attempts: attempt, assignedAt: iso(), dispatchMode: mode, lease: { agentId: agent.id, until: now() + config.leaseMs }, waitReason: null }, `${mode === 'dry_run' ? 'dry-run dispatch' : mode === 'live' ? 'live run' : 'hand-off'} to ${agent.id} (${plan.mode})`);
376
- metrics.dispatched++;
377
- locked.set(j.lockKey, j.id);
378
- taken.add(agent.id);
379
- if (mode === 'live') {
380
- const r = dispatcher.start({ job: n, agent: slot, plan, timeoutMs: Math.min(slot.timeoutMs ?? config.leaseMs, config.leaseMs) });
381
- if (r.ok) metrics.live_started++;
382
- else {
383
- metrics.live_refused++;
384
- requeueOrFail(store.jobs.get(n.id), `live run on ${agent.id} not started: ${r.reason}`);
385
- }
386
- } else if (mode === 'handoff') {
387
- const pid = slot.projects.includes(j.eventProjectId) ? j.eventProjectId : j.projectId;
388
- try {
389
- const h = await api.handoff(pid, { target_agent: slot.handoffAgent ?? slot.provider, title: clip(`DevOps job ${j.id}: ${j.kind} ${j.target} (${j.environment})`, 300), context: clip(plan.prompt, 19_000), idempotency_key: clip(`orc:${j.id}:a${attempt}`, 100) });
390
- if (!Number.isInteger(Number(h?.id))) throw Object.assign(new Error('no hand-off id'), { code: 'bad_answer' });
391
- n = store.jobs.update(n.id, { handoffId: Number(h.id), handoffProjectId: pid }, `hand-off #${h.id} → ${slot.handoffAgent ?? slot.provider}`);
392
- metrics.handoffs_created++;
393
- } catch (e) {
394
- requeueOrFail(store.jobs.get(n.id), `hand-off to ${agent.id} failed (${e.code ?? 'error'})`);
395
- }
396
- }
397
- }
398
- }
399
-
400
- async function tick() {
401
- try {
402
- expireLeases();
403
- await flushCancels();
404
- const raw = registry.snapshot(new Map());
405
- syncLeasedWithAgents(raw);
406
- await pollDeploys();
407
- await pollHandoffs();
408
- const leases = new Map(store.jobs.all().filter((j) => j.lease).map((j) => [j.lease.agentId, j.id]));
409
- lastSnapshot = registry.snapshot(leases);
410
- await schedule(lastSnapshot);
411
- await flushOutbox();
412
- } catch (e) {
413
- metrics.tick_errors++;
414
- lastError = { at: iso(), code: e.code ?? 'error', message: clip(redact(e.message ?? String(e)), 300) };
415
- log.error('tick failed', { code: lastError.code, error: lastError.message });
416
- }
417
- lastTickAt = iso();
418
- writeStatus();
419
- }
420
-
421
- function status() {
422
- const jobs = store.jobs.all();
423
- const counts = Object.fromEntries(JOB_STATUSES.map((s) => [s, jobs.filter((j) => j.status === s).length]));
424
- return {
425
- service: ORCHESTRATOR_NAME,
426
- state: stopping ? 'stopping' : startedAt ? 'running' : 'idle',
427
- dispatch: config.dispatch,
428
- started_at: startedAt,
429
- last_tick_at: lastTickAt,
430
- projects: deps.source?.status?.() ?? null,
431
- agents: lastSnapshot.map((a) => ({ id: a.id, provider: a.provider, mode: a.mode, dispatch: modeOf(slotOf(a.id)), state: a.state, reason: a.reason, session: a.session ?? null })),
432
- live: dispatcher?.list() ?? [],
433
- jobs: counts,
434
- active: jobs.filter((j) => !['succeeded', 'failed', 'cancelled'].includes(j.status)).map((j) => ({ id: j.id, status: j.status, kind: j.kind, target: j.target, environment: j.environment, agent: j.agentId, dispatch: j.dispatchMode ?? null, attempts: j.attempts, deploy_id: j.deployId, handoff_id: j.handoffId ?? null, wait: j.waitReason ?? null, signals: j.sources.length })),
435
- outbox: store.outbox.list().length,
436
- metrics: { ...metrics },
437
- last_error: lastError,
438
- };
439
- }
440
-
441
- function writeStatus() {
442
- try {
443
- const f = join(store.dir, 'status.json');
444
- writeFileSync(`${f}.tmp`, JSON.stringify(status(), null, 2), { mode: 0o600 });
445
- renameSync(`${f}.tmp`, f);
446
- } catch {
447
- /* diagnostics only */
448
- }
449
- }
450
-
451
- return {
452
- handle,
453
- enqueue,
454
- tick,
455
- complete,
456
- completeFromOutput,
457
- onLiveResult,
458
- status,
459
- metrics: () => ({ ...metrics }),
460
- async start() {
461
- startedAt = iso();
462
- const kept = store.jobs.all().filter((j) => LEASED.has(j.status));
463
- log.info('orchestrator started', { server: config.server, projects: config.projects, dispatch: config.dispatch, agents: config.agents.map((a) => a.id), state_dir: store.dir, recovered_jobs: kept.length });
464
- if (store.recoveredFromBrokenFile) log.warn('state.json was broken — started clean (the server journal and deploys are the truth)');
465
- // a live run of the previous process is gone (it was stopped with the service): retry it, do not wait for the lease
466
- for (const j of kept) if (j.dispatchMode === 'live' && j.lease && !j.deployId) requeueOrFail(j, 'the orchestrator restarted while the live run was in progress');
467
- deps.source?.start?.().catch?.((e) => log.error('event source failed to start', { code: e.code ?? 'error' }));
468
- loopDone = (async () => {
469
- while (!stopping) {
470
- await tick();
471
- if (!stopping) await sleep(config.pollMs, wake.signal);
472
- }
473
- })();
474
- await loopDone;
475
- writeStatus();
476
- deps.lock?.release();
477
- log.info('orchestrator stopped');
478
- },
479
- /** Graceful: stop the stream, finish the current tick, save; leased jobs stay leased (recovered by the next start). */
480
- async stop(reason = 'stop') {
481
- if (stopping) return loopDone;
482
- stopping = true;
483
- log.info('stopping', { reason });
484
- deps.source?.stop?.();
485
- wake.abort();
486
- await dispatcher?.stop?.();
487
- const t = setTimeout(() => log.warn('stop timeout'), config.stopTimeoutMs);
488
- t.unref?.();
489
- await loopDone;
490
- clearTimeout(t);
491
- return loopDone;
492
- },
493
- };
494
- }
@@ -1,28 +0,0 @@
1
- // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §9): the systemd USER unit of the
2
- // orchestrator as TEXT (`consilium-devops-orchestrator unit --print`). Nothing here installs or starts anything. A user
3
- // service: the orchestrator reads the turn-monitor state of the person's own workspaces and uses the person's sign-in.
4
- import { ORCHESTRATOR_NAME } from './config.js';
5
-
6
- export function orchestratorUnitText({ node = process.execPath, bin = '/usr/local/lib/node_modules/@consilium108/mcp-module-devops/bin/consilium-devops-orchestrator.js', configPath = `%h/.config/${ORCHESTRATOR_NAME}/config.json` } = {}) {
7
- return [
8
- '[Unit]',
9
- 'Description=Konsilium DevOps agent orchestrator (routes DevOps events to free local AI agents; never approves a deploy)',
10
- 'Documentation=https://www.npmjs.com/package/@consilium108/mcp-module-devops',
11
- 'After=network-online.target',
12
- 'Wants=network-online.target',
13
- '',
14
- '[Service]',
15
- 'Type=simple',
16
- `Environment=CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG=${configPath}`,
17
- `ExecStart=${node} ${bin} run`,
18
- 'Restart=on-failure',
19
- 'RestartSec=15',
20
- 'KillSignal=SIGTERM',
21
- 'TimeoutStopSec=60',
22
- 'NoNewPrivileges=true',
23
- '',
24
- '[Install]',
25
- 'WantedBy=default.target',
26
- '',
27
- ].join('\n');
28
- }