@consilium108/mcp-module-devops 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/README.md +63 -0
- package/bin/consilium-devops-orchestrator.js +172 -0
- package/package.json +6 -4
- package/src/orchestrator/adapters.js +158 -0
- package/src/orchestrator/api.js +86 -0
- package/src/orchestrator/config.js +164 -0
- package/src/orchestrator/daemon.js +494 -0
- package/src/orchestrator/events.js +91 -0
- package/src/orchestrator/index.js +13 -0
- package/src/orchestrator/install.js +28 -0
- package/src/orchestrator/live.js +161 -0
- package/src/orchestrator/registry.js +150 -0
- package/src/orchestrator/source.js +177 -0
- package/src/orchestrator/store.js +145 -0
- package/src/runner/state.js +4 -4
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §4): the orchestrator's config.
|
|
2
|
+
// It holds NO secret: the Konsilium credential comes from KONSILIUM_API_KEY or the `@consilium108/mcp login` sign-in (as
|
|
3
|
+
// in the DevOps MCP). Location: $CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG, else ~/.config/consilium-devops-orchestrator/
|
|
4
|
+
// config.json, else /etc/consilium-devops-orchestrator/config.json. Validation refuses anything that could approve or
|
|
5
|
+
// start a production deploy on its own. The global dispatch stays "dry_run"; stage 3 (2026-11-24, owner «Запускай все»)
|
|
6
|
+
// turns starting agents on PER SLOT only: agents[].dispatch "live" (mode headless + provider claude: `claude -p` with the
|
|
7
|
+
// default permission mode and an explicit tool list) or "handoff" (mode session: create_handoff into that session).
|
|
8
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { homedir } from 'node:os';
|
|
10
|
+
import { dirname, join, resolve } from 'node:path';
|
|
11
|
+
import { DevopsMcpError } from '../errors.js';
|
|
12
|
+
import { DEFAULT_SERVER } from '../runner/config.js';
|
|
13
|
+
|
|
14
|
+
export const ORCHESTRATOR_NAME = 'consilium-devops-orchestrator';
|
|
15
|
+
/** The provider name of the orchestrator's own reports (agent events); its own events are never consumed again. */
|
|
16
|
+
export const ORCHESTRATOR_PROVIDER = 'devops-orchestrator';
|
|
17
|
+
/** Idempotency-key prefix of its own reports; the server stores it as content_hash «tm:orc:…». */
|
|
18
|
+
export const OWN_KEY_PREFIX = 'orc:';
|
|
19
|
+
export const JOB_KINDS = ['deploy_check'];
|
|
20
|
+
export const DISPATCH_MODES = ['dry_run'];
|
|
21
|
+
/** Per agent slot (stage 3): dry_run (default) · live (headless claude only) · handoff (session slots only). */
|
|
22
|
+
export const SLOT_DISPATCH = ['dry_run', 'live', 'handoff'];
|
|
23
|
+
/** Environment variables a live run inherits by default (names only; values never logged). Anything else is dropped. */
|
|
24
|
+
export const LIVE_ENV_DEFAULT = ['PATH', 'HOME', 'USER', 'LOGNAME', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'TMPDIR', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'XDG_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR', 'ANTHROPIC_API_KEY', 'KONSILIUM_API_KEY', 'KONSILIUM_API_URL'];
|
|
25
|
+
export const AGENT_MODES = ['session', 'headless'];
|
|
26
|
+
|
|
27
|
+
const expandHome = (p, home) => (p && p.startsWith('~/') ? join(home, p.slice(2)) : p);
|
|
28
|
+
|
|
29
|
+
export function orchestratorConfigCandidates(env = process.env, home = homedir()) {
|
|
30
|
+
if (env.CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG) return [env.CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG];
|
|
31
|
+
const xdg = env.XDG_CONFIG_HOME || join(home, '.config');
|
|
32
|
+
return [join(xdg, ORCHESTRATOR_NAME, 'config.json'), `/etc/${ORCHESTRATOR_NAME}/config.json`];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const bad = (msg) => new DevopsMcpError('config_invalid', msg);
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Normalizes and validates a raw config object (already parsed). Throws config_invalid with the reason.
|
|
39
|
+
* → { file, server, projects, stateDir, pollMs, leaseMs, maxAttempts, backoffMs, dispatch, report, reportDryRun,
|
|
40
|
+
* logFormat, targets, routes, agents, stopTimeoutMs, idleTtlMs }
|
|
41
|
+
*/
|
|
42
|
+
export function normalizeOrchestratorConfig(raw, { file = null, env = process.env, home = homedir() } = {}) {
|
|
43
|
+
if (!raw || typeof raw !== 'object') throw bad('the config must be a JSON object');
|
|
44
|
+
const base = file ? dirname(file) : process.cwd();
|
|
45
|
+
if ('token' in raw || 'apiKey' in raw || 'tokenFile' in raw) throw bad('the orchestrator config holds no credential: use KONSILIUM_API_KEY or `npx @consilium108/mcp login`');
|
|
46
|
+
const dispatch = raw.dispatch ?? 'dry_run';
|
|
47
|
+
if (!DISPATCH_MODES.includes(dispatch)) throw bad(`dispatch «${dispatch}» is not available globally (the global dispatch stays ${DISPATCH_MODES.join(', ')}); start agents per slot: agents[].dispatch "live" (mode headless, provider claude) or "handoff" (mode session)`);
|
|
48
|
+
const leaseMs = Number(raw.leaseMs) || 30 * 60_000;
|
|
49
|
+
const targets = {};
|
|
50
|
+
for (const [key, t] of Object.entries(raw.targets ?? {})) {
|
|
51
|
+
if (!/^[a-z0-9][a-z0-9._-]{0,59}$/i.test(key)) throw bad(`target key «${key}»: letters, digits, . _ - only`);
|
|
52
|
+
const projectId = Number(t?.project_id);
|
|
53
|
+
if (!Number.isInteger(projectId) || projectId <= 0) throw bad(`target «${key}»: project_id (the Konsilium project of the deploy target) is required`);
|
|
54
|
+
const environment = String(t.environment ?? 'production');
|
|
55
|
+
if (t.approval && t.approval !== 'human') throw bad(`target «${key}»: approval is always «human» (✅ of a person with the deploy right); the orchestrator never approves`);
|
|
56
|
+
targets[key] = { key, projectId, environment, approval: 'human', title: t.title ? String(t.title).slice(0, 100) : null };
|
|
57
|
+
}
|
|
58
|
+
const routes = (raw.routes ?? []).map((r, i) => {
|
|
59
|
+
const event = String(r?.event ?? '');
|
|
60
|
+
if (!/^agent\.[a-z_]+$/.test(event)) throw bad(`routes[${i}].event: an agent event type such as agent.deploy_required`);
|
|
61
|
+
const projectId = Number(r.project_id);
|
|
62
|
+
if (!Number.isInteger(projectId) || projectId <= 0) throw bad(`routes[${i}].project_id is required (the project whose events start the job)`);
|
|
63
|
+
if (!targets[r.target]) throw bad(`routes[${i}].target «${r.target}» is not in targets`);
|
|
64
|
+
const kind = r.kind ?? 'deploy_check';
|
|
65
|
+
if (!JOB_KINDS.includes(kind)) throw bad(`routes[${i}].kind «${kind}»: one of ${JOB_KINDS.join(', ')}`);
|
|
66
|
+
return { event, projectId, target: r.target, kind, priority: Number(r.priority) || 0 };
|
|
67
|
+
});
|
|
68
|
+
const ids = new Set();
|
|
69
|
+
const agents = (raw.agents ?? []).map((a, i) => {
|
|
70
|
+
const id = String(a?.id ?? '');
|
|
71
|
+
if (!/^[a-z0-9][a-z0-9._-]{0,59}$/i.test(id)) throw bad(`agents[${i}].id: letters, digits, . _ - only`);
|
|
72
|
+
if (ids.has(id)) throw bad(`agents: id «${id}» twice`);
|
|
73
|
+
ids.add(id);
|
|
74
|
+
const mode = a.mode ?? 'session';
|
|
75
|
+
if (!AGENT_MODES.includes(mode)) throw bad(`agents[${i}].mode: ${AGENT_MODES.join(' | ')}`);
|
|
76
|
+
if (!a.workspace) throw bad(`agents[${i}].workspace (the repository the agent works in) is required`);
|
|
77
|
+
const projects = [].concat(a.projects ?? []).map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
|
78
|
+
if (!projects.length) throw bad(`agents[${i}].projects: at least one Konsilium project id`);
|
|
79
|
+
const provider = String(a.provider ?? 'claude');
|
|
80
|
+
// stage 3: starting an agent is per slot and narrow — never a second process in a person's session
|
|
81
|
+
const slotDispatch = a.dispatch ?? 'dry_run';
|
|
82
|
+
if (!SLOT_DISPATCH.includes(slotDispatch)) throw bad(`agents[${i}].dispatch: ${SLOT_DISPATCH.join(' | ')}`);
|
|
83
|
+
if (slotDispatch === 'live' && (mode !== 'headless' || provider !== 'claude')) throw bad(`agents[${i}].dispatch "live" is allowed only for mode "headless" with provider "claude" (a session slot gets "handoff")`);
|
|
84
|
+
if (slotDispatch === 'handoff' && mode !== 'session') throw bad(`agents[${i}].dispatch "handoff" is for mode "session" slots (a headless claude slot may be "live")`);
|
|
85
|
+
const timeoutMs = a.timeout_ms == null ? leaseMs : Number(a.timeout_ms);
|
|
86
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 1000 || timeoutMs > leaseMs) throw bad(`agents[${i}].timeout_ms: 1000 … leaseMs (${leaseMs}) — a live run never outlives its lease`);
|
|
87
|
+
const claudeBin = a.claude_bin == null ? 'claude' : String(a.claude_bin);
|
|
88
|
+
if (!/(^|\/)claude$/.test(claudeBin)) throw bad(`agents[${i}].claude_bin: a path to the \`claude\` binary (…/claude)`);
|
|
89
|
+
const envPass = [].concat(a.env_pass ?? []).map(String);
|
|
90
|
+
for (const n of envPass) if (!/^[A-Z_][A-Z0-9_]{0,63}$/.test(n)) throw bad(`agents[${i}].env_pass: variable names only (${n})`);
|
|
91
|
+
const handoffAgent = a.handoff_agent == null ? null : String(a.handoff_agent);
|
|
92
|
+
if (handoffAgent && !/^[a-z0-9][a-z0-9._-]{1,39}$/i.test(handoffAgent)) throw bad(`agents[${i}].handoff_agent: an agent id from list_agents (e.g. claude-1a2b3c) or a provider`);
|
|
93
|
+
return {
|
|
94
|
+
id,
|
|
95
|
+
provider,
|
|
96
|
+
mode,
|
|
97
|
+
dispatch: slotDispatch,
|
|
98
|
+
timeoutMs,
|
|
99
|
+
claudeBin: claudeBin.startsWith('~/') || claudeBin.includes('/') ? resolve(base, expandHome(claudeBin, home)) : claudeBin,
|
|
100
|
+
envPass,
|
|
101
|
+
handoffAgent,
|
|
102
|
+
workspace: resolve(base, expandHome(String(a.workspace), home)),
|
|
103
|
+
projects,
|
|
104
|
+
capabilities: [].concat(a.capabilities ?? JOB_KINDS).map(String),
|
|
105
|
+
sessionId: a.session_id ? String(a.session_id).slice(0, 120) : null,
|
|
106
|
+
};
|
|
107
|
+
});
|
|
108
|
+
const projects = [...new Set([...(raw.projects ?? []).map(Number), ...routes.map((r) => r.projectId)])].filter((n) => Number.isInteger(n) && n > 0);
|
|
109
|
+
if (!projects.length) throw bad('projects: at least one project id to listen to (or a route)');
|
|
110
|
+
const stateDir = resolve(base, expandHome(env.CONSILIUM_ORCHESTRATOR_STATE_DIR ?? raw.stateDir ?? join(env.XDG_STATE_HOME || join(home, '.local', 'state'), ORCHESTRATOR_NAME), home));
|
|
111
|
+
return {
|
|
112
|
+
file,
|
|
113
|
+
server: String(env.KONSILIUM_API_URL ?? raw.server ?? DEFAULT_SERVER).replace(/\/+$/, ''),
|
|
114
|
+
projects,
|
|
115
|
+
stateDir,
|
|
116
|
+
pollMs: Number(raw.pollMs) || 5_000,
|
|
117
|
+
leaseMs,
|
|
118
|
+
deployPollFallbackMs: Number(raw.deployPollFallbackMs) || 5 * 60_000,
|
|
119
|
+
maxAttempts: Number(raw.maxAttempts) || 3,
|
|
120
|
+
backoffMs: Number(raw.backoffMs) || 60_000,
|
|
121
|
+
idleTtlMs: Number(raw.idleTtlMs) || 6 * 3600_000,
|
|
122
|
+
stopTimeoutMs: Number(raw.stopTimeoutMs) || 30_000,
|
|
123
|
+
dispatch,
|
|
124
|
+
report: raw.report === 'off' ? 'off' : 'agent-events',
|
|
125
|
+
reportDryRun: raw.reportDryRun === true,
|
|
126
|
+
sse: raw.sse !== false,
|
|
127
|
+
logFormat: env.CONSILIUM_ORCHESTRATOR_LOG_FORMAT ?? raw.logFormat ?? 'json',
|
|
128
|
+
targets,
|
|
129
|
+
routes,
|
|
130
|
+
agents,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function loadOrchestratorConfig({ file = null, env = process.env, home = homedir() } = {}) {
|
|
135
|
+
const f = file ?? orchestratorConfigCandidates(env, home).find((p) => existsSync(p)) ?? null;
|
|
136
|
+
if (!f || !existsSync(f)) throw new DevopsMcpError('config_missing', `no orchestrator config (looked at ${orchestratorConfigCandidates(env, home).join(', ')}). Create it: ${ORCHESTRATOR_NAME} config --print > <file>`);
|
|
137
|
+
let raw;
|
|
138
|
+
try {
|
|
139
|
+
raw = JSON.parse(readFileSync(f, 'utf8'));
|
|
140
|
+
} catch (e) {
|
|
141
|
+
throw bad(`${f}: not valid JSON (${e.message})`);
|
|
142
|
+
}
|
|
143
|
+
return normalizeOrchestratorConfig(raw, { file: f, env, home });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** An example config (printed by `consilium-devops-orchestrator config --print`). No secret inside. */
|
|
147
|
+
export function exampleOrchestratorConfig({ repoDir = '/path/to/consilium.nativemind.net', projectId = 1, target = 'konsilium-prod' } = {}) {
|
|
148
|
+
return {
|
|
149
|
+
server: DEFAULT_SERVER,
|
|
150
|
+
projects: [projectId],
|
|
151
|
+
stateDir: `~/.local/state/${ORCHESTRATOR_NAME}`,
|
|
152
|
+
dispatch: 'dry_run',
|
|
153
|
+
report: 'agent-events',
|
|
154
|
+
pollMs: 5000,
|
|
155
|
+
leaseMs: 1800000,
|
|
156
|
+
maxAttempts: 3,
|
|
157
|
+
backoffMs: 60000,
|
|
158
|
+
targets: { [target]: { project_id: projectId, environment: 'production', approval: 'human', title: 'Консилиум (прод)' } },
|
|
159
|
+
routes: [{ event: 'agent.deploy_required', project_id: projectId, target, kind: 'deploy_check' }],
|
|
160
|
+
// dispatch per slot: "dry_run" (default) · "handoff" (a session slot: create_handoff into it) · "live" (mode
|
|
161
|
+
// "headless" + provider "claude" only: `claude -p`, timeout_ms ≤ leaseMs)
|
|
162
|
+
agents: [{ id: 'claude-main', provider: 'claude', mode: 'session', dispatch: 'dry_run', workspace: repoDir, projects: [projectId], capabilities: ['deploy_check'] }],
|
|
163
|
+
};
|
|
164
|
+
}
|
|
@@ -0,0 +1,494 @@
|
|
|
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
|
+
}
|