🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ruflo-ruos): host adapter, audited command builder, fleet MCP + SSH transports
ruvbd228c68adb5
diff --git a/plugins/ruflo-ruos/scripts/cli.mjs b/plugins/ruflo-ruos/scripts/cli.mjsnew file mode 100644index 0000000000..c27af747ec--- /dev/null+++ b/plugins/ruflo-ruos/scripts/cli.mjs@@ -0,0 +1,224 @@+#!/usr/bin/env node+// @ts-check+/**+ * ruflo-ruos CLI (ADR-405). Entry point for the plugin's commands/skills.+ *+ * hosts list your ruOS desktops (fleet MCP)+ * run --desktop <ref> (--prompt <t> | --prompt-file <f>) [--agent-type coder]+ * [--model haiku|sonnet|opus] [--timeout 900] [--max-budget-usd n]+ * [--start] [--ignore-autostop] [--transport fleet-mcp|ssh] [--json]+ * stop --desktop <ref> --run <id> --confirm+ * desktop-stop --desktop <ref> --confirm+ * logs --run <id>+ * build --run <id> --prompt-file <f> [--model m] [--max-budget-usd n]+ * print the exact desktop_exec strings (session path)+ * record <start|output|end> --run <id> ... feed the swarm ledger (session path)+ * status transport configuration (no network)+ *+ * With no RUOS_MCP_URL/RUOS_MCP_TOKEN (and no RUOS_SSH_KEY for ssh) every+ * networked command exits 2 with `not-configured` and makes no request.+ */+import { readFileSync, existsSync } from 'node:fs';+import { join } from 'node:path';+import { randomBytes } from 'node:crypto';+import { RuosError } from './lib/types.mjs';+import { FleetMcpClient, fleetConfigFromEnv, createFleet, createFleetTransport, normalizeDesktops } from './lib/fleet-mcp.mjs';+import { createSshTransport, sshConfigFromEnv } from './lib/ssh.mjs';+import { createLedger, resolveCallTool, projectCwd } from './lib/ledger.mjs';+import { RuosHostAdapter } from './lib/adapter.mjs';+import { newRunId, assertRunId, assertAgentId, resolveDesktop, assertInt } from './lib/validate.mjs';+import { buildPrepare, buildPromptChunks, buildLaunch, buildPoll, buildStop, buildProbe } from './lib/command-builder.mjs';+import { nextAutoStop } from './lib/autostop.mjs';++/**+ * @param {string[]} argv+ * @returns {{ _: string[], [k: string]: string|boolean|string[] }}+ */+export function parseArgs(argv) {+ /** @type {{ _: string[], [k: string]: string|boolean|string[] }} */+ const out = { _: [] };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a.startsWith('--')) {+ const eq = a.indexOf('=');+ if (eq > 0) { out[a.slice(2, eq)] = a.slice(eq + 1); continue; }+ const next = argv[i + 1];+ if (next !== undefined && !next.startsWith('--')) { out[a.slice(2)] = next; i++; } else out[a.slice(2)] = true;+ } else out._.push(a);+ }+ return out;+}++/** @param {unknown} v */+const str = (v) => (typeof v === 'string' ? v : undefined);++/**+ * @param {ReturnType<typeof parseArgs>} args+ * @param {NodeJS.ProcessEnv} env+ */+async function buildAdapter(args, env) {+ const client = new FleetMcpClient(fleetConfigFromEnv(env));+ client.assertConfigured(); // the fleet MCP is always the control plane+ const kind = str(args.transport) ?? env.RUOS_TRANSPORT ?? 'fleet-mcp';+ const transport = kind === 'ssh'+ ? createSshTransport(sshConfigFromEnv(env))+ : kind === 'fleet-mcp' ? createFleetTransport(client) : null;+ if (!transport) throw new RuosError('invalid-input', 'transport must be fleet-mcp or ssh');+ const ledger = createLedger({ cwd: projectCwd(env), callTool: await resolveCallTool(projectCwd(env), env) });+ return { adapter: new RuosHostAdapter({ fleet: createFleet(client), transport, ledger }), ledger };+}++/** @param {unknown} o */+const print = (o) => process.stdout.write((typeof o === 'string' ? o : JSON.stringify(o, null, 2)) + '\n');++/**+ * @param {ReturnType<typeof parseArgs>} args+ * @returns {string}+ */+function readPrompt(args) {+ const file = str(args['prompt-file']);+ if (file) return readFileSync(file, 'utf8');+ const p = str(args.prompt);+ if (p) return p;+ throw new RuosError('invalid-input', 'pass --prompt or --prompt-file');+}++/**+ * @param {string[]} argv+ * @param {NodeJS.ProcessEnv} env+ * @returns {Promise<number>}+ */+export async function main(argv, env = process.env) {+ const args = parseArgs(argv);+ const cmd = args._[0];+ switch (cmd) {+ case 'status': {+ const f = fleetConfigFromEnv(env);+ print({+ fleetMcp: f.url && f.token ? 'configured' : 'not-configured',+ ssh: env.RUOS_SSH_KEY ? 'configured' : 'not-configured',+ transport: env.RUOS_TRANSPORT ?? 'fleet-mcp',+ nextAutoStop: new Date(nextAutoStop(Date.now())).toISOString(),+ swarmLedger: (await resolveCallTool(projectCwd(env), env)) ? 'cli' : 'unavailable',+ });+ return 0;+ }+ case 'hosts': {+ const { adapter } = await buildAdapter(args, env);+ const ds = await adapter.discover();+ if (args.json) print(ds);+ else for (const d of ds) print(`${d.id} ${(d.displayName ?? d.name).padEnd(32)} ${d.state ?? '-'}/${d.heartbeatStatus ?? '-'}`);+ return 0;+ }+ case 'run': {+ const { adapter } = await buildAdapter(args, env);+ const runId = newRunId(Date.now, randomBytes);+ const outcome = await adapter.run({+ desktop: String(args.desktop ?? ''),+ prompt: readPrompt(args),+ runId,+ agentId: str(args['agent-id']) ?? `ruos-${runId}`,+ agentType: str(args['agent-type']) ?? 'coder',+ model: /** @type {any} */ (str(args.model)),+ maxBudgetUsd: str(args['max-budget-usd']) ? Number(args['max-budget-usd']) : undefined,+ timeoutSecs: str(args.timeout) ? Number(args.timeout) : undefined,+ allowStart: args.start === true,+ ignoreAutoStop: args['ignore-autostop'] === true,+ onOutput: args.json ? undefined : (c) => process.stdout.write(c),+ });+ if (args.json) print(outcome);+ else process.stderr.write(`\n[ruflo-ruos] ${outcome.status} exit=${outcome.exitCode} run=${outcome.runId} ledger=${outcome.swarmLedger}\n`);+ return outcome.status === 'completed' ? 0 : 1;+ }+ case 'stop': {+ const { adapter } = await buildAdapter(args, env);+ print(await adapter.stopRun({ desktop: String(args.desktop ?? ''), runId: String(args.run ?? ''), confirm: args.confirm === true }));+ return 0;+ }+ case 'desktop-stop': {+ const { adapter } = await buildAdapter(args, env);+ print(await adapter.stopDesktop({ desktop: String(args.desktop ?? ''), confirm: args.confirm === true }));+ return 0;+ }+ case 'logs': {+ const runId = assertRunId(args.run);+ const f = join(projectCwd(env), '.claude-flow', 'ruos', 'runs', `${runId}.log`);+ if (!existsSync(f)) throw new RuosError('invalid-input', 'no local log for that run');+ process.stdout.write(readFileSync(f));+ return 0;+ }+ case 'build': {+ // Session path: Claude calls mcp__ruos__desktop_exec with these strings.+ const runId = str(args.run) ? assertRunId(args.run) : newRunId(Date.now, randomBytes);+ const prompt = readPrompt(args);+ const chunks = buildPromptChunks(runId, prompt);+ print({+ runId,+ promptSha256: chunks.sha256,+ steps: [buildPrepare(runId), ...chunks.commands, buildLaunch({ runId, prompt, runner: 'claude', model: /** @type {any} */ (str(args.model)), maxBudgetUsd: str(args['max-budget-usd']) ? Number(args['max-budget-usd']) : undefined })],+ poll: buildPoll(runId, assertInt(str(args.offset) ?? 0, 0, Number.MAX_SAFE_INTEGER, 'offset')),+ stop: buildStop(runId),+ probe: buildProbe(),+ });+ return 0;+ }+ case 'record':+ return record(args, env);+ default:+ print('usage: cli.mjs <status|hosts|run|stop|desktop-stop|logs|build|record> [options] (see header)');+ return cmd ? 2 : 0;+ }+}++/**+ * Session-path ledger feed: the Claude session drives the fleet MCP tools+ * itself and reports lifecycle here so the swarm state stays one source.+ * @param {ReturnType<typeof parseArgs>} args+ * @param {NodeJS.ProcessEnv} env+ */+async function record(args, env) {+ const phase = args._[1];+ const runId = assertRunId(args.run);+ const agentId = assertAgentId(args['agent-id'] ?? `ruos-${runId}`);+ const agentType = assertAgentId(args['agent-type'] ?? 'coder');+ const ledger = createLedger({ cwd: projectCwd(env), callTool: await resolveCallTool(projectCwd(env), env) });+ if (phase === 'start') {+ // The desktop must come from the caller's own desktop_status output.+ const statusFile = str(args['desktop-status-file']);+ if (!statusFile) throw new RuosError('invalid-input', 'record start needs --desktop-status-file (desktop_status JSON)');+ const d = resolveDesktop(normalizeDesktops(JSON.parse(readFileSync(statusFile, 'utf8'))), String(args.desktop ?? ''));+ if (!(await ledger.claim(runId, agentId, agentType))) throw new RuosError('invalid-input', 'run already claimed');+ await ledger.registerAgent(agentId, agentType, { kind: 'ruos', desktopId: d.id, desktopName: d.displayName ?? d.name, transport: 'fleet-mcp', runId }, String(args.task ?? ''));+ ledger.snapshotHosts([d], { [d.id]: [agentId] });+ ledger.event({ type: 'run.started', runId, agentId, desktopId: d.id, desktopName: d.displayName ?? d.name });+ } else if (phase === 'output') {+ const b64 = String(args.b64 ?? '');+ if (!/^[A-Za-z0-9+/=]*$/.test(b64)) throw new RuosError('invalid-input', 'b64 is not base64');+ const chunk = Buffer.from(b64, 'base64');+ ledger.appendOutput(runId, chunk);+ ledger.event({ type: 'run.output', runId, agentId, bytes: chunk.length });+ } else if (phase === 'end') {+ const exit = args.exit === undefined ? null : assertInt(args.exit, 0, 255, 'exit');+ const status = exit === 0 ? 'completed' : 'failed';+ ledger.event({ type: status === 'completed' ? 'run.completed' : 'run.failed', runId, agentId, exitCode: exit });+ await ledger.updateAgent(agentId, 'idle', { runId, status, exitCode: exit });+ await ledger.release(runId, agentId, agentType);+ } else {+ throw new RuosError('invalid-input', 'record phase must be start|output|end');+ }+ print({ ok: true, runId, agentId, swarmLedger: ledger.swarmLedger, warnings: ledger.warnings });+ return 0;+}++const isMain = process.argv[1] && import.meta.url.endsWith(process.argv[1].split('/').pop() ?? '');+if (isMain) {+ main(process.argv.slice(2)).then((c) => { process.exitCode = c; }, (err) => {+ if (err instanceof RuosError) {+ process.stderr.write(`ruflo-ruos: ${err.code}: ${err.message}\n`);+ process.exitCode = err.code === 'not-configured' || err.code === 'confirm-required' ? 2 : 1;+ } else {+ process.stderr.write(`ruflo-ruos: ${String(err?.stack ?? err)}\n`);+ process.exitCode = 1;+ }+ });+}diff --git a/plugins/ruflo-ruos/scripts/lib/adapter.mjs b/plugins/ruflo-ruos/scripts/lib/adapter.mjsnew file mode 100644index 0000000000..77c03b926f--- /dev/null+++ b/plugins/ruflo-ruos/scripts/lib/adapter.mjs@@ -0,0 +1,287 @@+// @ts-check+/**+ * ruOS host adapter (ADR-405): discover → (opt-in start) → launch → stream →+ * stop, with typed failures. Collaborators are injected (London-school):+ * Fleet (control plane), Transport (exec), Ledger (swarm state), clock.+ */+import { RuosError } from './types.mjs';+import { resolveDesktop, assertRunId, assertAgentId, assertInt } from './validate.mjs';+import {+ buildPrepare, buildPromptChunks, buildLaunch, buildPoll, buildStop, parsePoll, parseLaunch,+} from './command-builder.mjs';+import { checkWindow } from './autostop.mjs';++/** heartbeat older than this is not evidence the desktop is up */+export const HEARTBEAT_FRESH_SECS = 180;++/**+ * @param {import('./types.mjs').Desktop} d+ * @param {number} nowMs+ */+export function isUp(d, nowMs) {+ if (d.heartbeatStatus && ['asleep', 'missing', 'stale'].includes(d.heartbeatStatus)) return false;+ if (d.heartbeatAt === null) return false;+ return nowMs / 1000 - d.heartbeatAt <= HEARTBEAT_FRESH_SECS;+}++/**+ * @typedef {object} AdapterDeps+ * @property {import('./types.mjs').Fleet} fleet+ * @property {import('./types.mjs').Transport} transport+ * @property {import('./ledger.mjs').Ledger} ledger+ * @property {() => number=} now+ * @property {(ms: number) => Promise<void>=} sleep+ */++/**+ * @typedef {object} RunOptions+ * @property {string} desktop desktop reference (id, fly id or name)+ * @property {string} prompt+ * @property {string} runId+ * @property {string} agentId+ * @property {string=} agentType+ * @property {('haiku'|'sonnet'|'opus')=} model+ * @property {number=} maxBudgetUsd+ * @property {number=} timeoutSecs wall-clock cap for the whole run+ * @property {boolean=} allowStart opt-in: wake a stopped desktop+ * @property {boolean=} ignoreAutoStop+ * @property {(chunk: Buffer) => void=} onOutput+ * @property {AbortSignal=} signal+ */++/**+ * @typedef {object} RunOutcome+ * @property {string} runId+ * @property {string} agentId+ * @property {string} desktopId+ * @property {'completed'|'failed'|'stopped'} status+ * @property {number|null} exitCode+ * @property {number} bytes+ * @property {number} dispatchMs local call → launch acknowledged+ * @property {number|null} firstOutputMs local call → first output byte+ * @property {number} totalMs+ * @property {string} swarmLedger+ * @property {string[]} warnings+ */++export class RuosHostAdapter {+ /** @param {AdapterDeps} deps */+ constructor(deps) {+ this.fleet = deps.fleet;+ this.transport = deps.transport;+ this.ledger = deps.ledger;+ this.now = deps.now ?? Date.now;+ this.sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));+ }++ async discover() {+ const desktops = await this.fleet.listDesktops();+ this.ledger.snapshotHosts(desktops, {});+ return desktops;+ }++ /** @param {string} ref */+ async resolve(ref) {+ return resolveDesktop(await this.fleet.listDesktops(), ref);+ }++ /**+ * Wake a stopped desktop only when the caller opted in; then wait for a+ * FRESH heartbeat (`ready` is a provisioning flag, not liveness).+ * @param {import('./types.mjs').Desktop} desktop+ * @param {{ allowStart?: boolean, waitSecs?: number }} o+ */+ async ensureUp(desktop, o) {+ if (isUp(desktop, this.now())) return desktop;+ if (!o.allowStart) {+ throw new RuosError('desktop-stopped', `desktop ${desktop.displayName ?? desktop.name} is not running; pass --start to wake it (billable)`);+ }+ if (!desktop.flyMachineId) {+ throw new RuosError('desktop-stopped', 'desktop is an enrolled endpoint without a cloud machine; start it on the device');+ }+ await this.fleet.start(desktop.id);+ this.ledger.event({ type: 'desktop.state', desktopId: desktop.id, state: 'starting' });+ const deadline = this.now() + (o.waitSecs ?? 180) * 1000;+ let delay = 2000;+ while (this.now() < deadline) {+ await this.sleep(delay);+ delay = Math.min(delay * 1.5, 10_000);+ const fresh = resolveDesktop(await this.fleet.listDesktops(), desktop.id);+ if (isUp(fresh, this.now())) {+ this.ledger.event({ type: 'desktop.state', desktopId: desktop.id, state: 'started' });+ return fresh;+ }+ }+ throw new RuosError('timeout', 'desktop did not report a fresh heartbeat after start');+ }++ /**+ * @param {import('./types.mjs').Desktop} desktop+ * @param {string} command+ * @param {number=} timeoutSecs+ */+ async exec(desktop, command, timeoutSecs = 30) {+ const r = await this.transport.exec(desktop, command, timeoutSecs);+ if (r.exitCode !== null && r.exitCode !== 0) {+ throw new RuosError('remote-error', `remote command failed (exit ${r.exitCode}): ${(r.stdout + r.stderr).slice(0, 200)}`);+ }+ return r;+ }++ /**+ * After a transport failure mid-run: did the desktop stop under us?+ * @param {import('./types.mjs').Desktop} desktop+ * @param {unknown} err+ */+ async classifyMidRun(desktop, err) {+ if (err instanceof RuosError && (err.code === 'auth-expired' || err.code === 'invalid-input')) return err;+ try {+ const fresh = resolveDesktop(await this.fleet.listDesktops(), desktop.id);+ if (!isUp(fresh, this.now())) {+ return new RuosError('auto-stopped', 'desktop stopped mid-run (weekday 23:00 America/Toronto auto-stop or idle autosleep)', err);+ }+ } catch (probeErr) {+ if (probeErr instanceof RuosError && probeErr.code === 'auth-expired') return probeErr;+ }+ return err instanceof RuosError ? err : new RuosError('remote-error', String(err), err);+ }++ /**+ * @param {RunOptions} o+ * @returns {Promise<RunOutcome>}+ */+ async run(o) {+ const t0 = this.now();+ const runId = assertRunId(o.runId);+ const agentId = assertAgentId(o.agentId);+ const agentType = assertAgentId(o.agentType ?? 'coder');+ const timeoutSecs = assertInt(o.timeoutSecs ?? 900, 30, 6 * 3600, 'timeoutSecs');++ const win = checkWindow(t0, timeoutSecs);+ if (!win.ok && !o.ignoreAutoStop) {+ throw new RuosError('autostop-window', `run may outlast the next auto-stop in ${win.minutesUntilStop} min (weekday 23:00 America/Toronto); shorten --timeout or pass --ignore-autostop`);+ }++ let desktop = await this.resolve(o.desktop);+ desktop = await this.ensureUp(desktop, { allowStart: o.allowStart });+ const name = desktop.displayName ?? desktop.name;+ /** @type {import('./types.mjs').HostRef} */+ const host = { kind: 'ruos', desktopId: desktop.id, desktopName: name, transport: this.transport.kind, runId };++ const chunks = buildPromptChunks(runId, o.prompt); // validates the prompt before any remote call+ const claimed = await this.ledger.claim(runId, agentId, agentType);+ if (!claimed) throw new RuosError('invalid-input', `run ${runId} is already claimed`);+ await this.ledger.registerAgent(agentId, agentType, host, o.prompt);+ this.ledger.snapshotHosts([desktop], { [desktop.id]: [agentId] });++ let bytes = 0;+ /** @type {number|null} */ let firstOutputMs = null;+ let dispatchMs = 0;+ /** @type {RunOutcome['status']} */ let status = 'failed';+ /** @type {number|null} */ let exitCode = null;+ try {+ await this.exec(desktop, buildPrepare(runId));+ for (const c of chunks.commands) await this.exec(desktop, c);+ const lr = await this.transport.exec(desktop, buildLaunch({ runId, prompt: o.prompt, runner: 'claude', model: o.model, maxBudgetUsd: o.maxBudgetUsd }), 60);+ const launched = parseLaunch(lr.stdout);+ if (launched.noRunner) throw new RuosError('remote-error', 'claude is not installed on the desktop');+ if (lr.exitCode !== null && lr.exitCode !== 0) throw new RuosError('remote-error', `launch failed (exit ${lr.exitCode})`);+ if (launched.sha256 !== chunks.sha256) throw new RuosError('remote-error', 'prompt integrity check failed (sha256 mismatch)');+ if (launched.pid === null) throw new RuosError('remote-error', 'runner did not report a pid');+ dispatchMs = this.now() - t0;+ this.ledger.event({ type: 'run.started', runId, agentId, desktopId: desktop.id, desktopName: name });+ if (desktop.flyMachineId) {+ await this.fleet.keepAwake(desktop.flyMachineId, Math.min(1440, Math.ceil(timeoutSecs / 60) + 5)).catch(() => {+ this.ledger.warnings.push('keepawake failed; idle autosleep may stop the run');+ });+ }++ let offset = 0;+ let delay = 1000;+ for (;;) {+ if (o.signal?.aborted) {+ await this.transport.exec(desktop, buildStop(runId), 30).catch(() => {});+ status = 'stopped';+ break;+ }+ if (this.now() - t0 > timeoutSecs * 1000) {+ await this.transport.exec(desktop, buildStop(runId), 30).catch(() => {});+ throw new RuosError('timeout', `run exceeded ${timeoutSecs}s and was stopped`);+ }+ const p = parsePoll((await this.transport.exec(desktop, buildPoll(runId, offset), 30)).stdout);+ if (p === 'norun') throw new RuosError('remote-error', 'run directory vanished on the desktop');+ if (p.chunk.length > 0) {+ if (firstOutputMs === null) firstOutputMs = this.now() - t0;+ offset += p.chunk.length;+ bytes += p.chunk.length;+ this.ledger.appendOutput(runId, p.chunk);+ o.onOutput?.(p.chunk);+ this.ledger.event({ type: 'run.output', runId, agentId, desktopId: desktop.id, bytes: p.chunk.length });+ delay = 1000;+ }+ if (p.exitCode !== null && offset >= p.size) {+ exitCode = p.exitCode;+ status = exitCode === 0 ? 'completed' : 'failed';+ break;+ }+ if (p.chunk.length === 0) {+ await this.sleep(delay);+ delay = Math.min(delay * 1.5, 5000);+ }+ }+ } catch (err) {+ const e = await this.classifyMidRun(desktop, err);+ this.ledger.event({ type: 'run.failed', runId, agentId, desktopId: desktop.id, error: e.code ?? 'remote-error' });+ await this.finish(agentId, agentType, runId, 'failed', null, bytes);+ throw e;+ }+ this.ledger.event({+ type: status === 'stopped' ? 'run.stopped' : status === 'completed' ? 'run.completed' : 'run.failed',+ runId, agentId, desktopId: desktop.id, exitCode, bytes,+ });+ await this.finish(agentId, agentType, runId, status, exitCode, bytes);+ return {+ runId, agentId, desktopId: desktop.id, status, exitCode, bytes, dispatchMs, firstOutputMs,+ totalMs: this.now() - t0, swarmLedger: this.ledger.swarmLedger, warnings: [...this.ledger.warnings],+ };+ }++ /**+ * @param {string} agentId+ * @param {string} agentType+ * @param {string} runId+ * @param {string} status+ * @param {number|null} exitCode+ * @param {number} bytes+ */+ async finish(agentId, agentType, runId, status, exitCode, bytes) {+ await this.ledger.updateAgent(agentId, 'idle', { runId, status, exitCode, bytes });+ await this.ledger.release(runId, agentId, agentType);+ }++ /**+ * Stop a run (its process group) — explicit confirm required.+ * @param {{ desktop: string, runId: string, confirm?: boolean }} o+ */+ async stopRun(o) {+ if (!o.confirm) throw new RuosError('confirm-required', 'stopping a run interrupts work; pass --confirm');+ const runId = assertRunId(o.runId);+ const desktop = await this.resolve(o.desktop);+ const r = await this.transport.exec(desktop, buildStop(runId), 30);+ const stopped = r.stdout.includes('RUOS_STOPPED');+ this.ledger.event({ type: 'run.stopped', runId, desktopId: desktop.id, state: stopped ? 'stopped' : 'not-running' });+ return { runId, desktopId: desktop.id, stopped };+ }++ /**+ * Stop the whole desktop — explicit confirm required (discards in-memory state).+ * @param {{ desktop: string, confirm?: boolean }} o+ */+ async stopDesktop(o) {+ if (!o.confirm) throw new RuosError('confirm-required', 'stopping a desktop interrupts all work on it; pass --confirm');+ const desktop = await this.resolve(o.desktop);+ await this.fleet.stop(desktop.id);+ this.ledger.event({ type: 'desktop.state', desktopId: desktop.id, state: 'stopping' });+ return { desktopId: desktop.id };+ }+}diff --git a/plugins/ruflo-ruos/scripts/lib/autostop.mjs b/plugins/ruflo-ruos/scripts/lib/autostop.mjsnew file mode 100644index 0000000000..aba39855d3--- /dev/null+++ b/plugins/ruflo-ruos/scripts/lib/autostop.mjs@@ -0,0 +1,98 @@+// @ts-check+/**+ * ruOS auto-stop window (ADR-405 §Cost and auto-stop).+ *+ * The fleet stops cloud desktops at 23:00 America/Toronto every weekday+ * (Mon–Fri); `desktop_keepawake` only blocks idle autosleep and does NOT+ * override this. A run whose deadline crosses the next stop would be killed+ * mid-flight, so the adapter refuses it unless the caller opts in.+ * Zero dependencies: Intl does the time-zone arithmetic (DST included).+ */+export const AUTOSTOP_TZ = 'America/Toronto';+export const AUTOSTOP_HOUR = 23;++const fmt = new Intl.DateTimeFormat('en-US', {+ timeZone: AUTOSTOP_TZ,+ hourCycle: 'h23',+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ weekday: 'short',+});++/**+ * @param {number} ms+ * @returns {{ y: number, m: number, d: number, hour: number, minute: number, weekday: string }}+ */+function torontoParts(ms) {+ /** @type {Record<string, string>} */+ const p = {};+ for (const part of fmt.formatToParts(new Date(ms))) p[part.type] = part.value;+ return {+ y: Number(p.year),+ m: Number(p.month),+ d: Number(p.day),+ hour: Number(p.hour),+ minute: Number(p.minute),+ weekday: p.weekday,+ };+}++const WEEKDAYS = new Set(['Mon', 'Tue', 'Wed', 'Thu', 'Fri']);++/**+ * The UTC instant of 23:00 Toronto on the given Toronto calendar date.+ * Toronto is UTC-4 (EDT) or UTC-5 (EST); pick the offset that round-trips.+ * @param {number} y+ * @param {number} m+ * @param {number} d+ * @returns {number}+ */+function torontoElevenPm(y, m, d) {+ for (const offsetH of [4, 5]) {+ const ms = Date.UTC(y, m - 1, d, AUTOSTOP_HOUR + offsetH, 0, 0);+ const p = torontoParts(ms);+ if (p.y === y && p.m === m && p.d === d && p.hour === AUTOSTOP_HOUR && p.minute === 0) return ms;+ }+ throw new Error('unreachable: no Toronto offset round-trips');+}++/**+ * Next auto-stop instant strictly after `nowMs`.+ * @param {number} nowMs+ * @returns {number}+ */+export function nextAutoStop(nowMs) {+ for (let day = 0; day <= 7; day++) {+ // Noon-anchored stepping keeps us on the intended calendar day across DST.+ const p = torontoParts(nowMs + day * 86_400_000);+ if (!WEEKDAYS.has(p.weekday)) continue;+ const stop = torontoElevenPm(p.y, p.m, p.d);+ if (stop > nowMs) return stop;+ }+ throw new Error('unreachable: no weekday within 8 days');+}++/**+ * @typedef {object} WindowCheck+ * @property {boolean} ok+ * @property {number} nextStopMs+ * @property {number} minutesUntilStop+ */++/**+ * Does a run that may last `timeoutSecs` finish before the next auto-stop?+ * @param {number} nowMs+ * @param {number} timeoutSecs+ * @returns {WindowCheck}+ */+export function checkWindow(nowMs, timeoutSecs) {+ const nextStopMs = nextAutoStop(nowMs);+ return {+ ok: nowMs + timeoutSecs * 1000 < nextStopMs,+ nextStopMs,+ minutesUntilStop: Math.floor((nextStopMs - nowMs) / 60_000),+ };+}diff --git a/plugins/ruflo-ruos/scripts/lib/command-builder.mjs b/plugins/ruflo-ruos/scripts/lib/command-builder.mjsnew file mode 100644index 0000000000..83753cad3a--- /dev/null+++ b/plugins/ruflo-ruos/scripts/lib/command-builder.mjs@@ -0,0 +1,178 @@+// @ts-check+/**+ * The ONE audited builder for every shell string sent to a ruOS desktop+ * (ADR-405 §Command construction).+ *+ * Invariants, enforced here and asserted by tests/command-builder.test.mjs:+ * 1. Every command is a single line (no \n, \r or NUL) of at most+ * MAX_COMMAND_BYTES — the fleet `desktop_exec` limit.+ * 2. The only variable regions are (a) a run id that matched RUN_ID_RE,+ * (b) integers produced by this module, (c) base64 text inside single+ * quotes, (d) a model name from a fixed enum. Task text never appears.+ * 3. Prompt text travels as base64 and is decoded on the desktop into a+ * file that the runner reads on stdin — it is never parsed by a shell.+ * 4. Output comes back base64-encoded, so arbitrary bytes survive the JSON+ * tool result and are decoded locally.+ * Both transports (fleet MCP desktop_exec and SSH :2222) send these exact+ * strings, so one builder covers both.+ */+import { createHash } from 'node:crypto';+import { RuosError } from './types.mjs';+import { assertRunId, assertModel, assertBudget, assertInt, assertPrompt } from './validate.mjs';++export const MAX_COMMAND_BYTES = 4000;+/** largest output slice a single poll returns (raw bytes, before base64) */+export const POLL_SLICE_BYTES = 48 * 1024;++const B64_RE = /^[A-Za-z0-9+/=]*$/;++/** @param {string} runId */+function runDir(runId) {+ return `"$HOME/.ruflo-ruos/runs/${assertRunId(runId)}"`;+}++/**+ * @param {string} cmd+ * @returns {string}+ */+function seal(cmd) {+ if (/[\n\r\0]/.test(cmd)) throw new RuosError('invalid-input', 'command must be one line');+ if (Buffer.byteLength(cmd, 'utf8') > MAX_COMMAND_BYTES) {+ throw new RuosError('invalid-input', `command exceeds ${MAX_COMMAND_BYTES} bytes`);+ }+ return cmd;+}++/** @param {string} runId */+export function buildPrepare(runId) {+ const d = runDir(runId);+ return seal(`umask 077 && mkdir -p ${d} && : > ${d}/prompt.b64 && echo RUOS_PREPARED`);+}++/**+ * Split the prompt into append commands that each fit the size limit.+ * @param {string} runId+ * @param {string} prompt+ * @returns {{ commands: string[], sha256: string, bytes: number }}+ */+export function buildPromptChunks(runId, prompt) {+ const text = assertPrompt(prompt);+ const b64 = Buffer.from(text, 'utf8').toString('base64');+ const d = runDir(runId);+ const head = `printf '%s' '`;+ const tail = `' >> ${d}/prompt.b64`;+ const room = MAX_COMMAND_BYTES - Buffer.byteLength(head + tail, 'utf8');+ const step = room - (room % 4); // keep chunk boundaries on base64 quanta+ /** @type {string[]} */+ const commands = [];+ for (let i = 0; i < b64.length; i += step) {+ const chunk = b64.slice(i, i + step);+ if (!B64_RE.test(chunk)) throw new RuosError('invalid-input', 'internal: non-base64 chunk');+ commands.push(seal(head + chunk + tail));+ }+ const sha256 = createHash('sha256').update(text, 'utf8').digest('hex');+ return { commands, sha256, bytes: Buffer.byteLength(text, 'utf8') };+}++/**+ * Decode the prompt, print its sha256 (checked against the local hash before+ * the run is trusted), and start the runner detached in its own session so a+ * later stop can signal the whole process group.+ * @param {import('./types.mjs').RunSpec} spec+ */+export function buildLaunch(spec) {+ const d = runDir(spec.runId);+ if (spec.runner !== 'claude') throw new RuosError('invalid-input', 'runner must be claude');+ const model = assertModel(spec.model);+ const budget = assertBudget(spec.maxBudgetUsd);+ const flags = ['--output-format text'];+ if (model) flags.push(`--model ${model}`);+ if (budget !== undefined) flags.push(`--max-budget-usd ${budget.toFixed(2)}`);+ // The inner script is a constant apart from the enum/number flags above.+ const inner = `claude -p ${flags.join(' ')} < prompt.txt > out.log 2>&1; echo $? > exit.code`;+ // Setup runs as separate `|| exit` statements, never an `&&` chain ending+ // in `&` (that would background the whole chain in a subshell). In a+ // non-interactive shell the background job is not a group leader, so+ // setsid execs in place and $! is the new session's pgid.+ return seal(+ `umask 077 ; command -v claude >/dev/null || { echo RUOS_NO_RUNNER; exit 127; }` ++ ` ; cd ${d} || exit 3` ++ ` ; base64 -d prompt.b64 > prompt.txt || exit 5` ++ ` ; rm -f exit.code ; : > out.log` ++ ` ; printf 'RUOS_SHA:%s\\n' "$(sha256sum prompt.txt | cut -c1-64)"` ++ ` ; nohup setsid sh -c '${inner}' > /dev/null 2>&1 < /dev/null & echo "RUOS_PID:$!" > pid ; cat pid`,+ );+}++/**+ * Report exit state and size, then return one base64 slice of the log from+ * byte `offset`. Output: `RUOS_POLL:<exit|->:<size>:<base64>`.+ * @param {string} runId+ * @param {number} offset+ * @param {number=} maxBytes+ */+export function buildPoll(runId, offset, maxBytes = POLL_SLICE_BYTES) {+ const d = runDir(runId);+ const off = assertInt(offset, 0, Number.MAX_SAFE_INTEGER, 'offset');+ const max = assertInt(maxBytes, 1, 1024 * 1024, 'maxBytes');+ return seal(+ `cd ${d} 2>/dev/null || { echo RUOS_NORUN; exit 3; }` ++ ` ; e=$(cat exit.code 2>/dev/null || echo -) ; s=$(stat -c %s out.log 2>/dev/null || echo 0)` ++ ` ; printf 'RUOS_POLL:%s:%s:' "$e" "$s" ; tail -c +${off + 1} out.log 2>/dev/null | head -c ${max} | base64 -w0 ; echo`,+ );+}++/**+ * Stop the run's process group. The pid file is re-validated as digits on+ * the desktop before it is used.+ * @param {string} runId+ */+export function buildStop(runId) {+ const d = runDir(runId);+ return seal(+ `p=$(sed -n 's/^RUOS_PID://p' ${d}/pid 2>/dev/null)` ++ ` ; case "$p" in ''|*[!0-9]*) echo RUOS_NOPID; exit 4;; esac` ++ ` ; { kill -TERM -- -"$p" 2>/dev/null || kill -TERM "$p" 2>/dev/null; } && echo RUOS_STOPPED || echo RUOS_NOT_RUNNING`,+ );+}++/** Probe: is the runner present on this desktop? */+export function buildProbe() {+ return seal(`command -v claude >/dev/null && echo RUOS_RUNNER_OK || echo RUOS_RUNNER_MISSING`);+}++/**+ * @typedef {object} PollResult+ * @property {number|null} exitCode null while running+ * @property {number} size total log size on the desktop+ * @property {Buffer} chunk+ */++/**+ * @param {string} stdout+ * @returns {PollResult|'norun'}+ */+export function parsePoll(stdout) {+ if (stdout.includes('RUOS_NORUN')) return 'norun';+ const m = /RUOS_POLL:(-|\d+):(\d+):([A-Za-z0-9+/=]*)/.exec(stdout);+ if (!m) throw new RuosError('remote-error', 'unparseable poll output');+ return {+ exitCode: m[1] === '-' ? null : Number(m[1]),+ size: Number(m[2]),+ chunk: Buffer.from(m[3], 'base64'),+ };+}++/**+ * @param {string} stdout+ * @returns {{ sha256: string|null, pid: number|null, noRunner: boolean }}+ */+export function parseLaunch(stdout) {+ const sha = /RUOS_SHA:([0-9a-f]{64})/.exec(stdout);+ const pid = /RUOS_PID:(\d+)/.exec(stdout);+ return {+ sha256: sha ? sha[1] : null,+ pid: pid ? Number(pid[1]) : null,+ noRunner: stdout.includes('RUOS_NO_RUNNER'),+ };+}diff --git a/plugins/ruflo-ruos/scripts/lib/fleet-mcp.mjs b/plugins/ruflo-ruos/scripts/lib/fleet-mcp.mjsnew file mode 100644index 0000000000..07b8a4d437--- /dev/null+++ b/plugins/ruflo-ruos/scripts/lib/fleet-mcp.mjs@@ -0,0 +1,249 @@+// @ts-check+/**+ * Fleet MCP transport (ADR-405 transport 1) — the tenant-authenticated ruOS+ * fleet MCP over streamable HTTP. The caller's own bearer comes from the+ * environment (RUOS_MCP_URL + RUOS_MCP_TOKEN); nothing is embedded, and with+ * either unset the client refuses before touching the network.+ *+ * This client never talks to a desktop directly. In particular it never+ * reaches the desktop executor on :17870 (no per-tenant auth, ADR-070).+ */+import { RuosError } from './types.mjs';+import { FLY_ID_RE, DESKTOP_ID_RE } from './validate.mjs';++const PROTOCOL_VERSION = '2025-06-18';++/**+ * @typedef {object} FleetMcpOptions+ * @property {string|undefined} url+ * @property {string|undefined} token+ * @property {typeof fetch=} fetchImpl+ * @property {number=} requestTimeoutMs+ */++/** @param {NodeJS.ProcessEnv} env */+export function fleetConfigFromEnv(env) {+ return { url: env.RUOS_MCP_URL || undefined, token: env.RUOS_MCP_TOKEN || undefined };+}++export class FleetMcpClient {+ /** @param {FleetMcpOptions} opts */+ constructor(opts) {+ this.url = opts.url;+ this.token = opts.token;+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;+ this.requestTimeoutMs = opts.requestTimeoutMs ?? 330_000;+ /** @type {string|null} */+ this.sessionId = null;+ this.nextId = 1;+ /** @type {Promise<void>|null} */+ this.ready = null;+ }++ get configured() {+ return Boolean(this.url && this.token);+ }++ assertConfigured() {+ if (!this.configured) {+ throw new RuosError('not-configured', 'set RUOS_MCP_URL and RUOS_MCP_TOKEN to use the fleet MCP transport');+ }+ const u = new URL(/** @type {string} */ (this.url));+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && (u.hostname === '127.0.0.1' || u.hostname === 'localhost'))) {+ throw new RuosError('invalid-input', 'RUOS_MCP_URL must be https (http only for localhost)');+ }+ if (u.port === '17870') throw new RuosError('invalid-input', 'refusing the desktop executor port :17870 (ADR-070)');+ }++ /**+ * @param {string} method+ * @param {Record<string, unknown>=} params+ * @param {boolean=} notification+ */+ async rpc(method, params, notification = false) {+ this.assertConfigured();+ /** @type {Record<string, string>} */+ const headers = {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ authorization: `Bearer ${this.token}`,+ 'mcp-protocol-version': PROTOCOL_VERSION,+ };+ if (this.sessionId) headers['mcp-session-id'] = this.sessionId;+ const body = notification+ ? { jsonrpc: '2.0', method, params: params ?? {} }+ : { jsonrpc: '2.0', id: this.nextId++, method, params: params ?? {} };+ /** @type {Response} */+ let res;+ try {+ res = await this.fetchImpl(/** @type {string} */ (this.url), {+ method: 'POST',+ headers,+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(this.requestTimeoutMs),+ });+ } catch (err) {+ const e = /** @type {Error} */ (err);+ if (e && e.name === 'TimeoutError') throw new RuosError('timeout', 'fleet MCP request timed out', err);+ throw new RuosError('network-down', 'fleet MCP unreachable', err);+ }+ if (res.status === 401 || res.status === 403) {+ throw new RuosError('auth-expired', `fleet MCP refused the credential (HTTP ${res.status}); refresh RUOS_MCP_TOKEN`);+ }+ if (!res.ok && res.status !== 202) {+ throw new RuosError('tool-error', `fleet MCP HTTP ${res.status}`);+ }+ const sid = res.headers.get('mcp-session-id');+ if (sid) this.sessionId = sid;+ if (notification || res.status === 202) return undefined;+ const text = await res.text();+ const msg = parseRpcBody(text, res.headers.get('content-type') || '');+ if (msg.error) {+ const code = /unauthori|expired|invalid token/i.test(String(msg.error.message)) ? 'auth-expired' : 'tool-error';+ throw new RuosError(code, `fleet MCP error: ${String(msg.error.message).slice(0, 200)}`);+ }+ return msg.result;+ }++ async init() {+ if (!this.ready) {+ this.ready = (async () => {+ await this.rpc('initialize', {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: 'ruflo-ruos', version: '0.1.0' },+ });+ await this.rpc('notifications/initialized', {}, true);+ })();+ this.ready.catch(() => { this.ready = null; });+ }+ return this.ready;+ }++ /**+ * Call a fleet tool and return its structured payload.+ * @param {string} name+ * @param {Record<string, unknown>} args+ * @returns {Promise<any>}+ */+ async callTool(name, args) {+ await this.init();+ const result = /** @type {any} */ (await this.rpc('tools/call', { name, arguments: args }));+ const payload = toolPayload(result);+ if (result && result.isError) {+ const text = typeof payload === 'string' ? payload : JSON.stringify(payload);+ throw classifyToolError(text);+ }+ return payload;+ }+}++/**+ * @param {string} text+ * @param {string} contentType+ * @returns {{ result?: unknown, error?: { message?: unknown } }}+ */+export function parseRpcBody(text, contentType) {+ if (contentType.includes('text/event-stream')) {+ let last = null;+ for (const line of text.split(/\r?\n/)) {+ if (line.startsWith('data:')) {+ const data = line.slice(5).trim();+ if (data) last = JSON.parse(data);+ }+ }+ if (!last) throw new RuosError('tool-error', 'empty SSE response from fleet MCP');+ return last;+ }+ return JSON.parse(text);+}++/** @param {any} result */+export function toolPayload(result) {+ if (!result) return null;+ if (result.structuredContent !== undefined) return result.structuredContent;+ const t = Array.isArray(result.content) ? result.content.find((/** @type {any} */ c) => c.type === 'text') : null;+ if (!t) return null;+ try {+ return JSON.parse(t.text);+ } catch {+ return t.text;+ }+}++/** @param {string} text */+export function classifyToolError(text) {+ const t = text.slice(0, 300);+ if (/unauthori|expired|forbidden|scope/i.test(t)) return new RuosError('auth-expired', `fleet: ${t}`);+ if (/not running|stopped|asleep|suspended|not started|no heartbeat/i.test(t)) return new RuosError('desktop-stopped', `fleet: ${t}`);+ if (/not found|not owned|unknown machine/i.test(t)) return new RuosError('not-owned', `fleet: ${t}`);+ if (/timed? ?out/i.test(t)) return new RuosError('timeout', `fleet: ${t}`);+ return new RuosError('tool-error', `fleet: ${t}`);+}++/**+ * @param {any} raw+ * @returns {import('./types.mjs').Desktop[]}+ */+export function normalizeDesktops(raw) {+ const list = raw && Array.isArray(raw.desktops) ? raw.desktops : [];+ return list+ .filter((/** @type {any} */ d) => typeof d.machine_id === 'string' && DESKTOP_ID_RE.test(d.machine_id))+ .map((/** @type {any} */ d) => ({+ id: d.machine_id,+ flyMachineId: typeof d.fly_machine_id === 'string' && FLY_ID_RE.test(d.fly_machine_id) ? d.fly_machine_id : null,+ name: String(d.name ?? ''),+ displayName: d.display_name ? String(d.display_name) : null,+ state: d.state ?? null,+ heartbeatStatus: d.heartbeat_status ?? null,+ heartbeatAt: typeof d.last_heartbeat_at === 'number' ? d.last_heartbeat_at : null,+ ready: d.ready === true,+ }));+}++/**+ * @param {any} raw+ * @returns {import('./types.mjs').ExecResult}+ */+export function normalizeExec(raw) {+ if (typeof raw === 'string') return { stdout: raw, stderr: '', exitCode: null };+ const r = raw ?? {};+ const exit = r.exit_code ?? r.exitCode ?? r.code ?? r.status;+ return {+ stdout: String(r.stdout ?? r.output ?? ''),+ stderr: String(r.stderr ?? ''),+ exitCode: typeof exit === 'number' ? exit : null,+ };+}++/**+ * Fleet control-plane operations bound to one client.+ * @param {FleetMcpClient} client+ * @returns {import('./types.mjs').Fleet}+ */+export function createFleet(client) {+ return {+ listDesktops: async () => normalizeDesktops(await client.callTool('desktop_status', {})),+ start: async (id) => { await client.callTool('desktop_start', { machine_id: id }); },+ stop: async (id) => { await client.callTool('desktop_stop', { machine_id: id }); },+ keepAwake: async (fly, minutes) => {+ await client.callTool('desktop_keepawake', { machine: fly, minutes });+ },+ };+}++/**+ * @param {FleetMcpClient} client+ * @returns {import('./types.mjs').Transport}+ */+export function createFleetTransport(client) {+ return {+ kind: 'fleet-mcp',+ exec: async (desktop, command, timeoutSecs) => {+ const timeout = Math.max(1, Math.min(300, Math.floor(timeoutSecs)));+ // desktop_exec's `machine` takes the Fly machine id (desktop_connect_info).+ const machine = desktop.flyMachineId ?? desktop.id;+ return normalizeExec(await client.callTool('desktop_exec', { command, machine, timeout_secs: timeout }));+ },+ };+}diff --git a/plugins/ruflo-ruos/scripts/lib/ledger.mjs b/plugins/ruflo-ruos/scripts/lib/ledger.mjsnew file mode 100644index 0000000000..a9da766556--- /dev/null+++ b/plugins/ruflo-ruos/scripts/lib/ledger.mjs@@ -0,0 +1,171 @@+// @ts-check+/**+ * Swarm ledger (ADR-405 §Swarm state and claims).+ *+ * Remote agents are recorded through ruflo's EXISTING paths, called+ * in-process via `callMCPTool` (so ADR-324 policy applies to every write):+ * - agent store: agent_spawn / agent_update / agent_terminate+ * (`.claude-flow/agents/store.json`), host in `config.host`+ * - work claims: claims_claim / claims_release (`.claude-flow/claims/`)+ * No new claims system and no direct writes into those stores.+ *+ * The plugin additionally owns `.claude-flow/ruos/`:+ * events.jsonl append-only lifecycle events (ids/sizes/states only)+ * hosts.json snapshot of the caller's desktops + which agents run there+ * runs/<id>.log local copy of the remote output (mode 0600)+ * If ruflo's CLI cannot be resolved, or policy denies a call, the ledger+ * degrades to these plugin files and reports `swarmLedger: 'unavailable'`.+ */+import { appendFileSync, mkdirSync, writeFileSync, renameSync, existsSync } from 'node:fs';+import { join } from 'node:path';+import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';++/**+ * @typedef {(name: string, input: Record<string, unknown>) => Promise<any>} CallTool+ */++/**+ * @typedef {object} Ledger+ * @property {'cli'|'unavailable'} swarmLedger+ * @property {(agentId: string, agentType: string, host: import('./types.mjs').HostRef, task: string) => Promise<void>} registerAgent+ * @property {(agentId: string, status: 'busy'|'idle', lastResult?: Record<string, unknown>) => Promise<void>} updateAgent+ * @property {(agentId: string) => Promise<void>} terminateAgent+ * @property {(runId: string, agentId: string, agentType: string) => Promise<boolean>} claim+ * @property {(runId: string, agentId: string, agentType: string) => Promise<void>} release+ * @property {(e: Omit<import('./types.mjs').RuosEvent, 'ts'>) => void} event+ * @property {(desktops: import('./types.mjs').Desktop[], agentsByDesktop: Record<string, string[]>) => void} snapshotHosts+ * @property {(runId: string, chunk: Buffer) => void} appendOutput+ * @property {string[]} warnings+ */++/**+ * Same project-root rule as ruflo's getProjectCwd(), so the plugin's files+ * land beside the agent and claims stores it writes through.+ * @param {NodeJS.ProcessEnv} env+ */+export function projectCwd(env) {+ const e = env.CLAUDE_FLOW_CWD;+ return e && e !== '/' && e !== env.HOME ? e : process.cwd();+}++/**+ * Locate ruflo's in-process tool dispatcher without depending on it.+ * @param {string} cwd+ * @param {NodeJS.ProcessEnv} env+ * @returns {Promise<CallTool|null>}+ */+export async function resolveCallTool(cwd, env) {+ const candidates = [];+ if (env.RUFLO_CLI_MCP_CLIENT) candidates.push(env.RUFLO_CLI_MCP_CLIENT);+ try {+ const req = createRequire(join(cwd, 'noop.js'));+ for (const pkg of ['@claude-flow/cli', 'ruflo', 'claude-flow']) {+ try {+ const pj = req.resolve(`${pkg}/package.json`);+ const base = pkg === '@claude-flow/cli' ? pj.replace(/package\.json$/, '') : null;+ if (base) candidates.push(join(base, 'dist/src/mcp-client.js'));+ else candidates.push(join(pj.replace(/package\.json$/, ''), 'node_modules/@claude-flow/cli/dist/src/mcp-client.js'));+ } catch { /* not installed here */ }+ }+ } catch { /* createRequire failed */ }+ for (const file of candidates) {+ if (!existsSync(file)) continue;+ try {+ const mod = await import(pathToFileURL(file).href);+ if (typeof mod.callMCPTool === 'function') return mod.callMCPTool;+ } catch { /* try next */ }+ }+ return null;+}++/**+ * @param {{ cwd: string, callTool: CallTool|null, now?: () => Date }} o+ * @returns {Ledger}+ */+export function createLedger({ cwd, callTool, now = () => new Date() }) {+ const dir = join(cwd, '.claude-flow', 'ruos');+ const runsDir = join(dir, 'runs');+ /** @type {string[]} */+ const warnings = [];+ let available = callTool !== null;++ const ensure = () => mkdirSync(runsDir, { recursive: true, mode: 0o700 });++ /**+ * Call a ruflo tool; on policy denial / missing tool, degrade instead of+ * failing the remote run.+ * @param {string} name+ * @param {Record<string, unknown>} input+ */+ const safeCall = async (name, input) => {+ if (!available || !callTool) return null;+ try {+ const r = await callTool(name, input);+ if (r && r.success === false) {+ warnings.push(`${name}: ${String(r.error ?? 'failed').slice(0, 160)}`);+ return r;+ }+ return r;+ } catch (err) {+ const msg = String(/** @type {Error} */ (err)?.message ?? err);+ warnings.push(`${name}: ${msg.slice(0, 160)}`);+ if (/not found|policy-/i.test(msg)) available = false;+ return null;+ }+ };++ /** @type {Ledger} */+ const ledger = {+ get swarmLedger() { return available ? 'cli' : 'unavailable'; },+ warnings,+ async registerAgent(agentId, agentType, host, task) {+ await safeCall('agent_spawn', {+ agentType,+ agentId,+ domain: 'ruos',+ config: { host, remote: true, taskSummary: task.slice(0, 120) },+ });+ await safeCall('agent_update', { agentId, status: 'busy' });+ },+ async updateAgent(agentId, status, lastResult) {+ await safeCall('agent_update', { agentId, status, ...(lastResult ? { config: { lastRemoteResult: lastResult } } : {}) });+ },+ async terminateAgent(agentId) {+ await safeCall('agent_terminate', { agentId });+ },+ async claim(runId, agentId, agentType) {+ const r = await safeCall('claims_claim', { issueId: `ruos-run-${runId}`, claimant: `agent:${agentId}:${agentType}` });+ return r === null || r.success !== false;+ },+ async release(runId, agentId, agentType) {+ await safeCall('claims_release', { issueId: `ruos-run-${runId}`, claimant: `agent:${agentId}:${agentType}` });+ },+ event(e) {+ ensure();+ appendFileSync(join(dir, 'events.jsonl'), JSON.stringify({ ts: now().toISOString(), ...e }) + '\n', { mode: 0o600 });+ },+ snapshotHosts(desktops, agentsByDesktop) {+ ensure();+ const snap = {+ updatedAt: now().toISOString(),+ hosts: desktops.map((d) => ({+ desktopId: d.id,+ name: d.displayName ?? d.name,+ state: d.state,+ heartbeatStatus: d.heartbeatStatus,+ heartbeatAt: d.heartbeatAt,+ agents: agentsByDesktop[d.id] ?? [],+ })),+ };+ const tmp = join(dir, `hosts.json.${process.pid}.tmp`);+ writeFileSync(tmp, JSON.stringify(snap, null, 2), { mode: 0o600 });+ renameSync(tmp, join(dir, 'hosts.json'));+ },+ appendOutput(runId, chunk) {+ ensure();+ appendFileSync(join(runsDir, `${runId}.log`), chunk, { mode: 0o600 });+ },+ };+ return ledger;+}diff --git a/plugins/ruflo-ruos/scripts/lib/ssh.mjs b/plugins/ruflo-ruos/scripts/lib/ssh.mjsnew file mode 100644index 0000000000..2bb2a3e3ab--- /dev/null+++ b/plugins/ruflo-ruos/scripts/lib/ssh.mjs@@ -0,0 +1,114 @@+// @ts-check+/**+ * Per-tenant SSH transport (ADR-405 transport 2, ruOS ADR-053 Phase 2).+ *+ * sshd on :2222 is pubkey-only and armed with the tenant's own fleet-minted+ * ed25519 key, so it is the sound peer-to-peer path — but it lives on the+ * Fly 6PN, so it only works when ruflo itself runs on a same-tenant ruOS+ * desktop. The ssh binary is spawned with a FIXED argv (no shell), and the+ * remote command is a builder-produced string (command-builder.mjs).+ */+import { spawn as nodeSpawn } from 'node:child_process';+import { RuosError } from './types.mjs';+import { SSH_USER_RE, FLY_APP_RE, FLY_ID_RE } from './validate.mjs';++export const SSH_PORT = 2222;++/**+ * @typedef {object} SshOptions+ * @property {string} keyPath path to the tenant's ed25519 private key+ * @property {string=} user remote user (default 'ruv')+ * @property {string=} app Fly app name (default 'ruos-desktop')+ * @property {typeof nodeSpawn=} spawnImpl+ */++/** @param {NodeJS.ProcessEnv} env */+export function sshConfigFromEnv(env) {+ return {+ keyPath: env.RUOS_SSH_KEY || undefined,+ user: env.RUOS_SSH_USER || 'ruv',+ app: env.RUOS_FLY_APP || 'ruos-desktop',+ };+}++/**+ * @param {import('./types.mjs').Desktop} desktop+ * @param {string} app+ */+export function sshHostFor(desktop, app) {+ if (!desktop.flyMachineId || !FLY_ID_RE.test(desktop.flyMachineId)) {+ throw new RuosError('invalid-input', 'desktop has no Fly machine id; SSH needs a cloud desktop');+ }+ if (!FLY_APP_RE.test(app)) throw new RuosError('invalid-input', 'RUOS_FLY_APP is invalid');+ return `${desktop.flyMachineId}.vm.${app}.internal`;+}++/**+ * The full ssh argv. Exported so tests can assert it is fixed.+ * @param {{ keyPath: string, user: string, host: string, command: string, connectTimeout?: number }} a+ * @returns {string[]}+ */+export function buildSshArgv(a) {+ if (!SSH_USER_RE.test(a.user)) throw new RuosError('invalid-input', 'ssh user is invalid');+ if (typeof a.keyPath !== 'string' || a.keyPath.length === 0 || a.keyPath.startsWith('-')) {+ throw new RuosError('invalid-input', 'ssh key path is invalid');+ }+ return [+ '-p', String(SSH_PORT),+ '-i', a.keyPath,+ '-o', 'BatchMode=yes',+ '-o', 'IdentitiesOnly=yes',+ '-o', 'StrictHostKeyChecking=accept-new',+ '-o', `ConnectTimeout=${a.connectTimeout ?? 5}`,+ '-o', 'ServerAliveInterval=15',+ '-l', a.user,+ '--',+ a.host,+ a.command,+ ];+}++/**+ * @param {SshOptions} opts+ * @returns {import('./types.mjs').Transport}+ */+export function createSshTransport(opts) {+ if (!opts.keyPath) throw new RuosError('not-configured', 'set RUOS_SSH_KEY to the tenant ed25519 key to use the ssh transport');+ const spawnImpl = opts.spawnImpl ?? nodeSpawn;+ const user = opts.user ?? 'ruv';+ const app = opts.app ?? 'ruos-desktop';+ return {+ kind: 'ssh',+ exec: (desktop, command, timeoutSecs) =>+ new Promise((resolve, reject) => {+ const argv = buildSshArgv({ keyPath: /** @type {string} */ (opts.keyPath), user, host: sshHostFor(desktop, app), command });+ const child = spawnImpl('ssh', argv, { stdio: ['ignore', 'pipe', 'pipe'], shell: false });+ /** @type {Buffer[]} */ const out = [];+ /** @type {Buffer[]} */ const err = [];+ const timer = setTimeout(() => {+ child.kill('SIGTERM');+ reject(new RuosError('timeout', `ssh command timed out after ${timeoutSecs}s`));+ }, Math.max(1, timeoutSecs) * 1000);+ child.stdout?.on('data', (b) => out.push(b));+ child.stderr?.on('data', (b) => err.push(b));+ child.on('error', (e) => {+ clearTimeout(timer);+ reject(new RuosError('network-down', 'ssh could not start', e));+ });+ child.on('close', (code) => {+ clearTimeout(timer);+ const stderr = Buffer.concat(err).toString('utf8');+ // 255 is ssh's own failure (connect/auth), not the remote command's.+ if (code === 255) {+ if (/permission denied|publickey/i.test(stderr)) {+ reject(new RuosError('auth-expired', 'ssh key refused (desktop not armed with this tenant key?)'));+ } else {+ reject(new RuosError('network-down', 'ssh connection failed (6PN unreachable or desktop stopped)'));+ }+ return;+ }+ resolve({ stdout: Buffer.concat(out).toString('utf8'), stderr, exitCode: code });+ });+ }),+ };+}diff --git a/plugins/ruflo-ruos/scripts/lib/types.mjs b/plugins/ruflo-ruos/scripts/lib/types.mjsnew file mode 100644index 0000000000..2c542f76c8--- /dev/null+++ b/plugins/ruflo-ruos/scripts/lib/types.mjs@@ -0,0 +1,100 @@+// @ts-check+/**+ * Shared types and the typed error for ruflo-ruos (ADR-405).+ *+ * Plain .mjs with JSDoc so the plugin needs no build step; `tsc --checkJs`+ * type-checks it (see scripts/typecheck.sh).+ */++/**+ * A desktop the caller owns, normalised from the fleet `desktop_status` tool.+ * @typedef {object} Desktop+ * @property {string} id fleet registry machine id (32 hex)+ * @property {string|null} flyMachineId Fly machine id (14 hex) or null for enrolled endpoints+ * @property {string} name+ * @property {string|null} displayName+ * @property {string|null} state last observed Fly run state ('started', 'stopped', ...)+ * @property {string|null} heartbeatStatus 'asleep' | 'stale' | 'missing' | other (live)+ * @property {number|null} heartbeatAt unix seconds of the last heartbeat+ * @property {boolean} ready provisioning flag — NOT liveness+ */++/**+ * The single seam between the adapter and a remote desktop. Both transports+ * run the same one-line shell strings produced by command-builder.mjs.+ * @typedef {object} ExecResult+ * @property {string} stdout+ * @property {string} stderr+ * @property {number|null} exitCode+ */++/**+ * @typedef {object} Transport+ * @property {'fleet-mcp'|'ssh'} kind+ * @property {(desktop: Desktop, command: string, timeoutSecs: number) => Promise<ExecResult>} exec+ */++/**+ * Fleet control-plane calls (always the tenant-authenticated fleet MCP).+ * @typedef {object} Fleet+ * @property {() => Promise<Desktop[]>} listDesktops+ * @property {(id: string) => Promise<void>} start+ * @property {(id: string) => Promise<void>} stop+ * @property {(flyMachineId: string|null, minutes: number) => Promise<void>} keepAwake+ */++/**+ * What the swarm ledger records about one remote agent.+ * @typedef {object} HostRef+ * @property {'ruos'} kind+ * @property {string} desktopId+ * @property {string} desktopName+ * @property {'fleet-mcp'|'ssh'} transport+ * @property {string} runId+ */++/**+ * @typedef {object} RunSpec+ * @property {string} runId+ * @property {string} prompt+ * @property {'claude'} runner+ * @property {('haiku'|'sonnet'|'opus')=} model+ * @property {number=} maxBudgetUsd+ */++/**+ * @typedef {'run.started'|'run.output'|'run.completed'|'run.failed'|'run.stopped'|'desktop.state'} EventType+ */++/**+ * Event-log row. Carries ids, sizes and states only — never prompt text or+ * agent output (those stay in the per-run local log, mode 0600).+ * @typedef {object} RuosEvent+ * @property {string} ts+ * @property {EventType} type+ * @property {string=} runId+ * @property {string=} agentId+ * @property {string=} desktopId+ * @property {string=} desktopName+ * @property {number=} bytes+ * @property {number|null=} exitCode+ * @property {string=} error+ * @property {string=} state+ */++/** @typedef {'not-configured'|'invalid-input'|'not-owned'|'ambiguous'|'confirm-required'|'auth-expired'|'network-down'|'desktop-stopped'|'auto-stopped'|'autostop-window'|'tool-error'|'remote-error'|'timeout'} RuosErrorCode */++export class RuosError extends Error {+ /**+ * @param {RuosErrorCode} code+ * @param {string} message+ * @param {unknown=} cause+ */+ constructor(code, message, cause) {+ super(message);+ this.name = 'RuosError';+ /** @type {RuosErrorCode} */+ this.code = code;+ if (cause !== undefined) this.cause = cause;+ }+}diff --git a/plugins/ruflo-ruos/scripts/lib/validate.mjs b/plugins/ruflo-ruos/scripts/lib/validate.mjsnew file mode 100644index 0000000000..1c0956ef18--- /dev/null+++ b/plugins/ruflo-ruos/scripts/lib/validate.mjs@@ -0,0 +1,133 @@+// @ts-check+/**+ * Input validation at the plugin boundary (ADR-405 §Security).+ *+ * Every id that reaches a remote command is checked against a strict+ * allow-list pattern here, and every desktop reference is resolved against+ * the caller's OWN desktop list — never passed through as given.+ */+import { RuosError } from './types.mjs';++/** fleet registry id — 32 lowercase hex */+export const DESKTOP_ID_RE = /^[0-9a-f]{32}$/;+/** Fly machine id — 14 lowercase hex */+export const FLY_ID_RE = /^[0-9a-f]{14}$/;+/** run id — also embedded in remote paths, so no separators beyond '-' */+export const RUN_ID_RE = /^[a-z0-9][a-z0-9-]{5,62}$/;+/** agent id / type — subset of ruflo's validateIdentifier charset */+export const AGENT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;+export const SSH_USER_RE = /^[a-z_][a-z0-9_-]{0,31}$/;+export const FLY_APP_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;+export const MODELS = /** @type {const} */ (['haiku', 'sonnet', 'opus']);++export const MAX_PROMPT_BYTES = 64 * 1024;++/**+ * @param {unknown} v+ * @param {RegExp} re+ * @param {string} label+ * @returns {string}+ */+export function assertMatch(v, re, label) {+ if (typeof v !== 'string' || !re.test(v)) {+ throw new RuosError('invalid-input', `${label} is invalid`);+ }+ return v;+}++/** @param {unknown} v */+export const assertRunId = (v) => assertMatch(v, RUN_ID_RE, 'runId');+/** @param {unknown} v */+export const assertAgentId = (v) => assertMatch(v, AGENT_ID_RE, 'agentId');++/**+ * @param {unknown} v+ * @param {number} min+ * @param {number} max+ * @param {string} label+ * @returns {number}+ */+export function assertInt(v, min, max, label) {+ const n = typeof v === 'string' && /^\d+$/.test(v) ? Number(v) : v;+ if (typeof n !== 'number' || !Number.isInteger(n) || n < min || n > max) {+ throw new RuosError('invalid-input', `${label} must be an integer in [${min}, ${max}]`);+ }+ return n;+}++/**+ * @param {unknown} v+ * @returns {'haiku'|'sonnet'|'opus'|undefined}+ */+export function assertModel(v) {+ if (v === undefined || v === null || v === '') return undefined;+ if (typeof v === 'string' && /** @type {readonly string[]} */ (MODELS).includes(v)) {+ return /** @type {'haiku'|'sonnet'|'opus'} */ (v);+ }+ throw new RuosError('invalid-input', `model must be one of ${MODELS.join(', ')}`);+}++/**+ * A budget cap is printed into the remote command, so it is reduced to a+ * canonical decimal string here (no exponent, no sign, two decimals max).+ * @param {unknown} v+ * @returns {number|undefined}+ */+export function assertBudget(v) {+ if (v === undefined || v === null || v === '') return undefined;+ const n = typeof v === 'string' && /^\d{1,4}(\.\d{1,2})?$/.test(v) ? Number(v) : v;+ if (typeof n !== 'number' || !Number.isFinite(n) || n <= 0 || n > 1000) {+ throw new RuosError('invalid-input', 'maxBudgetUsd must be a number in (0, 1000]');+ }+ return Math.round(n * 100) / 100;+}++/**+ * Prompt text never enters a command line verbatim (it is base64-encoded by+ * the builder), but it is still bounded and must be valid text.+ * @param {unknown} v+ * @returns {string}+ */+export function assertPrompt(v) {+ if (typeof v !== 'string' || v.trim().length === 0) {+ throw new RuosError('invalid-input', 'prompt must be a non-empty string');+ }+ if (Buffer.byteLength(v, 'utf8') > MAX_PROMPT_BYTES) {+ throw new RuosError('invalid-input', `prompt exceeds ${MAX_PROMPT_BYTES} bytes`);+ }+ if (v.includes('\0')) throw new RuosError('invalid-input', 'prompt contains NUL');+ return v;+}++/**+ * Resolve a user-supplied desktop reference (registry id, Fly id, name or+ * display name) against the caller's own desktops. Anything not in that+ * list is refused — this is what keeps a typo, a stale id or a forged id+ * from ever reaching a transport.+ * @param {import('./types.mjs').Desktop[]} owned+ * @param {unknown} ref+ * @returns {import('./types.mjs').Desktop}+ */+export function resolveDesktop(owned, ref) {+ if (typeof ref !== 'string' || ref.length === 0 || ref.length > 128) {+ throw new RuosError('invalid-input', 'desktop reference is invalid');+ }+ const byId = owned.filter((d) => d.id === ref || (d.flyMachineId !== null && d.flyMachineId === ref));+ if (byId.length === 1) return byId[0];+ const byName = owned.filter((d) => d.name === ref || d.displayName === ref);+ if (byName.length === 1) return byName[0];+ if (byName.length > 1) {+ throw new RuosError('ambiguous', `desktop name matches ${byName.length} desktops; use its machine id`);+ }+ throw new RuosError('not-owned', 'desktop is not in your desktop_status list');+}++/**+ * A deterministic-length, path-safe run id.+ * @param {() => number} now+ * @param {(n: number) => Buffer} randomBytes+ * @returns {string}+ */+export function newRunId(now, randomBytes) {+ return `r-${now().toString(36)}-${randomBytes(4).toString('hex')}`;+}diff --git a/plugins/ruflo-ruos/tests/adapter.test.mjs b/plugins/ruflo-ruos/tests/adapter.test.mjsnew file mode 100644index 0000000000..9be9074ddb--- /dev/null+++ b/plugins/ruflo-ruos/tests/adapter.test.mjs@@ -0,0 +1,183 @@+// @ts-check+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { RuosHostAdapter, isUp } from '../scripts/lib/adapter.mjs';+import { buildPromptChunks } from '../scripts/lib/command-builder.mjs';+import { RuosError } from '../scripts/lib/types.mjs';+import { desktop, fakeClock, fakeFleet, fakeTransport, fakeLedger, ok, DESKTOP_ID, FLY_ID } from './fakes.mjs';++const RUN = 'r-adapter-0001';+const PROMPT = 'write hello.txt';+const SHA = buildPromptChunks(RUN, PROMPT).sha256;+const b64 = (/** @type {string} */ s) => Buffer.from(s).toString('base64');++/**+ * Remote that answers each builder command; `polls` is consumed in order.+ * @param {string[]} polls+ * @param {{ sha?: string, launch?: string }} o+ */+function remote(polls, o = {}) {+ let i = 0;+ return fakeTransport((cmd) => {+ if (cmd.includes('RUOS_PREPARED')) return ok('RUOS_PREPARED\n');+ if (cmd.startsWith("printf '%s'")) return ok('');+ if (cmd.includes('RUOS_NO_RUNNER')) return ok(o.launch ?? `RUOS_SHA:${o.sha ?? SHA}\nRUOS_PID:4242\n`);+ if (cmd.includes('RUOS_POLL')) {+ const p = polls[Math.min(i++, polls.length - 1)];+ if (p === 'THROW') throw new RuosError('network-down', 'gone');+ return ok(p);+ }+ if (cmd.includes('RUOS_STOPPED')) return ok('RUOS_STOPPED\n');+ throw new Error(`unexpected command ${cmd.slice(0, 40)}`);+ });+}++/** @param {any} over */+function setup(over = {}) {+ const clock = fakeClock();+ const ds = over.desktops ?? [desktop({ heartbeatAt: Math.floor(clock.now() / 1000) })];+ const fleet = over.fleet ?? fakeFleet(ds);+ const transport = over.transport ?? remote([`RUOS_POLL:-:6:${b64('hello ')}`, 'RUOS_POLL:-:6:', `RUOS_POLL:0:12:${b64('world\n')}`]);+ const ledger = fakeLedger();+ const adapter = new RuosHostAdapter({ fleet, transport, ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });+ return { adapter, fleet, transport, ledger, clock };+}++const base = { desktop: 'Work Desktop', prompt: PROMPT, runId: RUN, agentId: 'ruos-agent-1', agentType: 'coder', timeoutSecs: 600 };++test('happy path: launch, stream, ledger + claims, keepawake', async () => {+ const { adapter, ledger, fleet, transport } = setup();+ /** @type {string[]} */ const seen = [];+ const out = await adapter.run({ ...base, onOutput: (c) => seen.push(c.toString()) });+ assert.equal(out.status, 'completed');+ assert.equal(out.exitCode, 0);+ assert.equal(seen.join(''), 'hello world\n');+ assert.equal(out.bytes, 12);+ assert.equal(out.desktopId, DESKTOP_ID);+ assert.ok(out.firstOutputMs !== null && out.firstOutputMs >= out.dispatchMs);+ const names = ledger.calls.map((c) => c[0]);+ assert.deepEqual(names.filter((n) => n !== 'snapshotHosts'), ['claim', 'registerAgent', 'updateAgent', 'release']);+ const host = /** @type {any} */ (ledger.calls.find((c) => c[0] === 'registerAgent'))[1][2];+ assert.deepEqual(host, { kind: 'ruos', desktopId: DESKTOP_ID, desktopName: 'Work Desktop', transport: 'fleet-mcp', runId: RUN });+ assert.deepEqual(ledger.events.map((e) => e.type), ['run.started', 'run.output', 'run.output', 'run.completed']);+ assert.ok(ledger.events.every((e) => !JSON.stringify(e).includes(PROMPT)), 'events never carry the prompt');+ assert.deepEqual(fleet.calls.find((c) => c[0] === 'keepAwake'), ['keepAwake', [FLY_ID, 15]]);+ assert.ok(!transport.commands.join('\n').includes(PROMPT), 'prompt never sent verbatim');+});++test('stopped desktop without --start is refused before any exec', async () => {+ const { adapter, transport, fleet } = setup({ desktops: [desktop({ state: 'stopped', heartbeatStatus: 'asleep' })] });+ await assert.rejects(adapter.run(base), (e) => e instanceof RuosError && e.code === 'desktop-stopped');+ assert.equal(transport.commands.length, 0);+ assert.ok(!fleet.calls.some((c) => c[0] === 'start'));+});++test('--start wakes the desktop and waits for a fresh heartbeat (not `ready`)', async () => {+ const clock = fakeClock();+ let started = false;+ /** @type {any} */ let fleet;+ fleet = fakeFleet(() => {+ const woke = started && fleet.calls.filter((/** @type {any} */ c) => c[0] === 'listDesktops').length > 3;+ return [desktop(woke ? { heartbeatAt: Math.floor(clock.now() / 1000), heartbeatStatus: 'ok', state: 'started' } : { state: 'stopped', heartbeatStatus: 'asleep', heartbeatAt: 1 })];+ });+ const origStart = fleet.start;+ fleet.start = async (/** @type {string} */ id) => { started = true; return origStart(id); };+ const ledger = fakeLedger();+ const transport = remote([`RUOS_POLL:0:2:${b64('ok')}`]);+ const adapter = new RuosHostAdapter({ fleet, transport, ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });+ const out = await adapter.run({ ...base, allowStart: true });+ assert.equal(out.status, 'completed');+ assert.deepEqual(fleet.calls.find((/** @type {any} */ c) => c[0] === 'start'), ['start', [DESKTOP_ID]]);+ assert.ok(ledger.events.some((e) => e.type === 'desktop.state' && e.state === 'started'));+});++test('desktop auto-stopped mid-run is reported as auto-stopped and released', async () => {+ const clock = fakeClock();+ let calls = 0;+ const fleet = fakeFleet(() => [desktop(++calls <= 1 ? { heartbeatAt: Math.floor(clock.now() / 1000) } : { state: 'stopped', heartbeatStatus: 'asleep' })]);+ const ledger = fakeLedger();+ const adapter = new RuosHostAdapter({ fleet, transport: remote([`RUOS_POLL:-:2:${b64('hi')}`, 'THROW']), ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });+ await assert.rejects(adapter.run(base), (e) => e instanceof RuosError && e.code === 'auto-stopped');+ assert.ok(ledger.calls.some((c) => c[0] === 'release'), 'claim released on failure');+ assert.equal(ledger.events.at(-1).type, 'run.failed');+ assert.equal(ledger.events.at(-1).error, 'auto-stopped');+});++test('auth expired mid-run surfaces as auth-expired', async () => {+ const { adapter } = setup({ transport: remote(['THROW']) });+ // make the poll throw auth-expired instead of network-down+ const t = fakeTransport((cmd) => {+ if (cmd.includes('RUOS_POLL')) throw new RuosError('auth-expired', 'token expired');+ if (cmd.includes('RUOS_NO_RUNNER')) return ok(`RUOS_SHA:${SHA}\nRUOS_PID:1\n`);+ return ok('RUOS_PREPARED\n');+ });+ adapter.transport = t;+ await assert.rejects(adapter.run(base), (e) => e instanceof RuosError && e.code === 'auth-expired');+});++test('network down while desktop is still up stays network-down', async () => {+ const { adapter } = setup({ transport: remote(['THROW']) });+ await assert.rejects(adapter.run(base), (e) => e instanceof RuosError && e.code === 'network-down');+});++test('prompt integrity mismatch aborts before streaming', async () => {+ const { adapter, ledger } = setup({ transport: remote([], { sha: 'f'.repeat(64) }) });+ await assert.rejects(adapter.run(base), /integrity/);+ assert.ok(!ledger.events.some((e) => e.type === 'run.started'));+});++test('missing runner on the desktop is a clear error', async () => {+ const { adapter } = setup({ transport: remote([], { launch: 'RUOS_NO_RUNNER\n' }) });+ await assert.rejects(adapter.run(base), /not installed/);+});++test('a run that would cross the 23:00 Toronto auto-stop is refused unless overridden', async () => {+ const clock = fakeClock(Date.parse('2026-10-02T02:45:00Z')); // Thu 22:45 EDT+ const fleet = fakeFleet([desktop({ heartbeatAt: Math.floor(clock.now() / 1000) })]);+ const transport = remote([`RUOS_POLL:0:0:`]);+ const adapter = new RuosHostAdapter({ fleet, transport, ledger: /** @type {any} */ (fakeLedger()), now: clock.now, sleep: clock.sleep });+ await assert.rejects(adapter.run({ ...base, timeoutSecs: 3600 }), (e) => e instanceof RuosError && e.code === 'autostop-window');+ assert.equal(transport.commands.length, 0);+ const out = await adapter.run({ ...base, timeoutSecs: 3600, ignoreAutoStop: true });+ assert.equal(out.status, 'completed');+});++test('run timeout stops the remote process group', async () => {+ const { adapter, transport } = setup({ transport: remote(['RUOS_POLL:-:0:']) });+ await assert.rejects(adapter.run({ ...base, timeoutSecs: 30 }), (e) => e instanceof RuosError && e.code === 'timeout');+ assert.ok(transport.commands.at(-1)?.includes('RUOS_STOPPED'));+});++test('abort signal stops the run and records run.stopped', async () => {+ const ac = new AbortController();+ const { adapter, ledger } = setup({ transport: remote([`RUOS_POLL:-:1:${b64('x')}`, 'RUOS_POLL:-:1:']) });+ const p = adapter.run({ ...base, signal: ac.signal, onOutput: () => ac.abort() });+ const out = await p;+ assert.equal(out.status, 'stopped');+ assert.equal(ledger.events.at(-1).type, 'run.stopped');+});++test('foreign desktop ids never reach a transport', async () => {+ const { adapter, transport } = setup();+ await assert.rejects(adapter.run({ ...base, desktop: 'ffffffffffffffffffffffffffffffff' }), (e) => e instanceof RuosError && e.code === 'not-owned');+ assert.equal(transport.commands.length, 0);+});++test('destructive ops require explicit confirm', async () => {+ const { adapter, fleet, transport } = setup();+ await assert.rejects(adapter.stopRun({ desktop: 'Work Desktop', runId: RUN }), (e) => e instanceof RuosError && e.code === 'confirm-required');+ await assert.rejects(adapter.stopDesktop({ desktop: 'Work Desktop' }), (e) => e instanceof RuosError && e.code === 'confirm-required');+ assert.equal(transport.commands.length, 0);+ assert.ok(!fleet.calls.some((c) => c[0] === 'stop'));+ assert.deepEqual(await adapter.stopRun({ desktop: 'Work Desktop', runId: RUN, confirm: true }), { runId: RUN, desktopId: DESKTOP_ID, stopped: true });+ await adapter.stopDesktop({ desktop: 'Work Desktop', confirm: true });+ assert.deepEqual(fleet.calls.find((c) => c[0] === 'stop'), ['stop', [DESKTOP_ID]]);+});++test('isUp uses heartbeat freshness, not `ready`', () => {+ const now = Date.UTC(2026, 9, 1, 15, 0, 0);+ assert.equal(isUp(desktop({ heartbeatAt: now / 1000 - 10 }), now), true);+ assert.equal(isUp(desktop({ heartbeatAt: now / 1000 - 1000 }), now), false);+ assert.equal(isUp(desktop({ heartbeatStatus: 'asleep', heartbeatAt: now / 1000 }), now), false);+ assert.equal(isUp(desktop({ heartbeatAt: null, ready: true }), now), false);+});diff --git a/plugins/ruflo-ruos/tests/command-builder.test.mjs b/plugins/ruflo-ruos/tests/command-builder.test.mjsnew file mode 100644index 0000000000..ec3878f913--- /dev/null+++ b/plugins/ruflo-ruos/tests/command-builder.test.mjs@@ -0,0 +1,151 @@+// @ts-check+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { execFileSync, execSync } from 'node:child_process';+import { mkdtempSync, writeFileSync, chmodSync, existsSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ buildPrepare, buildPromptChunks, buildLaunch, buildPoll, buildStop, buildProbe,+ parsePoll, parseLaunch, MAX_COMMAND_BYTES,+} from '../scripts/lib/command-builder.mjs';+import { RuosError } from '../scripts/lib/types.mjs';++const RUN = 'r-test-abc123';+const HOSTILE = [+ '$(touch /tmp/ruflo-ruos-pwned)',+ '`touch /tmp/ruflo-ruos-pwned`',+ "'; touch /tmp/ruflo-ruos-pwned; echo '",+ '"; touch /tmp/ruflo-ruos-pwned; echo "',+ 'a\ntouch /tmp/ruflo-ruos-pwned',+ 'a\r\ntouch /tmp/ruflo-ruos-pwned',+ '${IFS}touch${IFS}/tmp/ruflo-ruos-pwned',+ '| touch /tmp/ruflo-ruos-pwned &',+ 'ünïcödé ✓ 🚀 rtl',+ '\\x27 \\" %s %n',+];++/** Every variable region must be a validated id, an int, an enum, or base64. */+function assertOnlyExpectedRegions(/** @type {string} */ cmd) {+ assert.ok(!/[\n\r\0]/.test(cmd), 'single line');+ assert.ok(Buffer.byteLength(cmd) <= MAX_COMMAND_BYTES, 'size');+ assert.ok(!cmd.includes('ruflo-ruos-pwned'), 'task text must never appear verbatim');+ // Strip the single-quoted payloads; what remains is fixed template text.+ const outsideQuotes = cmd.replace(/'[^']*'/g, "''");+ assert.ok(!/[`]/.test(outsideQuotes), 'no backticks outside quotes');+}++test('prompt chunks carry only base64 inside single quotes', () => {+ for (const p of HOSTILE) {+ const { commands } = buildPromptChunks(RUN, p);+ for (const c of commands) {+ assertOnlyExpectedRegions(c);+ const m = /^printf '%s' '([^']*)' >> "\$HOME\/\.ruflo-ruos\/runs\/r-test-abc123"\/prompt\.b64$/.exec(c);+ assert.ok(m, `chunk shape: ${c.slice(0, 80)}`);+ assert.match(m[1], /^[A-Za-z0-9+/=]+$/);+ }+ }+});++test('chunking respects the 4000-byte limit at the boundaries', () => {+ const head = `printf '%s' '`.length + `' >> "$HOME/.ruflo-ruos/runs/${RUN}"/prompt.b64`.length;+ const room = MAX_COMMAND_BYTES - head;+ const step = room - (room % 4);+ const bytesForB64 = (/** @type {number} */ n) => (n / 4) * 3;+ for (const b64len of [step - 4, step, step + 4, 3 * step]) {+ const p = 'x'.repeat(bytesForB64(b64len));+ const { commands } = buildPromptChunks(RUN, p);+ for (const c of commands) assert.ok(Buffer.byteLength(c) <= MAX_COMMAND_BYTES);+ assert.equal(commands.length, Math.ceil(b64len / step));+ const joined = commands.map((c) => /'([A-Za-z0-9+/=]+)'/.exec(c)?.[1]).join('');+ assert.equal(Buffer.from(joined, 'base64').toString(), p);+ }+});++test('hostile run ids, models, budgets and offsets are refused', () => {+ for (const bad of ['../etc', 'r-x"; id', 'R-UPPER1', 'a', 'r-$(id)xx', 'r-ok\nnew', '']) {+ assert.throws(() => buildPrepare(bad), RuosError);+ assert.throws(() => buildPoll(bad, 0), RuosError);+ assert.throws(() => buildStop(bad), RuosError);+ }+ const base = { runId: RUN, prompt: 'x', runner: /** @type {'claude'} */ ('claude') };+ assert.throws(() => buildLaunch({ ...base, model: /** @type {any} */ ('opus; id') }), RuosError);+ assert.throws(() => buildLaunch({ ...base, maxBudgetUsd: /** @type {any} */ ('1e9') }), RuosError);+ assert.throws(() => buildLaunch({ ...base, maxBudgetUsd: -1 }), RuosError);+ assert.throws(() => buildLaunch({ ...base, runner: /** @type {any} */ ('bash') }), RuosError);+ assert.throws(() => buildPoll(RUN, -1), RuosError);+ assert.throws(() => buildPoll(RUN, /** @type {any} */ ('1;id')), RuosError);+ assert.throws(() => buildPromptChunks(RUN, 'a\0b'), RuosError);+ assert.throws(() => buildPromptChunks(RUN, ' '), RuosError);+ assert.throws(() => buildPromptChunks(RUN, 'x'.repeat(64 * 1024 + 1)), RuosError);+});++test('launch/poll/stop/probe are single fixed-template lines', () => {+ const cmds = [+ buildPrepare(RUN),+ buildLaunch({ runId: RUN, prompt: HOSTILE[0], runner: 'claude', model: 'haiku', maxBudgetUsd: 0.5 }),+ buildPoll(RUN, 12345),+ buildStop(RUN),+ buildProbe(),+ ];+ for (const c of cmds) assertOnlyExpectedRegions(c);+ assert.match(cmds[1], /--model haiku --max-budget-usd 0\.50/);+ assert.ok(!cmds.join(' ').includes('17870'), 'never targets the executor port');+});++test('parsePoll / parseLaunch', () => {+ assert.equal(parsePoll('RUOS_NORUN\n'), 'norun');+ const p = parsePoll(`RUOS_POLL:0:5:${Buffer.from('hello').toString('base64')}\n`);+ assert.deepEqual([p !== 'norun' && p.exitCode, p !== 'norun' && p.size, p !== 'norun' && p.chunk.toString()], [0, 5, 'hello']);+ const r = parsePoll('RUOS_POLL:-:0:\n');+ assert.equal(r !== 'norun' && r.exitCode, null);+ assert.throws(() => parsePoll('garbage'), RuosError);+ const l = parseLaunch(`RUOS_SHA:${'a'.repeat(64)}\nRUOS_PID:42\n`);+ assert.deepEqual(l, { sha256: 'a'.repeat(64), pid: 42, noRunner: false });+ assert.equal(parseLaunch('RUOS_NO_RUNNER').noRunner, true);+});++// Real-shell execution of the builder output against a fake `claude`, so the+// quoting is proven by /bin/sh itself, not only by pattern assertions.+const hasShell = (() => { try { execSync('command -v base64 setsid nohup sha256sum', { shell: '/bin/sh' }); return true; } catch { return false; } })();++test('real /bin/sh: hostile prompt round-trips inert; run completes and stops', { skip: !hasShell }, async () => {+ const root = mkdtempSync(join(tmpdir(), 'ruflo-ruos-'));+ const home = join(root, 'home');+ const bin = join(root, 'bin');+ execFileSync('mkdir', ['-p', home, bin]);+ writeFileSync(join(bin, 'claude'), '#!/bin/sh\necho "ARGS:$*"; cat; sleep "${FAKE_SLEEP:-0}"; echo done\n');+ chmodSync(join(bin, 'claude'), 0o755);+ const env = { HOME: home, PATH: `${bin}:/usr/bin:/bin`, FAKE_SLEEP: '0' };+ const sh = (/** @type {string} */ c, /** @type {Record<string,string>} */ e = env) => execSync(c, { shell: '/bin/sh', env: e, encoding: 'utf8' });+ const prompt = HOSTILE.join('\n');+ const marker = '/tmp/ruflo-ruos-pwned';+ const before = existsSync(marker);++ sh(buildPrepare(RUN));+ const chunks = buildPromptChunks(RUN, prompt);+ for (const c of chunks.commands) sh(c);+ const launched = parseLaunch(sh(buildLaunch({ runId: RUN, prompt, runner: 'claude', model: 'sonnet' })));+ assert.equal(launched.sha256, chunks.sha256);+ assert.ok(launched.pid);+ let p;+ for (let i = 0; i < 50; i++) {+ p = parsePoll(sh(buildPoll(RUN, 0)));+ if (p !== 'norun' && p.exitCode !== null) break;+ await new Promise((r) => setTimeout(r, 50));+ }+ assert.ok(p && p !== 'norun');+ assert.equal(p.exitCode, 0);+ assert.equal(p.chunk.toString(), `ARGS:-p --output-format text --model sonnet\n${prompt}done\n`);+ assert.equal(existsSync(marker), before, 'payload must not execute');+ assert.equal(statSync(join(home, '.ruflo-ruos/runs', RUN, 'out.log')).mode & 0o077, 0, 'run files are private');++ // A long-running run is stopped via its process group.+ const run2 = 'r-test-stop01';+ const env2 = { ...env, FAKE_SLEEP: '30' };+ sh(buildPrepare(run2), env2);+ for (const c of buildPromptChunks(run2, 'x').commands) sh(c, env2);+ sh(buildLaunch({ runId: run2, prompt: 'x', runner: 'claude' }), env2);+ await new Promise((r) => setTimeout(r, 200));+ assert.match(sh(buildStop(run2), env2), /RUOS_STOPPED/);+});diff --git a/plugins/ruflo-ruos/tests/fakes.mjs b/plugins/ruflo-ruos/tests/fakes.mjsnew file mode 100644index 0000000000..1931955ea4--- /dev/null+++ b/plugins/ruflo-ruos/tests/fakes.mjs@@ -0,0 +1,91 @@+// @ts-check+/** London-school test doubles for ruflo-ruos (ADR-405). */++export const DESKTOP_ID = '43faac2ae346b16fafdd7c6b70061294';+export const FLY_ID = '85050dc77130e8';+export const OTHER_ID = '59fc0c7fcdd873c1eba47092dfee29e2';++/**+ * @param {Partial<import('../scripts/lib/types.mjs').Desktop>=} o+ * @returns {import('../scripts/lib/types.mjs').Desktop}+ */+export function desktop(o = {}) {+ return {+ id: DESKTOP_ID,+ flyMachineId: FLY_ID,+ name: 'ruos-work',+ displayName: 'Work Desktop',+ state: 'started',+ heartbeatStatus: 'ok',+ heartbeatAt: Math.floor(Date.UTC(2026, 9, 1, 15, 0, 0) / 1000),+ ready: true,+ ...o,+ };+}++/** A clock that only moves when sleep() is called or tick() is used. */+export function fakeClock(startMs = Date.UTC(2026, 9, 1, 15, 0, 0)) {+ let t = startMs;+ return {+ now: () => t,+ sleep: async (/** @type {number} */ ms) => { t += ms; },+ tick: (/** @type {number} */ ms) => { t += ms; },+ };+}++/**+ * @param {import('../scripts/lib/types.mjs').Desktop[]|(() => import('../scripts/lib/types.mjs').Desktop[])} desktops+ */+export function fakeFleet(desktops) {+ /** @type {Array<[string, unknown[]]>} */+ const calls = [];+ return {+ calls,+ listDesktops: async () => { calls.push(['listDesktops', []]); return typeof desktops === 'function' ? desktops() : desktops; },+ start: async (/** @type {string} */ id) => { calls.push(['start', [id]]); },+ stop: async (/** @type {string} */ id) => { calls.push(['stop', [id]]); },+ keepAwake: async (/** @type {string|null} */ f, /** @type {number} */ m) => { calls.push(['keepAwake', [f, m]]); },+ };+}++/**+ * A scripted transport: `respond(command)` returns the ExecResult or throws.+ * @param {(cmd: string, n: number) => import('../scripts/lib/types.mjs').ExecResult | Promise<import('../scripts/lib/types.mjs').ExecResult>} respond+ */+export function fakeTransport(respond) {+ /** @type {string[]} */+ const commands = [];+ return {+ kind: /** @type {'fleet-mcp'} */ ('fleet-mcp'),+ commands,+ exec: async (/** @type {any} */ _d, /** @type {string} */ cmd) => {+ commands.push(cmd);+ return respond(cmd, commands.length);+ },+ };+}++/** @param {string} stdout */+export const ok = (stdout) => ({ stdout, stderr: '', exitCode: 0 });++export function fakeLedger() {+ /** @type {Array<[string, unknown[]]>} */+ const calls = [];+ /** @type {any[]} */+ const events = [];+ /** @type {Buffer[]} */+ const output = [];+ return {+ calls, events, output,+ swarmLedger: /** @type {'cli'} */ ('cli'),+ warnings: /** @type {string[]} */ ([]),+ registerAgent: async (/** @type {unknown[]} */ ...a) => { calls.push(['registerAgent', a]); },+ updateAgent: async (/** @type {unknown[]} */ ...a) => { calls.push(['updateAgent', a]); },+ terminateAgent: async (/** @type {unknown[]} */ ...a) => { calls.push(['terminateAgent', a]); },+ claim: async (/** @type {unknown[]} */ ...a) => { calls.push(['claim', a]); return true; },+ release: async (/** @type {unknown[]} */ ...a) => { calls.push(['release', a]); },+ event: (/** @type {any} */ e) => { events.push(e); },+ snapshotHosts: (/** @type {unknown[]} */ ...a) => { calls.push(['snapshotHosts', a]); },+ appendOutput: (/** @type {string} */ _r, /** @type {Buffer} */ c) => { output.push(c); },+ };+}diff --git a/plugins/ruflo-ruos/tests/ledger-cli.test.mjs b/plugins/ruflo-ruos/tests/ledger-cli.test.mjsnew file mode 100644index 0000000000..ee06624eff--- /dev/null+++ b/plugins/ruflo-ruos/tests/ledger-cli.test.mjs@@ -0,0 +1,105 @@+// @ts-check+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, existsSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { createLedger } from '../scripts/lib/ledger.mjs';+import { desktop, DESKTOP_ID } from './fakes.mjs';++const here = dirname(fileURLToPath(import.meta.url));+const CLI = resolve(here, '../scripts/cli.mjs');+const REPO_DIST = resolve(here, '../../../v3/@claude-flow/cli/dist/src/mcp-client.js');+const tmp = () => mkdtempSync(join(tmpdir(), 'ruflo-ruos-ledger-'));+const host = { kind: /** @type {'ruos'} */ ('ruos'), desktopId: DESKTOP_ID, desktopName: 'Work Desktop', transport: /** @type {'fleet-mcp'} */ ('fleet-mcp'), runId: 'r-ledger-0001' };++test('ledger records through ruflo tools (mocked callTool) and owns only .claude-flow/ruos', async () => {+ const cwd = tmp();+ /** @type {Array<[string, any]>} */ const calls = [];+ const ledger = createLedger({ cwd, callTool: async (n, i) => { calls.push([n, i]); return { success: true }; } });+ assert.equal(await ledger.claim('r-ledger-0001', 'a1', 'coder'), true);+ await ledger.registerAgent('a1', 'coder', host, 'task text');+ ledger.event({ type: 'run.started', runId: 'r-ledger-0001' });+ ledger.appendOutput('r-ledger-0001', Buffer.from('out'));+ ledger.snapshotHosts([desktop()], { [DESKTOP_ID]: ['a1'] });+ await ledger.updateAgent('a1', 'idle', { exitCode: 0 });+ await ledger.release('r-ledger-0001', 'a1', 'coder');+ assert.deepEqual(calls.map((c) => c[0]), ['claims_claim', 'agent_spawn', 'agent_update', 'agent_update', 'claims_release']);+ assert.deepEqual(calls[0][1], { issueId: 'ruos-run-r-ledger-0001', claimant: 'agent:a1:coder' });+ assert.deepEqual(calls[1][1].config.host, host);+ assert.equal(ledger.swarmLedger, 'cli');+ const hosts = JSON.parse(readFileSync(join(cwd, '.claude-flow/ruos/hosts.json'), 'utf8'));+ assert.deepEqual(hosts.hosts[0].agents, ['a1']);+ assert.equal(statSync(join(cwd, '.claude-flow/ruos/runs/r-ledger-0001.log')).mode & 0o077, 0);+ assert.ok(!existsSync(join(cwd, '.claude-flow/agents')), 'never writes ruflo stores directly');+});++test('policy denial / missing tool degrades to unavailable without throwing', async () => {+ const ledger = createLedger({ cwd: tmp(), callTool: async () => { throw new Error('policy-denied:enforce; receipt=x'); } });+ await ledger.registerAgent('a1', 'coder', host, 't');+ assert.equal(ledger.swarmLedger, 'unavailable');+ assert.equal(await ledger.claim('r-ledger-0001', 'a1', 'coder'), true, 'no ledger means no claim conflict to report');+ assert.ok(ledger.warnings[0].includes('policy-denied'));+ const conflict = createLedger({ cwd: tmp(), callTool: async () => ({ success: false, error: 'Issue already claimed' }) });+ assert.equal(await conflict.claim('r-ledger-0001', 'a1', 'coder'), false);+ const none = createLedger({ cwd: tmp(), callTool: null });+ assert.equal(none.swarmLedger, 'unavailable');+});++test('real ruflo CLI: agent store carries config.host and claims round-trip', { skip: !existsSync(REPO_DIST) && 'v3 CLI not built' }, () => {+ const cwd = tmp();+ const status = join(cwd, 'status.json');+ writeFileSync(status, JSON.stringify({ desktops: [{ machine_id: DESKTOP_ID, fly_machine_id: '85050dc77130e8', name: 'w', display_name: 'Work Desktop', state: 'started', heartbeat_status: 'ok', last_heartbeat_at: 1 }] }));+ const env = { ...process.env, RUFLO_CLI_MCP_CLIENT: REPO_DIST, CLAUDE_FLOW_CWD: '' };+ const run = (/** @type {string[]} */ a) => JSON.parse(execFileSync('node', [CLI, ...a], { cwd, env, encoding: 'utf8' }));+ const start = run(['record', 'start', '--run', 'r-ledger-0002', '--agent-id', 'ruos-int-1', '--desktop', 'Work Desktop', '--desktop-status-file', status, '--task', 'demo']);+ assert.equal(start.swarmLedger, 'cli');+ const store = JSON.parse(readFileSync(join(cwd, '.claude-flow/agents/store.json'), 'utf8'));+ assert.equal(store.agents['ruos-int-1'].status, 'busy');+ assert.deepEqual(store.agents['ruos-int-1'].config.host, { kind: 'ruos', desktopId: DESKTOP_ID, desktopName: 'Work Desktop', transport: 'fleet-mcp', runId: 'r-ledger-0002' });+ const claims = JSON.parse(readFileSync(join(cwd, '.claude-flow/claims/claims.json'), 'utf8'));+ assert.equal(claims.claims['ruos-run-r-ledger-0002'].claimant.agentId, 'ruos-int-1');+ run(['record', 'output', '--run', 'r-ledger-0002', '--agent-id', 'ruos-int-1', '--b64', Buffer.from('hi').toString('base64')]);+ run(['record', 'end', '--run', 'r-ledger-0002', '--agent-id', 'ruos-int-1', '--exit', '0']);+ const after = JSON.parse(readFileSync(join(cwd, '.claude-flow/agents/store.json'), 'utf8'));+ assert.equal(after.agents['ruos-int-1'].status, 'idle');+ const events = readFileSync(join(cwd, '.claude-flow/ruos/events.jsonl'), 'utf8').trim().split('\n').map((l) => JSON.parse(l).type);+ assert.deepEqual(events, ['run.started', 'run.output', 'run.completed']);+ assert.equal(readFileSync(join(cwd, '.claude-flow/ruos/runs/r-ledger-0002.log'), 'utf8'), 'hi');+ // A foreign desktop is refused even on the session path.+ assert.throws(() => execFileSync('node', [CLI, 'record', 'start', '--run', 'r-ledger-0003', '--desktop', 'f'.repeat(32), '--desktop-status-file', status], { cwd, env, stdio: 'pipe' }));+});++test('CLI with no configuration: exits 2, makes no network call', () => {+ const cwd = tmp();+ const env = { PATH: process.env.PATH ?? '', HOME: cwd };+ for (const cmd of [['hosts'], ['run', '--desktop', 'x', '--prompt', 'y']]) {+ let code = 0;+ let stderr = '';+ try {+ execFileSync('node', [CLI, ...cmd], { cwd, env, stdio: 'pipe' });+ } catch (e) {+ const err = /** @type {any} */ (e);+ code = err.status;+ stderr = String(err.stderr);+ }+ assert.equal(code, 2, cmd.join(' '));+ assert.match(stderr, /not-configured/);+ }+ const status = JSON.parse(execFileSync('node', [CLI, 'status'], { cwd, env, encoding: 'utf8' }));+ assert.equal(status.fleetMcp, 'not-configured');+ assert.ok(!existsSync(join(cwd, '.claude-flow')), 'nothing written when unconfigured');+});++test('CLI build prints the audited session-path strings', () => {+ const cwd = tmp();+ const pf = join(cwd, 'p.txt');+ writeFileSync(pf, 'do $(rm -rf ~) the thing');+ const out = JSON.parse(execFileSync('node', [CLI, 'build', '--run', 'r-build-0001', '--prompt-file', pf, '--model', 'haiku'], { cwd, encoding: 'utf8' }));+ assert.equal(out.runId, 'r-build-0001');+ assert.ok(out.steps.length >= 3);+ assert.ok(!JSON.stringify(out).includes('rm -rf ~'));+ assert.match(out.poll, /RUOS_POLL/);+});diff --git a/plugins/ruflo-ruos/tests/transports.test.mjs b/plugins/ruflo-ruos/tests/transports.test.mjsnew file mode 100644index 0000000000..e49145d56b--- /dev/null+++ b/plugins/ruflo-ruos/tests/transports.test.mjs@@ -0,0 +1,149 @@+// @ts-check+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { EventEmitter } from 'node:events';+import {+ FleetMcpClient, createFleet, createFleetTransport, normalizeDesktops, classifyToolError, parseRpcBody,+} from '../scripts/lib/fleet-mcp.mjs';+import { buildSshArgv, createSshTransport, sshHostFor } from '../scripts/lib/ssh.mjs';+import { RuosError } from '../scripts/lib/types.mjs';+import { desktop } from './fakes.mjs';++const URL_ = 'https://fleet.example.test/mcp';+const TOKEN = 'test-token-not-real';++/**+ * Fake fetch: answers initialize/initialized, then `onTool(name, args)`.+ * @param {(name: string, args: any) => { status?: number, result?: any, sse?: boolean, throws?: Error }} onTool+ */+function fakeFetch(onTool) {+ /** @type {any[]} */+ const requests = [];+ /** @type {typeof fetch} */+ const f = async (url, init) => {+ const body = JSON.parse(String(init?.body));+ requests.push({ url, headers: init?.headers, body });+ const headers = new Headers({ 'mcp-session-id': 'sess-1', 'content-type': 'application/json' });+ if (body.method === 'initialize') return new Response(JSON.stringify({ jsonrpc: '2.0', id: body.id, result: { protocolVersion: '2025-06-18' } }), { status: 200, headers });+ if (body.method === 'notifications/initialized') return new Response(null, { status: 202, headers });+ const r = onTool(body.params.name, body.params.arguments);+ if (r.throws) throw r.throws;+ if (r.status && r.status !== 200) return new Response('no', { status: r.status });+ const msg = JSON.stringify({ jsonrpc: '2.0', id: body.id, result: r.result });+ if (r.sse) return new Response(`event: message\ndata: ${msg}\n\n`, { status: 200, headers: { 'content-type': 'text/event-stream' } });+ return new Response(msg, { status: 200, headers });+ };+ return { f, requests };+}++const text = (/** @type {unknown} */ o) => ({ content: [{ type: 'text', text: JSON.stringify(o) }] });++test('fleet MCP: unconfigured client refuses with no network call', async () => {+ let called = false;+ const c = new FleetMcpClient({ url: undefined, token: undefined, fetchImpl: async () => { called = true; return new Response(''); } });+ await assert.rejects(c.callTool('desktop_status', {}), (e) => e instanceof RuosError && e.code === 'not-configured');+ assert.equal(called, false);+});++test('fleet MCP: refuses http and the executor port', async () => {+ for (const url of ['http://fleet.example.test/mcp', 'https://desk.internal:17870/x']) {+ const c = new FleetMcpClient({ url, token: TOKEN, fetchImpl: async () => new Response('') });+ await assert.rejects(c.callTool('desktop_status', {}), (e) => e instanceof RuosError && e.code === 'invalid-input');+ }+});++test('fleet MCP: handshake, bearer, session id, SSE and structured payloads', async () => {+ const { f, requests } = fakeFetch((name) => name === 'desktop_status'+ ? { result: text({ desktops: [{ machine_id: 'a'.repeat(32), fly_machine_id: 'b'.repeat(14), name: 'n', display_name: 'D', state: 'started', heartbeat_status: 'ok', last_heartbeat_at: 5, ready: true }, { machine_id: 'bogus' }] }), sse: true }+ : { result: { structuredContent: { stdout: 'RUOS_RUNNER_OK\n', exit_code: 0 } } });+ const client = new FleetMcpClient({ url: URL_, token: TOKEN, fetchImpl: f });+ const ds = await createFleet(client).listDesktops();+ assert.equal(ds.length, 1, 'malformed ids are dropped');+ assert.equal(ds[0].flyMachineId, 'b'.repeat(14));+ const r = await createFleetTransport(client).exec(ds[0], 'echo', 999);+ assert.deepEqual(r, { stdout: 'RUOS_RUNNER_OK\n', stderr: '', exitCode: 0 });+ const call = requests.at(-1);+ assert.equal(call.headers.authorization, `Bearer ${TOKEN}`);+ assert.equal(call.headers['mcp-session-id'], 'sess-1');+ assert.deepEqual(call.body.params.arguments, { command: 'echo', machine: 'b'.repeat(14), timeout_secs: 300 });+});++test('fleet MCP failure typing: auth expired, network down, stopped, timeout', async () => {+ const mk = (/** @type {any} */ r) => new FleetMcpClient({ url: URL_, token: TOKEN, fetchImpl: fakeFetch(() => r).f });+ await assert.rejects(mk({ status: 401 }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'auth-expired');+ await assert.rejects(mk({ status: 403 }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'auth-expired');+ await assert.rejects(mk({ throws: new TypeError('fetch failed') }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'network-down');+ const timeoutErr = Object.assign(new Error('t'), { name: 'TimeoutError' });+ await assert.rejects(mk({ throws: timeoutErr }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'timeout');+ await assert.rejects(mk({ result: { isError: true, content: [{ type: 'text', text: 'machine is stopped' }] } }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'desktop-stopped');+ await assert.rejects(mk({ status: 500 }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'tool-error');+ // A failed handshake is retried on the next call instead of being cached.+ let n = 0;+ const flaky = new FleetMcpClient({ url: URL_, token: TOKEN, fetchImpl: async (u, i) => { if (n++ === 0) throw new TypeError('down'); return fakeFetch(() => ({ result: text({ desktops: [] }) })).f(u, i); } });+ await assert.rejects(flaky.callTool('desktop_status', {}));+ assert.deepEqual(await flaky.callTool('desktop_status', {}), { desktops: [] });+});++test('classifyToolError / parseRpcBody / normalizeDesktops edge cases', () => {+ assert.equal(classifyToolError('token expired').code, 'auth-expired');+ assert.equal(classifyToolError('machine not found').code, 'not-owned');+ assert.equal(classifyToolError('boom').code, 'tool-error');+ assert.throws(() => parseRpcBody('', 'text/event-stream'), RuosError);+ assert.deepEqual(normalizeDesktops(null), []);+});++test('ssh argv is fixed, no shell, executor port never used', () => {+ const argv = buildSshArgv({ keyPath: '/k', user: 'ruv', host: 'h', command: 'echo hi' });+ assert.deepEqual(argv.slice(0, 2), ['-p', '2222']);+ assert.equal(argv.at(-1), 'echo hi');+ assert.equal(argv.at(-3), '--');+ assert.ok(!argv.includes('17870'));+ assert.throws(() => buildSshArgv({ keyPath: '-oProxyCommand=x', user: 'ruv', host: 'h', command: 'c' }), RuosError);+ assert.throws(() => buildSshArgv({ keyPath: '/k', user: 'root;id', host: 'h', command: 'c' }), RuosError);+ assert.equal(sshHostFor(desktop(), 'ruos-desktop'), '85050dc77130e8.vm.ruos-desktop.internal');+ assert.throws(() => sshHostFor(desktop({ flyMachineId: null }), 'ruos-desktop'), RuosError);+ assert.throws(() => sshHostFor(desktop(), 'bad app;'), RuosError);+ assert.throws(() => createSshTransport({ keyPath: '' }), (e) => e instanceof RuosError && e.code === 'not-configured');+});++/**+ * @param {{ code?: number, stdout?: string, stderr?: string, hang?: boolean, error?: Error }} o+ */+function fakeSpawn(o) {+ /** @type {any[]} */+ const calls = [];+ const spawnImpl = /** @type {any} */ ((/** @type {string} */ cmd, /** @type {string[]} */ argv, /** @type {any} */ opts) => {+ calls.push({ cmd, argv, opts });+ const child = /** @type {any} */ (new EventEmitter());+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = () => { child.killed = true; };+ setImmediate(() => {+ if (o.error) return child.emit('error', o.error);+ if (o.hang) return;+ if (o.stdout) child.stdout.emit('data', Buffer.from(o.stdout));+ if (o.stderr) child.stderr.emit('data', Buffer.from(o.stderr));+ child.emit('close', o.code ?? 0);+ });+ return child;+ });+ return { spawnImpl, calls };+}++test('ssh transport: success, key refused, unreachable, timeout', async () => {+ const good = fakeSpawn({ stdout: 'RUOS_RUNNER_OK\n' });+ const t = createSshTransport({ keyPath: '/k', spawnImpl: good.spawnImpl });+ assert.equal((await t.exec(desktop(), 'echo', 5)).stdout, 'RUOS_RUNNER_OK\n');+ assert.equal(good.calls[0].cmd, 'ssh');+ assert.equal(good.calls[0].opts.shell, false);+ const denied = createSshTransport({ keyPath: '/k', spawnImpl: fakeSpawn({ code: 255, stderr: 'Permission denied (publickey).' }).spawnImpl });+ await assert.rejects(denied.exec(desktop(), 'x', 5), (e) => e instanceof RuosError && e.code === 'auth-expired');+ const down = createSshTransport({ keyPath: '/k', spawnImpl: fakeSpawn({ code: 255, stderr: 'Connection timed out' }).spawnImpl });+ await assert.rejects(down.exec(desktop(), 'x', 5), (e) => e instanceof RuosError && e.code === 'network-down');+ const noBin = createSshTransport({ keyPath: '/k', spawnImpl: fakeSpawn({ error: new Error('ENOENT') }).spawnImpl });+ await assert.rejects(noBin.exec(desktop(), 'x', 5), (e) => e instanceof RuosError && e.code === 'network-down');+ const hang = createSshTransport({ keyPath: '/k', spawnImpl: fakeSpawn({ hang: true }).spawnImpl });+ await assert.rejects(hang.exec(desktop(), 'x', 0.01), (e) => e instanceof RuosError && e.code === 'timeout');+ const remoteFail = createSshTransport({ keyPath: '/k', spawnImpl: fakeSpawn({ code: 3, stdout: 'RUOS_NORUN' }).spawnImpl });+ assert.equal((await remoteFail.exec(desktop(), 'x', 5)).exitCode, 3, 'remote exit codes pass through');+});diff --git a/plugins/ruflo-ruos/tests/validate-autostop.test.mjs b/plugins/ruflo-ruos/tests/validate-autostop.test.mjsnew file mode 100644index 0000000000..6fd155ee9b--- /dev/null+++ b/plugins/ruflo-ruos/tests/validate-autostop.test.mjs@@ -0,0 +1,61 @@+// @ts-check+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { resolveDesktop, assertBudget, assertModel, newRunId, RUN_ID_RE } from '../scripts/lib/validate.mjs';+import { nextAutoStop, checkWindow } from '../scripts/lib/autostop.mjs';+import { RuosError } from '../scripts/lib/types.mjs';+import { desktop, DESKTOP_ID, FLY_ID, OTHER_ID } from './fakes.mjs';++const owned = [desktop(), desktop({ id: OTHER_ID, flyMachineId: '815601f9e17de8', name: 'ruos-4', displayName: 'Desktop 4' })];++test('desktop ids resolve only against the caller\'s own list', () => {+ assert.equal(resolveDesktop(owned, DESKTOP_ID).id, DESKTOP_ID);+ assert.equal(resolveDesktop(owned, FLY_ID).id, DESKTOP_ID);+ assert.equal(resolveDesktop(owned, 'Work Desktop').id, DESKTOP_ID);+ assert.equal(resolveDesktop(owned, 'ruos-4').id, OTHER_ID);+ for (const foreign of ['ffffffffffffffffffffffffffffffff', 'aaaaaaaaaaaaaa', 'other tenant', '../../x', '$(id)']) {+ assert.throws(() => resolveDesktop(owned, foreign), (e) => e instanceof RuosError && e.code === 'not-owned');+ }+ for (const bad of ['', 123, null, 'x'.repeat(200)]) {+ assert.throws(() => resolveDesktop(owned, bad), (e) => e instanceof RuosError && e.code === 'invalid-input');+ }+ const dup = [...owned, desktop({ id: 'b'.repeat(32), flyMachineId: null, displayName: 'Work Desktop' })];+ assert.throws(() => resolveDesktop(dup, 'Work Desktop'), (e) => e instanceof RuosError && e.code === 'ambiguous');+});++test('budget and model validation', () => {+ assert.equal(assertBudget('0.5'), 0.5);+ assert.equal(assertBudget(2.555), 2.56);+ for (const b of ['1e3', '-1', '0', 'NaN', 'Infinity', '1;id', 1001]) assert.throws(() => assertBudget(b), RuosError);+ assert.equal(assertModel(undefined), undefined);+ assert.equal(assertModel('opus'), 'opus');+ assert.throws(() => assertModel('gpt-5'), RuosError);+});++test('run ids are path-safe', () => {+ const id = newRunId(() => 1_790_000_000_000, (n) => Buffer.alloc(n, 0xab));+ assert.match(id, RUN_ID_RE);+});++const iso = (/** @type {number} */ ms) => new Date(ms).toISOString();++test('auto-stop: weekday 23:00 America/Toronto, DST aware', () => {+ // Thu 2026-10-01 16:00 EDT → Thu 23:00 EDT = 03:00Z Fri+ assert.equal(iso(nextAutoStop(Date.parse('2026-10-01T20:00:00Z'))), '2026-10-02T03:00:00.000Z');+ // Friday evening before stop → Friday 23:00+ assert.equal(iso(nextAutoStop(Date.parse('2026-10-03T02:59:00Z'))), '2026-10-03T03:00:00.000Z');+ // Friday after stop → skips the weekend → Monday 23:00 EDT+ assert.equal(iso(nextAutoStop(Date.parse('2026-10-03T03:30:00Z'))), '2026-10-06T03:00:00.000Z');+ // Sunday 2026-11-01 (DST ends that day) → Monday 23:00 EST = 04:00Z+ assert.equal(iso(nextAutoStop(Date.parse('2026-11-01T12:00:00Z'))), '2026-11-03T04:00:00.000Z');+ // Sunday 2026-03-08 (DST starts) → Monday 23:00 EDT = 03:00Z+ assert.equal(iso(nextAutoStop(Date.parse('2026-03-08T12:00:00Z'))), '2026-03-10T03:00:00.000Z');+});++test('auto-stop window check', () => {+ const now = Date.parse('2026-10-02T02:30:00Z'); // Thu 22:30 EDT+ assert.equal(checkWindow(now, 600).ok, true);+ const w = checkWindow(now, 3600);+ assert.equal(w.ok, false);+ assert.equal(w.minutesUntilStop, 30);+});