@consilium108/mcp-module-devops 1.3.0 → 1.4.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 +36 -0
- package/README.md +58 -56
- package/bin/consilium-devops-mcp.js +47 -3
- package/package.json +4 -4
- package/src/orchestrator/brief.js +46 -0
- package/src/orchestrator/config.js +29 -78
- package/src/orchestrator/events.js +5 -12
- package/src/orchestrator/index.js +9 -12
- package/src/orchestrator/producer.js +193 -0
- package/src/orchestrator/registry.js +16 -4
- package/src/standalone.js +9 -3
- package/bin/consilium-devops-orchestrator.js +0 -172
- package/src/orchestrator/adapters.js +0 -158
- package/src/orchestrator/api.js +0 -86
- package/src/orchestrator/daemon.js +0 -494
- package/src/orchestrator/install.js +0 -28
- package/src/orchestrator/live.js +0 -161
- package/src/orchestrator/source.js +0 -177
- package/src/orchestrator/store.js +0 -145
package/src/orchestrator/live.js
DELETED
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium SDD-P37-160 stage 3 (IT-13, IT-15; owner 2026-11-24 «Запускай
|
|
2
|
-
// все, добавь сразу»): the LIVE dispatcher — starts `claude -p` for a slot with dispatch "live" (mode headless, provider
|
|
3
|
-
// claude only), one job at a time per slot, in the slot's workspace, with a timeout (≤ the lease), and hands the result
|
|
4
|
-
// back to the orchestrator (→ complete → agent-events report). What it never does:
|
|
5
|
-
// • start anything validateLivePlan refuses (no bypass flag, only --permission-mode default, only the explicit
|
|
6
|
-
// --allowedTools list: DevOps MCP tools + read-only git; no shell: spawn without a shell, argv as given);
|
|
7
|
-
// • pass the service's whole environment (only LIVE_ENV_DEFAULT + the slot's env_pass names);
|
|
8
|
-
// • write a secret: the per-run log in <stateDir>/live/ keeps a masked tail of stdout / stderr only;
|
|
9
|
-
// • approve: the agent may only REQUEST a deploy (request_deploy); a person approves it with ✅.
|
|
10
|
-
import { spawn } from 'node:child_process';
|
|
11
|
-
import { mkdirSync, writeFileSync, renameSync } from 'node:fs';
|
|
12
|
-
import { join } from 'node:path';
|
|
13
|
-
import { LIVE_ENV_DEFAULT } from './config.js';
|
|
14
|
-
import { validateLivePlan } from './adapters.js';
|
|
15
|
-
import { redact } from '../runner/log.js';
|
|
16
|
-
|
|
17
|
-
const MAX_OUT = 1024 * 1024; // bytes of stdout kept for the result (the claude JSON); stderr: 64 KB
|
|
18
|
-
const LOG_TAIL = 16 * 1024;
|
|
19
|
-
const SECRETISH = [
|
|
20
|
-
/\b(ksk_[A-Za-z0-9]{4})[A-Za-z0-9_-]*/g,
|
|
21
|
-
/\b(sk-ant-[A-Za-z0-9]{2})[A-Za-z0-9_-]*/g,
|
|
22
|
-
/\b(gh[pousr]_[A-Za-z0-9]{2})[A-Za-z0-9]*/g,
|
|
23
|
-
/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,
|
|
24
|
-
/\b((?:[A-Z][A-Z0-9_]*_)?(?:TOKEN|SECRET|PASSWORD|API_KEY)\s*[=:]\s*)\S+/g,
|
|
25
|
-
];
|
|
26
|
-
/** The runner's redact + Konsilium keys, Anthropic keys, GitHub tokens, Bearer values, NAME_TOKEN=… assignments. */
|
|
27
|
-
export function maskSecrets(s) {
|
|
28
|
-
let out = redact(String(s ?? ''));
|
|
29
|
-
for (const re of SECRETISH) out = out.replace(re, (_m, keep) => `${keep}…`);
|
|
30
|
-
return out;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** `claude -p --output-format json` prints one JSON object with `result` (the final text); anything else → the raw text. */
|
|
34
|
-
export function resultTextOf(stdout) {
|
|
35
|
-
const t = String(stdout ?? '').trim();
|
|
36
|
-
for (const cand of [t, t.split('\n').filter(Boolean).at(-1) ?? '']) {
|
|
37
|
-
try {
|
|
38
|
-
const j = JSON.parse(cand);
|
|
39
|
-
if (j && typeof j.result === 'string') return { text: j.result, isError: j.is_error === true || j.subtype === 'error', format: 'json' };
|
|
40
|
-
} catch {}
|
|
41
|
-
}
|
|
42
|
-
return { text: t, isError: false, format: 'text' };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** The environment of a live run: only the named variables (default list + the slot's env_pass), never the whole env. */
|
|
46
|
-
export function liveEnvOf(env, agent, jobId) {
|
|
47
|
-
const names = new Set([...LIVE_ENV_DEFAULT, ...(agent?.envPass ?? [])]);
|
|
48
|
-
const out = {};
|
|
49
|
-
for (const n of names) if (env[n] != null) out[n] = env[n];
|
|
50
|
-
out.KONSILIUM_ORCHESTRATOR_JOB = String(jobId);
|
|
51
|
-
return out;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* @param {{ onResult: (r: { jobId: string, agentId: string, attempt: number, exitCode: number|null, signal: string|null,
|
|
56
|
-
* timedOut: boolean, text: string, isError: boolean, error: string|null, ms: number }) => void, logDir: string,
|
|
57
|
-
* spawnImpl?: typeof spawn, env?: object, log?: object, now?: () => number, killGraceMs?: number }} o
|
|
58
|
-
*/
|
|
59
|
-
export function createLiveDispatcher(o) {
|
|
60
|
-
const spawnImpl = o.spawnImpl ?? spawn;
|
|
61
|
-
const env = o.env ?? process.env;
|
|
62
|
-
const log = o.log ?? { info() {}, warn() {}, error() {} };
|
|
63
|
-
const now = o.now ?? Date.now;
|
|
64
|
-
const grace = o.killGraceMs ?? 5000;
|
|
65
|
-
const running = new Map(); // agentId → { jobId, attempt, child, startedAt, timer, done }
|
|
66
|
-
|
|
67
|
-
function writeLog(jobId, attempt, rec) {
|
|
68
|
-
try {
|
|
69
|
-
mkdirSync(o.logDir, { recursive: true, mode: 0o700 });
|
|
70
|
-
const f = join(o.logDir, `${jobId}-a${attempt}.json`);
|
|
71
|
-
writeFileSync(`${f}.tmp`, JSON.stringify(rec, null, 2), { mode: 0o600 });
|
|
72
|
-
renameSync(`${f}.tmp`, f);
|
|
73
|
-
} catch {
|
|
74
|
-
/* diagnostics only */
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** → { ok: true } | { ok: false, reason } (nothing started). */
|
|
79
|
-
function start({ job, agent, plan, timeoutMs }) {
|
|
80
|
-
if (running.has(agent.id)) return { ok: false, reason: `slot ${agent.id} already runs ${running.get(agent.id).jobId}` };
|
|
81
|
-
const v = validateLivePlan(plan, agent);
|
|
82
|
-
if (!v.ok) return v;
|
|
83
|
-
const attempt = job.attempts;
|
|
84
|
-
const startedAt = now();
|
|
85
|
-
let child;
|
|
86
|
-
try {
|
|
87
|
-
child = spawnImpl(plan.argv[0], plan.argv.slice(1), { cwd: plan.cwd, env: liveEnvOf(env, agent, job.id), stdio: ['ignore', 'pipe', 'pipe'], shell: false, windowsHide: true });
|
|
88
|
-
} catch (e) {
|
|
89
|
-
return { ok: false, reason: `could not start ${plan.argv[0]}: ${e?.code ?? e?.message ?? 'error'}` };
|
|
90
|
-
}
|
|
91
|
-
const r = { jobId: job.id, attempt, child, startedAt, timedOut: false, out: [], outLen: 0, err: '', settled: false };
|
|
92
|
-
running.set(agent.id, r);
|
|
93
|
-
child.stdout?.on('data', (c) => {
|
|
94
|
-
if (r.outLen < MAX_OUT) {
|
|
95
|
-
r.out.push(c);
|
|
96
|
-
r.outLen += c.length;
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
child.stderr?.on('data', (c) => {
|
|
100
|
-
if (r.err.length < 65536) r.err += c.toString('utf8');
|
|
101
|
-
});
|
|
102
|
-
const kill = (sig) => {
|
|
103
|
-
try {
|
|
104
|
-
child.kill(sig);
|
|
105
|
-
} catch {}
|
|
106
|
-
};
|
|
107
|
-
r.timer = setTimeout(() => {
|
|
108
|
-
r.timedOut = true;
|
|
109
|
-
log.warn('live run timed out — stopping it', { job: job.id, agent: agent.id, timeout_ms: timeoutMs });
|
|
110
|
-
kill('SIGTERM');
|
|
111
|
-
r.killTimer = setTimeout(() => kill('SIGKILL'), grace);
|
|
112
|
-
r.killTimer.unref?.();
|
|
113
|
-
}, timeoutMs);
|
|
114
|
-
r.timer.unref?.();
|
|
115
|
-
const finish = (exitCode, signal, error = null) => {
|
|
116
|
-
if (r.settled) return;
|
|
117
|
-
r.settled = true;
|
|
118
|
-
clearTimeout(r.timer);
|
|
119
|
-
clearTimeout(r.killTimer);
|
|
120
|
-
running.delete(agent.id);
|
|
121
|
-
const stdout = Buffer.concat(r.out).toString('utf8');
|
|
122
|
-
const res = resultTextOf(stdout);
|
|
123
|
-
const ms = now() - startedAt;
|
|
124
|
-
writeLog(job.id, attempt, { job: job.id, agent: agent.id, attempt, started_at: new Date(startedAt).toISOString(), ms, exit_code: exitCode, signal, timed_out: r.timedOut, error, argv: [plan.argv[0], '-p', '<prompt: konsilium.devops-job/1>', ...plan.argv.slice(3)], cwd: plan.cwd, env_names: Object.keys(liveEnvOf(env, agent, job.id)).sort(), result_tail: maskSecrets(res.text.slice(-LOG_TAIL)), stderr_tail: maskSecrets(r.err.slice(-LOG_TAIL)) });
|
|
125
|
-
log.info('live run finished', { job: job.id, agent: agent.id, exit_code: exitCode, signal, timed_out: r.timedOut, ms });
|
|
126
|
-
r.resolve?.();
|
|
127
|
-
try {
|
|
128
|
-
o.onResult({ jobId: job.id, agentId: agent.id, attempt, exitCode, signal, timedOut: r.timedOut, text: res.text, isError: res.isError, error, ms });
|
|
129
|
-
} catch (e) {
|
|
130
|
-
log.error('live result handler failed', { job: job.id, error: maskSecrets(e?.message ?? e) });
|
|
131
|
-
}
|
|
132
|
-
};
|
|
133
|
-
r.done = new Promise((res) => (r.resolve = res));
|
|
134
|
-
child.on('error', (e) => finish(null, null, `spawn ${e?.code ?? 'error'}`));
|
|
135
|
-
child.on('close', (code, signal) => finish(code, signal));
|
|
136
|
-
log.info('live run started', { job: job.id, agent: agent.id, attempt, cwd: plan.cwd, pid: child.pid ?? null, timeout_ms: timeoutMs });
|
|
137
|
-
return { ok: true, pid: child.pid ?? null };
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
return {
|
|
141
|
-
start,
|
|
142
|
-
busy: (agentId) => running.has(agentId),
|
|
143
|
-
list: () => [...running.entries()].map(([agent, r]) => ({ agent, job: r.jobId, attempt: r.attempt, pid: r.child.pid ?? null, started_at: new Date(r.startedAt).toISOString() })),
|
|
144
|
-
/** Graceful stop of the service: SIGTERM every run (SIGKILL after the grace), wait for them. Their leases stay. */
|
|
145
|
-
async stop() {
|
|
146
|
-
const all = [...running.values()];
|
|
147
|
-
for (const r of all) {
|
|
148
|
-
try {
|
|
149
|
-
r.child.kill('SIGTERM');
|
|
150
|
-
} catch {}
|
|
151
|
-
const t = setTimeout(() => {
|
|
152
|
-
try {
|
|
153
|
-
r.child.kill('SIGKILL');
|
|
154
|
-
} catch {}
|
|
155
|
-
}, grace);
|
|
156
|
-
t.unref?.();
|
|
157
|
-
}
|
|
158
|
-
await Promise.all(all.map((r) => r.done));
|
|
159
|
-
},
|
|
160
|
-
};
|
|
161
|
-
}
|
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §3.3): the event source — the
|
|
2
|
-
// SAME delivery as the local MCP sync (#437), no new transport: per project
|
|
3
|
-
// • catch-up through get_events from the stored cursor (start, a heartbeat head beyond the cursor, cursor_expired);
|
|
4
|
-
// • then the SSE stream projectEvents (types agent.* and deploy.* — G1) via subscribeSse of @nativemind108/mcp;
|
|
5
|
-
// • the long poll of get_events (wait_seconds 25) when no SSE is given or the server answers 404/400 (subscriptions off).
|
|
6
|
-
// The cursor moves only AFTER the event was handled (at-least-once); duplicates are dropped by the caller's seen set.
|
|
7
|
-
// First start without a cursor: the journal (last 7 days) is read as a BASELINE — the cursor moves to its head, state
|
|
8
|
-
// hints are kept, nothing is enqueued (old DEPLOY_REQUIRED signals never start work).
|
|
9
|
-
import { normalizeBusEvent } from './events.js';
|
|
10
|
-
|
|
11
|
-
const backoff = (n) => Math.min(60_000, 1000 * 2 ** Math.min(n, 6));
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* @param {{ api: object, store: object, projects: number[], handle: (ev: object, o: { baseline: boolean }) => Promise<void>,
|
|
15
|
-
* types?: string[], log?: object, sleep?: (ms: number, signal?: AbortSignal) => Promise<void>, sse?: boolean,
|
|
16
|
-
* pollWaitSec?: number }} o
|
|
17
|
-
*/
|
|
18
|
-
export function createEventSource(o) {
|
|
19
|
-
const log = o.log ?? {};
|
|
20
|
-
const types = o.types ?? ['agent.', 'deploy.']; // deploy.*: G1 (2026-11-24) — the deploy lifecycle instead of polling
|
|
21
|
-
const sleep = o.sleep ?? ((ms, signal) => new Promise((r) => {
|
|
22
|
-
const t = setTimeout(r, ms);
|
|
23
|
-
signal?.addEventListener('abort', () => (clearTimeout(t), r()), { once: true });
|
|
24
|
-
}));
|
|
25
|
-
const stop = new AbortController();
|
|
26
|
-
const per = new Map(); // pid → { transport, state, error, lastEventAt, events, sub }
|
|
27
|
-
const st = (pid) => {
|
|
28
|
-
if (!per.has(pid)) per.set(pid, { transport: null, state: 'stopped', error: null, lastEventAt: null, events: 0, sub: null, polling: false, notFound: 0 });
|
|
29
|
-
return per.get(pid);
|
|
30
|
-
};
|
|
31
|
-
const chains = new Map(); // pid → a promise chain: events of one project are handled one at a time, in order
|
|
32
|
-
|
|
33
|
-
function serial(pid, fn) {
|
|
34
|
-
const prev = chains.get(pid) ?? Promise.resolve();
|
|
35
|
-
const next = prev.then(fn, fn);
|
|
36
|
-
chains.set(pid, next.catch(() => {}));
|
|
37
|
-
return next;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async function handleRaw(pid, raw, baseline = false, moveCursor = true) {
|
|
41
|
-
const ev = normalizeBusEvent(raw);
|
|
42
|
-
if (!ev) return;
|
|
43
|
-
// an event behind the cursor (a replayed / duplicated delivery) still goes to the handler: its seen set drops it
|
|
44
|
-
await o.handle({ ...ev, projectId: ev.projectId ?? pid }, { baseline });
|
|
45
|
-
const s = st(pid);
|
|
46
|
-
s.lastEventAt = new Date().toISOString();
|
|
47
|
-
s.events++;
|
|
48
|
-
if (moveCursor) o.store.cursor.set(pid, ev.cursor);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** An SSE event is a doorbell: the journal is read from the cursor (so a gap — a lost message — is read too). If the
|
|
52
|
-
* journal is unreachable, the pushed event is handled now WITHOUT moving the cursor (the next catch-up re-reads it). */
|
|
53
|
-
async function onPushed(pid, raw) {
|
|
54
|
-
try {
|
|
55
|
-
await catchUpNow(pid);
|
|
56
|
-
} catch (e) {
|
|
57
|
-
st(pid).error = e?.code ?? e?.message;
|
|
58
|
-
await serial(pid, () => handleRaw(pid, raw, false, false));
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** Read the journal after the stored cursor, in pages, oldest first. */
|
|
63
|
-
function catchUpNow(pid) {
|
|
64
|
-
return serial(pid, async () => {
|
|
65
|
-
const baseline = o.store.cursor.get(pid) == null;
|
|
66
|
-
let cursor = o.store.cursor.get(pid) ?? 0;
|
|
67
|
-
for (let i = 0; i < 100; i++) {
|
|
68
|
-
const r = await o.api.events(pid, cursor, { waitSeconds: 0, limit: 200, types });
|
|
69
|
-
const evs = r?.events ?? [];
|
|
70
|
-
for (const e of evs) await handleRaw(pid, e, baseline);
|
|
71
|
-
const next = Number(r?.next_cursor ?? cursor);
|
|
72
|
-
if (!evs.length || next <= cursor) {
|
|
73
|
-
if (Number.isFinite(next)) o.store.cursor.set(pid, Math.max(next, 1));
|
|
74
|
-
break;
|
|
75
|
-
}
|
|
76
|
-
cursor = next;
|
|
77
|
-
}
|
|
78
|
-
if (baseline && o.store.cursor.get(pid) == null) o.store.cursor.set(pid, 1);
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
const catchUp = catchUpNow;
|
|
82
|
-
|
|
83
|
-
async function pollLoop(pid) {
|
|
84
|
-
const s = st(pid);
|
|
85
|
-
if (s.polling) return;
|
|
86
|
-
s.polling = true;
|
|
87
|
-
s.transport = 'get_events';
|
|
88
|
-
let attempt = 0;
|
|
89
|
-
while (!stop.signal.aborted) {
|
|
90
|
-
try {
|
|
91
|
-
const got = await serial(pid, async () => {
|
|
92
|
-
const r = await o.api.events(pid, o.store.cursor.get(pid) ?? 0, { waitSeconds: o.pollWaitSec ?? 25, limit: 200, types });
|
|
93
|
-
for (const e of r?.events ?? []) {
|
|
94
|
-
if (stop.signal.aborted) break;
|
|
95
|
-
await handleRaw(pid, e);
|
|
96
|
-
}
|
|
97
|
-
if (!(r?.events ?? []).length && r?.next_cursor != null) o.store.cursor.set(pid, Number(r.next_cursor));
|
|
98
|
-
return (r?.events ?? []).length;
|
|
99
|
-
});
|
|
100
|
-
s.state = 'open';
|
|
101
|
-
s.error = null;
|
|
102
|
-
attempt = 0;
|
|
103
|
-
// an empty answer that came back at once (a server without the long poll): never spin
|
|
104
|
-
if (!got) await sleep(o.pollIdleMs ?? 1000, stop.signal);
|
|
105
|
-
} catch (e) {
|
|
106
|
-
s.error = e?.code ?? e?.message ?? String(e);
|
|
107
|
-
if (e?.status === 401 || e?.code === 'auth_required') {
|
|
108
|
-
s.state = 'auth_required';
|
|
109
|
-
log.error?.('event source: no valid credential', { project_id: pid, code: s.error });
|
|
110
|
-
await sleep(60_000, stop.signal);
|
|
111
|
-
continue;
|
|
112
|
-
}
|
|
113
|
-
s.state = 'retrying';
|
|
114
|
-
log.warn?.('event source: get_events failed, retrying', { project_id: pid, code: s.error });
|
|
115
|
-
await sleep(backoff(attempt++), stop.signal);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
s.polling = false;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
function subscribe(pid) {
|
|
122
|
-
const s = st(pid);
|
|
123
|
-
s.transport = 'sse';
|
|
124
|
-
s.sub = o.api.subscribe({
|
|
125
|
-
projectId: pid,
|
|
126
|
-
types,
|
|
127
|
-
getCursor: () => o.store.cursor.get(pid),
|
|
128
|
-
cursorOf: (r) => Number(r?.data?.projectEvents?.cursor ?? NaN),
|
|
129
|
-
onEvent: async (r) => onPushed(pid, r?.data?.projectEvents),
|
|
130
|
-
onHeadAhead: async () => catchUp(pid),
|
|
131
|
-
onCursorExpired: async () => catchUp(pid),
|
|
132
|
-
onState: (state, info) => {
|
|
133
|
-
s.state = state;
|
|
134
|
-
if (info?.error) s.error = info.error;
|
|
135
|
-
if (state === 'open') {
|
|
136
|
-
s.error = null;
|
|
137
|
-
s.notFound = 0;
|
|
138
|
-
}
|
|
139
|
-
if (state === 'retrying' && (info?.status === 404 || info?.status === 400) && ++s.notFound >= 2 && !stop.signal.aborted) {
|
|
140
|
-
s.sub?.close();
|
|
141
|
-
s.sub = null;
|
|
142
|
-
log.warn?.('event source: no SSE subscriptions on the server — long poll of get_events', { project_id: pid });
|
|
143
|
-
void pollLoop(pid);
|
|
144
|
-
}
|
|
145
|
-
},
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
return {
|
|
150
|
-
catchUp,
|
|
151
|
-
onPushed,
|
|
152
|
-
async start() {
|
|
153
|
-
for (const pid of o.projects) {
|
|
154
|
-
try {
|
|
155
|
-
await catchUp(pid);
|
|
156
|
-
} catch (e) {
|
|
157
|
-
st(pid).error = e?.code ?? e?.message;
|
|
158
|
-
log.warn?.('event source: first catch-up failed (retried by the poll / stream)', { project_id: pid, code: st(pid).error });
|
|
159
|
-
}
|
|
160
|
-
if (o.sse !== false && o.api.subscribe) subscribe(pid);
|
|
161
|
-
else void pollLoop(pid);
|
|
162
|
-
}
|
|
163
|
-
},
|
|
164
|
-
stop() {
|
|
165
|
-
stop.abort();
|
|
166
|
-
for (const s of per.values()) {
|
|
167
|
-
s.sub?.close();
|
|
168
|
-
s.sub = null;
|
|
169
|
-
s.state = 'stopped';
|
|
170
|
-
}
|
|
171
|
-
},
|
|
172
|
-
status: () => Object.fromEntries(o.projects.map((pid) => {
|
|
173
|
-
const s = st(pid);
|
|
174
|
-
return [pid, { cursor: o.store.cursor.get(pid), transport: s.transport, state: s.state, error: s.error, last_event_at: s.lastEventAt, events: s.events }];
|
|
175
|
-
})),
|
|
176
|
-
};
|
|
177
|
-
}
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §6): the orchestrator's durable
|
|
2
|
-
// local state — ONE file state.json (tmp + rename after every change, 0600 in a 0700 directory) with
|
|
3
|
-
// cursors per project: the last event of get_events / SSE handled (saved AFTER the event was handled: at-least-once)
|
|
4
|
-
// seen dedup keys of handled events (p<project>:e<event id>) → time; pruned (30 days, at most 5000)
|
|
5
|
-
// jobs the queue: every job with its status, lock key, lease, attempts, sources and history
|
|
6
|
-
// outbox reports to Konsilium not delivered yet (retried with backoff; idempotent on the server)
|
|
7
|
-
// dispatches the last dry-run dispatch plans (what would have been started)
|
|
8
|
-
// The server stays the source of truth for tasks, deploy requests and approvals; this file only coordinates local agents.
|
|
9
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
10
|
-
import { join } from 'node:path';
|
|
11
|
-
|
|
12
|
-
const SEEN_MAX = 5000;
|
|
13
|
-
const SEEN_TTL_MS = 30 * 24 * 3600_000;
|
|
14
|
-
const KEEP_FINISHED = 200;
|
|
15
|
-
const KEEP_DISPATCHES = 50;
|
|
16
|
-
const KEEP_HISTORY = 30;
|
|
17
|
-
|
|
18
|
-
export const JOB_STATUSES = ['queued', 'assigned', 'running', 'waiting_for_user', 'blocked', 'succeeded', 'failed', 'cancelled'];
|
|
19
|
-
/** Statuses that hold the lock of a target (one deploy-related job per project + environment + target at a time). */
|
|
20
|
-
export const LOCKING = new Set(['assigned', 'running', 'waiting_for_user']);
|
|
21
|
-
export const FINISHED = new Set(['succeeded', 'failed', 'cancelled', 'blocked']);
|
|
22
|
-
|
|
23
|
-
const empty = () => ({ version: 1, seq: 0, cursors: {}, seen: {}, jobs: [], outbox: [], dispatches: [] });
|
|
24
|
-
|
|
25
|
-
/** @param {{ dir: string, now?: () => number }} o */
|
|
26
|
-
export function createOrchestratorStore({ dir, now = Date.now }) {
|
|
27
|
-
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
28
|
-
const file = join(dir, 'state.json');
|
|
29
|
-
let s = empty();
|
|
30
|
-
let broken = false;
|
|
31
|
-
if (existsSync(file)) {
|
|
32
|
-
try {
|
|
33
|
-
s = { ...empty(), ...JSON.parse(readFileSync(file, 'utf8')) };
|
|
34
|
-
} catch {
|
|
35
|
-
broken = true; // a broken file: start clean (events are re-read from the server journal; deploys are on the server)
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
const save = () => {
|
|
39
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
40
|
-
writeFileSync(tmp, JSON.stringify(s), { mode: 0o600 });
|
|
41
|
-
renameSync(tmp, file);
|
|
42
|
-
};
|
|
43
|
-
const iso = (t = now()) => new Date(t).toISOString();
|
|
44
|
-
const find = (id) => s.jobs.find((j) => j.id === id) ?? null;
|
|
45
|
-
|
|
46
|
-
function prune() {
|
|
47
|
-
const cut = now() - SEEN_TTL_MS;
|
|
48
|
-
let entries = Object.entries(s.seen).filter(([, t]) => t >= cut);
|
|
49
|
-
if (entries.length > SEEN_MAX) entries = entries.sort((a, b) => b[1] - a[1]).slice(0, SEEN_MAX);
|
|
50
|
-
s.seen = Object.fromEntries(entries);
|
|
51
|
-
const done = s.jobs.filter((j) => FINISHED.has(j.status));
|
|
52
|
-
if (done.length > KEEP_FINISHED) {
|
|
53
|
-
const drop = new Set(done.sort((a, b) => Date.parse(a.updatedAt) - Date.parse(b.updatedAt)).slice(0, done.length - KEEP_FINISHED).map((j) => j.id));
|
|
54
|
-
s.jobs = s.jobs.filter((j) => !drop.has(j.id));
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
return {
|
|
59
|
-
file,
|
|
60
|
-
dir,
|
|
61
|
-
recoveredFromBrokenFile: broken,
|
|
62
|
-
snapshot: () => JSON.parse(JSON.stringify(s)),
|
|
63
|
-
cursor: {
|
|
64
|
-
get: (pid) => (s.cursors[pid] ?? null),
|
|
65
|
-
set(pid, c) {
|
|
66
|
-
if (Number.isFinite(c) && c > (s.cursors[pid] ?? 0)) {
|
|
67
|
-
s.cursors[pid] = c;
|
|
68
|
-
save();
|
|
69
|
-
}
|
|
70
|
-
},
|
|
71
|
-
},
|
|
72
|
-
seen: {
|
|
73
|
-
has: (key) => !!s.seen[key],
|
|
74
|
-
add(key) {
|
|
75
|
-
if (s.seen[key]) return false;
|
|
76
|
-
s.seen[key] = now();
|
|
77
|
-
if (Object.keys(s.seen).length > SEEN_MAX * 1.1) prune();
|
|
78
|
-
save();
|
|
79
|
-
return true;
|
|
80
|
-
},
|
|
81
|
-
},
|
|
82
|
-
jobs: {
|
|
83
|
-
all: () => s.jobs.map((j) => ({ ...j })),
|
|
84
|
-
get: (id) => {
|
|
85
|
-
const j = find(id);
|
|
86
|
-
return j ? JSON.parse(JSON.stringify(j)) : null;
|
|
87
|
-
},
|
|
88
|
-
byIdempotency: (key) => s.jobs.find((j) => j.idempotencyKey === key) ?? null,
|
|
89
|
-
create(job) {
|
|
90
|
-
const id = `J${++s.seq}`;
|
|
91
|
-
const at = iso();
|
|
92
|
-
const j = { id, status: 'queued', attempts: 0, nextAttemptAt: 0, lease: null, agentId: null, deployId: null, deployStatus: null, result: null, createdAt: at, updatedAt: at, history: [{ at, status: 'queued', note: job.note ?? 'created' }], ...job };
|
|
93
|
-
delete j.note;
|
|
94
|
-
s.jobs.push(j);
|
|
95
|
-
save();
|
|
96
|
-
return { ...j };
|
|
97
|
-
},
|
|
98
|
-
/** patch + optional status change (recorded in history). */
|
|
99
|
-
update(id, patch = {}, note = null) {
|
|
100
|
-
const j = find(id);
|
|
101
|
-
if (!j) return null;
|
|
102
|
-
const prev = j.status;
|
|
103
|
-
Object.assign(j, patch);
|
|
104
|
-
j.updatedAt = iso();
|
|
105
|
-
if ((patch.status && patch.status !== prev) || note) j.history = [...j.history, { at: j.updatedAt, status: j.status, note: note ?? null }].slice(-KEEP_HISTORY);
|
|
106
|
-
if (FINISHED.has(j.status)) prune();
|
|
107
|
-
save();
|
|
108
|
-
return { ...j };
|
|
109
|
-
},
|
|
110
|
-
addSource(id, src) {
|
|
111
|
-
const j = find(id);
|
|
112
|
-
if (!j) return null;
|
|
113
|
-
if (!j.sources.some((x) => x.project_id === src.project_id && x.event_id === src.event_id)) j.sources = [...j.sources, src].slice(-20);
|
|
114
|
-
j.updatedAt = iso();
|
|
115
|
-
save();
|
|
116
|
-
return { ...j };
|
|
117
|
-
},
|
|
118
|
-
},
|
|
119
|
-
outbox: {
|
|
120
|
-
list: () => s.outbox.map((o) => ({ ...o })),
|
|
121
|
-
add(item) {
|
|
122
|
-
if (s.outbox.some((o) => o.id === item.id)) return false;
|
|
123
|
-
s.outbox.push({ attempts: 0, nextAt: 0, ...item });
|
|
124
|
-
save();
|
|
125
|
-
return true;
|
|
126
|
-
},
|
|
127
|
-
update(id, patch) {
|
|
128
|
-
const o = s.outbox.find((x) => x.id === id);
|
|
129
|
-
if (o) Object.assign(o, patch);
|
|
130
|
-
save();
|
|
131
|
-
},
|
|
132
|
-
remove(id) {
|
|
133
|
-
s.outbox = s.outbox.filter((x) => x.id !== id);
|
|
134
|
-
save();
|
|
135
|
-
},
|
|
136
|
-
},
|
|
137
|
-
dispatches: {
|
|
138
|
-
list: () => s.dispatches.map((d) => ({ ...d })),
|
|
139
|
-
add(d) {
|
|
140
|
-
s.dispatches = [...s.dispatches, d].slice(-KEEP_DISPATCHES);
|
|
141
|
-
save();
|
|
142
|
-
},
|
|
143
|
-
},
|
|
144
|
-
};
|
|
145
|
-
}
|