π 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): commands, skill, agent, smoke contract, deploy-info, ADR-405
ruv92ff48b7b53a
diff --git a/plugins/ruflo-ruos/.claude-plugin/plugin.json b/plugins/ruflo-ruos/.claude-plugin/plugin.jsonnew file mode 100644index 0000000000..9720a4cce1--- /dev/null+++ b/plugins/ruflo-ruos/.claude-plugin/plugin.json@@ -0,0 +1,21 @@+{+ "name": "ruflo-ruos",+ "description": "Run ruflo swarm agents on your own ruOS cloud desktops via the tenant-authenticated fleet MCP or per-tenant SSH; optional and removable (ADR-405)",+ "version": "0.1.0",+ "author": {+ "name": "ruvnet",+ "url": "https://github.com/ruvnet"+ },+ "homepage": "https://github.com/ruvnet/ruflo",+ "license": "MIT",+ "keywords": [+ "ruflo",+ "ruos",+ "swarm",+ "remote-host",+ "cloud-desktop",+ "fleet-mcp",+ "ssh",+ "claims"+ ]+}diff --git a/plugins/ruflo-ruos/agents/ruos-host-operator.md b/plugins/ruflo-ruos/agents/ruos-host-operator.mdnew file mode 100644index 0000000000..0a14dc46b2--- /dev/null+++ b/plugins/ruflo-ruos/agents/ruos-host-operator.md@@ -0,0 +1,25 @@+---+name: ruos-host-operator+description: Places ruflo swarm agents on the user's own ruOS desktops, streams their output into swarm state, and hands finished work back for review β fleet MCP or per-tenant SSH only+model: sonnet+---+You operate ruOS desktops as remote execution hosts for a ruflo swarm (ADR-405).++Hard rules:+- Transports: the tenant-authenticated ruOS fleet MCP (`desktop_status`, `desktop_exec`,+ `desktop_start`, `desktop_stop`, `desktop_keepawake`) or per-tenant SSH on :2222. Never+ the desktop executor on :17870, never a forged `Host` header.+- Desktops come only from the caller's own `desktop_status`. Refuse anything else.+- Remote commands come only from `scripts/cli.mjs build` (the audited builder). Task+ text never enters a command line.+- Starting a desktop costs money: ask first. Stopping a run or a desktop needs the+ user's explicit confirmation.+- Respect the weekday 23:00 America/Toronto auto-stop; refuse runs that would cross it+ unless the user accepts.+- Record every remote agent through ruflo's existing ledger (`cli.mjs record` or+ `cli.mjs run`), which uses `agent_spawn`/`agent_update` and `claims_claim`/`claims_release`.+ Do not invent another claims or state store.+- Deploy is the user's decision: report repo state with `cli.mjs deploy-info`, never push.++Workflow: follow the `ruos-host-run` skill. Report per run: desktop, runId, agentId,+status, exit code, bytes, and any ledger warnings.diff --git a/plugins/ruflo-ruos/commands/deploy.md b/plugins/ruflo-ruos/commands/deploy.mdnew file mode 100644index 0000000000..633eb9adeb--- /dev/null+++ b/plugins/ruflo-ruos/commands/deploy.md@@ -0,0 +1,15 @@+---+name: deploy+description: Read-only deploy hand-off after a swarm finishes on a ruOS desktop β report what would ship, never push+---+$ARGUMENTS++After a remote swarm run, report the state of a repo on the desktop so the user can+decide on a deploy:++`node "${CLAUDE_PLUGIN_ROOT}/scripts/cli.mjs" deploy-info --desktop "<ref>" --repo <path-relative-to-$HOME>`++It returns branch, HEAD, dirty file count and commits ahead of upstream. It does **not**+push, merge or deploy: ruOS's exec filter refuses `git push` / `fly deploy` literals by+design, and deploying is the user's decision through their own ruOS or project tooling.+Present the summary and stop.diff --git a/plugins/ruflo-ruos/commands/hosts.md b/plugins/ruflo-ruos/commands/hosts.mdnew file mode 100644index 0000000000..e331fe6e37--- /dev/null+++ b/plugins/ruflo-ruos/commands/hosts.md@@ -0,0 +1,24 @@+---+name: hosts+description: List your ruOS desktops as ruflo swarm hosts β state, liveness, and which ruflo agents run on each+---+$ARGUMENTS++Show the caller's own ruOS desktops as candidate swarm hosts.++1. If the ruOS fleet MCP tools are connected in this session (`mcp__ruos__desktop_status`,+ or the claude.ai ruOS connector equivalent), call `desktop_status` and present each+ desktop's `display_name`, `machine_id`, `state` and `heartbeat_status`. `ready` is a+ provisioning flag, not liveness β only a recent `last_heartbeat_at` means "up".+2. Otherwise run the CLI path (needs `RUOS_MCP_URL` + `RUOS_MCP_TOKEN` in the environment;+ with them unset it exits 2 and makes no request):++ `node "${CLAUDE_PLUGIN_ROOT}/scripts/cli.mjs" hosts`++3. Show which ruflo agents are placed on each desktop from+ `.claude-flow/ruos/hosts.json` and agents whose `config.host.kind` is `ruos`+ (`npx ruflo agent list`).++Mention the next weekday 23:00 America/Toronto auto-stop+(`node "${CLAUDE_PLUGIN_ROOT}/scripts/cli.mjs" status` prints it). Never start a desktop+from this command.diff --git a/plugins/ruflo-ruos/commands/run.md b/plugins/ruflo-ruos/commands/run.mdnew file mode 100644index 0000000000..3682bf561c--- /dev/null+++ b/plugins/ruflo-ruos/commands/run.md@@ -0,0 +1,23 @@+---+name: run+description: Run a ruflo agent (claude -p) on one of your ruOS desktops and stream its output into the swarm+---+$ARGUMENTS++Place one swarm agent on a ruOS desktop. Follow the `ruos-host-run` skill. Summary:++- **Target**: a desktop from the caller's own `desktop_status` list (id, Fly id or exact+ name). Anything else is refused.+- **Stopped desktop**: do not start it unless the user asked (`--start`); starting is billable.+- **Auto-stop**: refuse a run whose timeout crosses the next weekday 23:00+ America/Toronto stop unless the user passes `--ignore-autostop`.+- **CLI path** (env-configured fleet MCP or SSH):++ `node "${CLAUDE_PLUGIN_ROOT}/scripts/cli.mjs" run --desktop "<ref>" --prompt-file <file> [--model sonnet] [--timeout 900] [--start]`++- **Session path** (fleet MCP connected in Claude Code): `cli.mjs build` prints the exact+ `desktop_exec` command strings; send them in order, poll, and report lifecycle with+ `cli.mjs record start|output|end` so the swarm ledger stays one source.++Never put task text into a `desktop_exec` command yourself β only the strings `build` prints.+Never contact a desktop on port 17870.diff --git a/plugins/ruflo-ruos/commands/view.md b/plugins/ruflo-ruos/commands/view.mdnew file mode 100644index 0000000000..5cf6fe89fd--- /dev/null+++ b/plugins/ruflo-ruos/commands/view.md@@ -0,0 +1,18 @@+---+name: view+description: Watch the ruOS desktop a ruflo agent is running on β delegates to ruOS's own viewer+---+$ARGUMENTS++Open a view of a ruOS desktop that hosts a ruflo agent. ruflo-ruos does not implement a+viewer; it delegates:++1. If the ruOS Claude Code mod is installed (`/ruos` commands available), run+ `/ruos view <desktop>` β that owns the `ruos-view` pane.+2. Else, if the fleet MCP is connected, call `desktop_share` for a revocable, expiring,+ view-only link (or `computer_screenshot` for a single frame).+3. Else tell the user to open https://ruos.cognitum.one/dashboard/#desktops.++Resolve `<desktop>` from the agent's `config.host.desktopId` (`npx ruflo agent status <id>`)+or `.claude-flow/ruos/hosts.json`. Never open an interactive control session+(`desktop_control`) unless the user asks for hands-on control.diff --git a/plugins/ruflo-ruos/scripts/cli.mjs b/plugins/ruflo-ruos/scripts/cli.mjsold mode 100644new mode 100755index c27af747ec..0290a36332--- a/plugins/ruflo-ruos/scripts/cli.mjs+++ b/plugins/ruflo-ruos/scripts/cli.mjs@@ -13,6 +13,8 @@* 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)+ * deploy-info --desktop <ref> --repo <path-under-$HOME>+ * read-only: what a deploy from that repo would ship* status transport configuration (no network)** With no RUOS_MCP_URL/RUOS_MCP_TOKEN (and no RUOS_SSH_KEY for ssh) every@@ -27,7 +29,7 @@ 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 { buildPrepare, buildPromptChunks, buildLaunch, buildPoll, buildStop, buildProbe, buildRepoSummary, parseRepoSummary } from './lib/command-builder.mjs';import { nextAutoStop } from './lib/autostop.mjs';/**@@ -140,6 +142,15 @@ export async function main(argv, env = process.env) {print(await adapter.stopDesktop({ desktop: String(args.desktop ?? ''), confirm: args.confirm === true }));return 0;}+ case 'deploy-info': {+ // Read-only hand-off: report repo state; never push or deploy.+ const { adapter } = await buildAdapter(args, env);+ const cmdline = buildRepoSummary(String(args.repo ?? ''));+ const d = await adapter.resolve(String(args.desktop ?? ''));+ print({ desktopId: d.id, repo: args.repo, ...parseRepoSummary((await adapter.transport.exec(d, cmdline, 30)).stdout),+ next: 'review the diff, then deploy with your ruOS/project tooling; ruflo-ruos does not push or deploy' });+ return 0;+ }case 'logs': {const runId = assertRunId(args.run);const f = join(projectCwd(env), '.claude-flow', 'ruos', 'runs', `${runId}.log`);@@ -165,7 +176,7 @@ export async function main(argv, env = process.env) {case 'record':return record(args, env);default:- print('usage: cli.mjs <status|hosts|run|stop|desktop-stop|logs|build|record> [options] (see header)');+ print('usage: cli.mjs <status|hosts|run|stop|desktop-stop|logs|build|record|deploy-info> [options] (see header)');return cmd ? 2 : 0;}}diff --git a/plugins/ruflo-ruos/scripts/lib/command-builder.mjs b/plugins/ruflo-ruos/scripts/lib/command-builder.mjsindex 83753cad3a..605967f8e8 100644--- a/plugins/ruflo-ruos/scripts/lib/command-builder.mjs+++ b/plugins/ruflo-ruos/scripts/lib/command-builder.mjs@@ -89,7 +89,7 @@ export function buildLaunch(spec) {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`;+ const inner = `claude -p ${flags.join(' ')} < prompt.txt > out.log 2>&1; echo $? > exit.code.tmp && mv exit.code.tmp 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@@ -136,6 +136,40 @@ export function buildStop(runId) {);}+/** a repo path on the desktop, relative to $HOME; no traversal, no quoting tricks */+export const REPO_PATH_RE = /^(?!.*(^|\/)\.\.(\/|$))[A-Za-z0-9._][A-Za-z0-9._/-]{0,199}$/;++/**+ * Read-only deploy hand-off probe (ADR-405 Β§Deploy hand-off): what would be+ * shipped from a repo on the desktop. It never pushes or deploys β ruOS's+ * exec filter refuses `git push` / `fly deploy` literals by design, and the+ * deploy decision stays with the user.+ * @param {string} repoPath path relative to $HOME+ */+export function buildRepoSummary(repoPath) {+ if (typeof repoPath !== 'string' || !REPO_PATH_RE.test(repoPath)) {+ throw new RuosError('invalid-input', 'repo path must be relative to $HOME without ..');+ }+ const d = `"$HOME/${repoPath}"`;+ return seal(+ `cd ${d} 2>/dev/null || { echo RUOS_NOREPO; exit 3; }` ++ ` ; printf 'RUOS_BRANCH:%s\\n' "$(git rev-parse --abbrev-ref HEAD 2>/dev/null)"` ++ ` ; printf 'RUOS_HEAD:%s\\n' "$(git rev-parse HEAD 2>/dev/null)"` ++ ` ; printf 'RUOS_DIRTY:%s\\n' "$(git status --porcelain 2>/dev/null | wc -l)"` ++ ` ; printf 'RUOS_AHEAD:%s\\n' "$(git rev-list --count @{u}..HEAD 2>/dev/null || echo unknown)"`,+ );+}++/**+ * @param {string} stdout+ * @returns {{ found: boolean, branch?: string, head?: string, dirty?: number, ahead?: string }}+ */+export function parseRepoSummary(stdout) {+ if (stdout.includes('RUOS_NOREPO')) return { found: false };+ const get = (/** @type {string} */ k) => new RegExp(`RUOS_${k}:(.*)`).exec(stdout)?.[1]?.trim() ?? '';+ return { found: true, branch: get('BRANCH'), head: get('HEAD'), dirty: Number(get('DIRTY')) || 0, ahead: get('AHEAD') };+}+/** 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`);diff --git a/plugins/ruflo-ruos/scripts/smoke.sh b/plugins/ruflo-ruos/scripts/smoke.shnew file mode 100755index 0000000000..f28dd6e1b7--- /dev/null+++ b/plugins/ruflo-ruos/scripts/smoke.sh@@ -0,0 +1,54 @@+#!/usr/bin/env bash+# ruflo-ruos smoke contract (ADR-405). Runs offline: no fleet credentials,+# no network. Exits non-zero on any failed check.+set -u+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+PASS=0+FAIL=0+step() { printf "β %s ... " "$1"; }+ok() { printf "PASS\n"; PASS=$((PASS+1)); }+bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }++step "1. plugin.json is valid and declares 0.1.0"+v=$(node -e 'const p=require(process.argv[1]);if(p.name!=="ruflo-ruos")process.exit(1);console.log(p.version)' "$ROOT/.claude-plugin/plugin.json" 2>/dev/null)+[[ "$v" == "0.1.0" ]] && ok || bad "got '$v'"++step "2. commands, skill and agent present with frontmatter"+miss=""+for c in hosts run view deploy; do+ f="$ROOT/commands/$c.md"; [[ -f "$f" ]] || { miss="$miss cmd-$c"; continue; }+ grep -q "^name: $c$" "$f" || miss="$miss $c-name"+ grep -q '^description:' "$f" || miss="$miss $c-desc"+done+grep -q '^name: ruos-host-run$' "$ROOT/skills/ruos-host-run/SKILL.md" 2>/dev/null || miss="$miss skill"+grep -q '^name: ruos-host-operator$' "$ROOT/agents/ruos-host-operator.md" 2>/dev/null || miss="$miss agent"+[[ -z "$miss" ]] && ok || bad "$miss"++step "3. every source file under 500 lines"+long=$(find "$ROOT/scripts" "$ROOT/tests" -name '*.mjs' -exec awk 'END{if(NR>500)print FILENAME":"NR}' {} \;)+[[ -z "$long" ]] && ok || bad "$long"++step "4. no source path opens the :17870 executor"+# The only allowed mentions are refusals/assertions, never a URL or connect.+hits=$(grep -rnE "17870" "$ROOT/scripts" --include="*.mjs" | grep -vE "refus|never|ADR-070|includes\('17870'\)|port === '17870'" || true)+[[ -z "$hits" ]] && ok || bad "$hits"++step "5. ssh is spawned with a fixed argv and shell:false"+grep -q "shell: false" "$ROOT/scripts/lib/ssh.mjs" && ! grep -qE "exec\(|execSync\(|shell: true" "$ROOT/scripts/lib/ssh.mjs" \+ && ok || bad "ssh transport must not use a shell"++step "6. unconfigured CLI makes no request and exits 2"+tmp=$(mktemp -d)+out=$(cd "$tmp" && env -i PATH="$PATH" HOME="$tmp" node "$ROOT/scripts/cli.mjs" hosts 2>&1); code=$?+[[ $code -eq 2 && "$out" == *not-configured* && ! -e "$tmp/.claude-flow" ]] && ok || bad "code=$code out=$out"+rm -rf "$tmp"++step "7. unit + injection + failure-path tests"+if out=$(cd "$ROOT" && node --test tests/*.test.mjs 2>&1); then ok; else bad "$(printf '%s' "$out" | grep -E '^not ok' | head -5)"; fi++step "8. ADR-405 present"+[[ -f "$ROOT/../../v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md" ]] && ok || bad "missing ADR"++echo+echo "ruflo-ruos smoke: $PASS passed, $FAIL failed"+[[ $FAIL -eq 0 ]]diff --git a/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md b/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.mdnew file mode 100644index 0000000000..2ef7a66515--- /dev/null+++ b/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md@@ -0,0 +1,50 @@+---+name: ruos-host-run+description: Run a ruflo swarm agent on the user's own ruOS cloud desktop through the tenant-authenticated fleet MCP, stream its output, and record it in ruflo's swarm state. Use when the user wants an agent to run on a ruOS desktop, asks to "run this on my ruOS desktop", or places a swarm agent on a remote ruOS host.+argument-hint: "<desktop> <task>"+allowed-tools: Bash(node *) mcp__ruos__desktop_status mcp__ruos__desktop_exec mcp__ruos__desktop_keepawake mcp__ruos__desktop_start+---+# Run a ruflo agent on a ruOS desktop (session path, ADR-405)++Transport rules β non-negotiable:+- Use ONLY the fleet MCP tools (`mcp__ruos__*`, or the claude.ai ruOS connector's+ equivalents) or the plugin CLI. Never call a desktop on port 17870 and never set a+ `Host` header yourself (ruOS ADR-070: that executor has no per-tenant auth).+- Send ONLY the command strings printed by `cli.mjs build`. Never compose a+ `desktop_exec` command from task text.++`CLI` below is `node "${CLAUDE_PLUGIN_ROOT}/scripts/cli.mjs"`.++1. **Pick the host.** Call `desktop_status`. Resolve the user's desktop by `machine_id`,+ `fly_machine_id` or exact `display_name`; if it is not in that list, stop. Save the raw+ JSON to a temp file (`status.json`) for step 4.+2. **Liveness.** A desktop is up only if `heartbeat_status` is not `asleep`/`missing`/`stale`+ and `last_heartbeat_at` is recent. If it is down, ask before `desktop_start` (billable),+ then re-poll `desktop_status` until the heartbeat advances.+3. **Auto-stop.** `CLI status` prints `nextAutoStop` (weekday 23:00 America/Toronto). If the+ run could cross it, tell the user and stop unless they accept. `desktop_keepawake` blocks+ idle autosleep only; it does not override the 23:00 stop.+4. **Build + record.** Write the task to a file, then:+ - `CLI build --prompt-file task.txt [--model sonnet]` β JSON with `runId`, `steps[]`,+ `poll`, `stop`, `promptSha256`.+ - `CLI record start --run <runId> --desktop "<ref>" --desktop-status-file status.json --task "<one-line summary>"`+ β registers the agent through ruflo's `agent_spawn` (with `config.host`) and claims+ `ruos-run-<runId>` via `claims_claim`.+5. **Launch.** Call `desktop_exec` with each `steps[i]` in order (`machine` = the desktop's+ `fly_machine_id`). The last step prints `RUOS_SHA:<hash>` β it must equal+ `promptSha256`, else `desktop_exec` the `stop` string and abort. `RUOS_NO_RUNNER` means+ `claude` is not installed there.+6. **Stream.** Call `desktop_exec` with `poll` (rebuild with `CLI build --run <runId> --offset <n> ...`+ as the offset grows, or use `CLI run` for automatic polling). Output is+ `RUOS_POLL:<exit|->:<size>:<base64>`; pass the base64 to+ `CLI record output --run <runId> --b64 <b64>` and show the decoded text. Back off 1sβ5s+ between empty polls β each poll is audited on ruOS and serialises behind the desktop's+ run lock.+7. **Finish.** When exit is not `-` and all bytes are read:+ `CLI record end --run <runId> --exit <code>` (agent β idle, claim released).+ On failure, check `desktop_status`: a stopped desktop means it was auto-stopped mid-run.+8. **Stop early** only on the user's request: `desktop_exec` the `stop` string.++For unattended runs from a terminal, `CLI run --desktop "<ref>" --prompt-file task.txt`+does steps 1β7 itself (needs `RUOS_MCP_URL` + `RUOS_MCP_TOKEN`, or `--transport ssh` with+`RUOS_SSH_KEY` when ruflo runs on a same-tenant ruOS desktop).diff --git a/plugins/ruflo-ruos/tests/command-builder.test.mjs b/plugins/ruflo-ruos/tests/command-builder.test.mjsindex ec3878f913..acc98c73e4 100644--- a/plugins/ruflo-ruos/tests/command-builder.test.mjs+++ b/plugins/ruflo-ruos/tests/command-builder.test.mjs@@ -7,7 +7,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import {buildPrepare, buildPromptChunks, buildLaunch, buildPoll, buildStop, buildProbe,- parsePoll, parseLaunch, MAX_COMMAND_BYTES,+ parsePoll, parseLaunch, MAX_COMMAND_BYTES, buildRepoSummary, parseRepoSummary,} from '../scripts/lib/command-builder.mjs';import { RuosError } from '../scripts/lib/types.mjs';@@ -149,3 +149,12 @@ test('real /bin/sh: hostile prompt round-trips inert; run completes and stops',await new Promise((r) => setTimeout(r, 200));assert.match(sh(buildStop(run2), env2), /RUOS_STOPPED/);});++test('deploy hand-off probe is read-only and path-validated', () => {+ const c = buildRepoSummary('projects/app');+ assertOnlyExpectedRegions(c);+ for (const verb of ['push', 'deploy', 'commit', 'reset', 'checkout']) assert.ok(!new RegExp(`git ${verb}`).test(c), verb);+ for (const bad of ['../etc', 'a/../../b', '/abs', '$(id)', 'a b', "a'b", '-rf', '']) assert.throws(() => buildRepoSummary(bad), RuosError, bad);+ assert.deepEqual(parseRepoSummary('RUOS_NOREPO'), { found: false });+ assert.deepEqual(parseRepoSummary('RUOS_BRANCH:main\nRUOS_HEAD:abc\nRUOS_DIRTY:2\nRUOS_AHEAD:1\n'), { found: true, branch: 'main', head: 'abc', dirty: 2, ahead: '1' });+});diff --git a/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md b/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.mdnew file mode 100644index 0000000000..d113ee7250--- /dev/null+++ b/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md@@ -0,0 +1,143 @@+# ADR 405: ruOS Desktops as Swarm Execution Hosts++Status: Proposed++Date: 2026 10 01++Related: ADR 150 (removable integrations), ADR 324 (policy chokepoint), ADR 325 (claims plane), ruOS ADR-043 (exec literal filter), ruOS ADR-053 (per-tenant SSH :2222), ruOS ADR-070 (the desktop executor has no peer authentication), ruOS ADR-071 (remote MCP endpoint)++## Context++ruOS gives each user their own cloud Linux desktops (Fly machines), plus enrolled Macs and PCs. A ruflo swarm can only place agents on the local machine today. Users with ruOS desktops want swarm agents to run there: the desktop has its own disk, toolchain, `claude` CLI and LLM route, and the user can watch it.++There are three ways into a ruOS desktop. They have different trust properties:++| Path | Authentication | Usable from |+|---|---|---|+| ruOS fleet MCP (`desktop_status`, `desktop_exec`, `desktop_start`, `desktop_stop`, `desktop_keepawake`) | The caller's tenant credential. The fleet enforces machine ownership on every call. | Anywhere |+| sshd on `:2222` (ruOS ADR-053 Phase 2) | Pubkey-only, with a per-tenant ed25519 key minted by the fleet. `authorized_keys` is replaced with that tenant's key each time the desktop is armed. | Only inside the Fly 6PN, so only from another of the same tenant's desktops |+| Desktop executor on `:17870` | None per tenant. It is guarded only by a spoofable `Host` header, binds all interfaces, and every tenant shares one flat Fly 6PN app (ruOS ADR-070). | Any machine on the 6PN |++## Decision++### Host model++A ruOS desktop is a remote execution host for one or more ruflo swarm agents. The `ruflo-ruos` plugin places an agent on a host, launches `claude -p` there detached, streams its output back, and records the agent in ruflo's swarm state. The swarm topology, routing and coordination stay local. The desktop only runs the agent process.++### Transports++Two transports are allowed, both implemented in `plugins/ruflo-ruos/scripts/lib/`:++1. **The fleet MCP** (`fleet-mcp.mjs`). This is the default and the only control plane, used for discovery, start, stop and keepawake. In a Claude Code session the user's connected `mcp__ruos__*` tools are used directly. A terminal run reads `RUOS_MCP_URL` and `RUOS_MCP_TOKEN` from the environment. Neither value is embedded or defaulted. With either unset the CLI exits 2 with `not-configured` and makes no request. The client refuses plain `http` (except localhost) and any URL on port 17870.+2. **Per-tenant SSH on `:2222`** (`ssh.mjs`). It is opt-in (`--transport ssh`, `RUOS_SSH_KEY`) and works only when ruflo itself runs on one of the same tenant's ruOS desktops. `ssh` is spawned with a fixed argv and `shell: false`, with `BatchMode`, `IdentitiesOnly` and `StrictHostKeyChecking=accept-new`. The host is derived from the validated Fly machine id: `<fly-id>.vm.<app>.internal`. ADR-053 records that arming is probabilistic, so `Permission denied (publickey)` maps to `auth-expired` ("desktop not armed with this key").++The `:17870` executor is excluded. Any path that called it from a ruflo swarm would extend ADR-070's cross-tenant shell exposure into ruflo. The plugin sends no `Host` header and opens no connection to that port, and its smoke contract greps for any use of it. If ruOS ADR-070 lands per-request fleet authentication on the executor, a follow-up ADR can reconsider; until then the fleet MCP is the boundary.++### Command construction++Every shell string sent to a desktop comes from one audited module, `command-builder.mjs`. The same strings go over both transports.++- Each command is one line of at most 4000 bytes, the `desktop_exec` limit.+- The only variable regions are:+ - a run id matching `^[a-z0-9][a-z0-9-]{5,62}$`;+ - integers;+ - a model name from a fixed enum;+ - a canonicalised budget number;+ - base64 text inside single quotes.+- Prompt text travels only as base64. It is appended to a file in chunks, decoded on the desktop, and fed to `claude -p` on stdin, so no shell ever parses it.+- The decoded prompt's sha256 is checked against the local hash before the run is trusted.+- Output returns as `RUOS_POLL:<exit>:<size>:<base64 slice>`, so arbitrary bytes survive the JSON tool result.+- Run files live in `~/.ruflo-ruos/runs/<runId>/` with `umask 077`. The exit code is written atomically (`tmp` + `mv`), so a poll never reads a half-written file.+- The runner starts as `nohup setsid sh -c '<constant>'`. Stop signals its process group, after re-validating the pid file as digits on the desktop.++The ADR-043 literal filter passes these commands: `nohup`, `setsid` and `sh -c` are not on its denylist. That filter is a mistake guard, not a sandbox. The fleet's ownership check is the boundary.++### Swarm state and claims++The plugin does not add a claims system or an agent store. ADR-325 already describes four disconnected claim mechanisms. This plugin uses ruflo's local work-ownership board, the `claims_*` MCP tools (`.claude-flow/claims/claims.json`), which is ADR-325's "work ownership" responsibility in single-node form.++| What | ruflo tool (called in-process via `callMCPTool`, so ADR-324 policy applies) |+|---|---|+| Register a remote agent | `agent_spawn` with `domain: "ruos"`, `config.host = {kind:"ruos", desktopId, desktopName, transport, runId}` |+| Running / done | `agent_update` (`busy` β `idle`, `config.lastRemoteResult`) |+| Ownership of the run | `claims_claim` / `claims_release`, issue `ruos-run-<runId>`, claimant `agent:<agentId>:<agentType>` |++The plugin itself owns only `.claude-flow/ruos/`:++- `events.jsonl` holds lifecycle events carrying ids, sizes and states, never prompt or output text.+- `hosts.json` is a snapshot of hosts and their agents.+- `runs/<runId>.log` is a local copy of the output, mode 0600.++The swarm pane (`ruflo-swarm`) reads agents with `config.host.kind === "ruos"` plus these two files. If the CLI cannot be resolved, or policy denies a call, the ledger degrades to the plugin files and reports `swarmLedger: "unavailable"`. A remote run is never aborted because bookkeeping failed.++### Cost and auto-stop++- Starting a desktop is billable. The adapter starts one only with an explicit `--start`, and then waits for a fresh `last_heartbeat_at`, not `ready`.+- The fleet stops cloud desktops at 23:00 America/Toronto every weekday. `desktop_keepawake` blocks idle autosleep but does not override that stop. The adapter computes the next stop with `Intl`, so DST is handled. A run whose timeout crosses it is refused unless the user passes `--ignore-autostop`.+- At launch the adapter calls `desktop_keepawake` for the run's timeout plus 5 minutes.+- Polls back off from 1 s to 5 s. Each poll is an audited `desktop_exec` that waits behind the desktop's run lock.++### Deploy hand-off++After a run, `deploy-info` reports a repo's branch, HEAD, dirty count and commits ahead of upstream on the desktop. It never pushes or deploys. ruOS's exec filter refuses `git push` and `fly deploy` literals by design, and the deploy decision stays with the user.++### Removability (ADR-150 style)++- ruflo works identically when the plugin is absent. The PR changes no file under `v3/`, apart from this ADR.+- The plugin has no npm dependencies.+- The ruflo CLI is resolved at runtime and is optional.+- The `$.ruos` and `$.ruflo` Claude Code mod nouns are feature-detected and never required.++## Failure modes++Each failure surfaces as a typed `RuosError` code:++| Failure | Detection | Code |+|---|---|---|+| Fleet credential expired or revoked | HTTP 401/403, or a tool error mentioning auth | `auth-expired` |+| Fleet unreachable | `fetch` network error | `network-down` |+| Request hangs | `AbortSignal.timeout` | `timeout` |+| Desktop stopped before the run | Heartbeat not fresh, and `--start` not given | `desktop-stopped` |+| Desktop stopped mid-run (23:00 stop, idle autosleep) | A poll fails, then `desktop_status` shows the desktop down | `auto-stopped` |+| Run would cross the auto-stop | `checkWindow` | `autostop-window` |+| Desktop not the caller's | Not in `desktop_status` | `not-owned` |+| Prompt corrupted in transit | sha256 mismatch | `remote-error` |+| `claude` missing on the desktop | `RUOS_NO_RUNNER` | `remote-error` |+| SSH key not armed | ssh exit 255 + `publickey` | `auth-expired` |+| Run outlives its timeout | Wall-clock check; the process group is stopped | `timeout` |++On every failure the agent is set `idle` and the claim is released.++## Threat model++| Threat | Mitigation |+|---|---|+| Cross-tenant shell via `:17870` | Transport excluded. Smoke check 4. Client refuses the port. |+| Acting on another tenant's desktop | Ids resolve only against the caller's own `desktop_status`. The fleet re-checks ownership on every call. |+| Shell injection from task text (including a prompt-injected agent writing the task) | Base64-only payloads. One builder. Tests run hostile prompts through a real `/bin/sh`. |+| Injection via ids, model, budget, offset or repo path | Allow-list regexes. Canonical numbers. `..` and leading `-` refused. |+| Credential leakage | Bearer token and SSH key path come only from the environment. They are never logged or written to events. |+| Prompt or output leakage into shared state | Events carry ids and sizes only. Output is kept in a 0600 local file and a 0700 remote run dir. |+| Accidental spend | No start without `--start`. Auto-stop window check. `--max-budget-usd` passes through to `claude -p`. |+| Destructive operations | `stop` and `desktop-stop` require `--confirm`. No delete or provision verbs. |+| Silent success (cognitum#620 pattern) | Every run needs a positive exit code from the desktop. A missing run dir or a missing pid is an error. |++Residual risk: the remote `claude -p` runs with the desktop user's full trust. That is the user's own desktop, and its tool permissions are governed by its own Claude Code settings.++## Consequences++**Positive:**+- Swarm agents can run on the user's own ruOS desktops, visible in the swarm pane.+- No new trust path is added.+- Swarm state stays one source of truth.++**Negative:**+- Streaming is poll-based, because `desktop_exec` is request/response. Each poll costs one audited fleet call.+- SSH works only desktop-to-desktop.+- The fleet MCP's `desktop_exec` output shape is normalised defensively (`stdout|output`, `exit_code|exitCode`). A change on the ruOS side is caught by the live check, not by unit tests.++## Verification++- `bash plugins/ruflo-ruos/scripts/smoke.sh` runs the structural checks, the no-`:17870` grep, an offline exit-2 check, and the full `node --test` suite.+- The suite includes London-school adapter tests, transport failure typing with injected `fetch` and `spawn`, injection tests, real-`/bin/sh` execution of the builder output, and an integration test against the in-tree CLI's real `agent_spawn` and `claims_*` tools.+- The live end-to-end and benchmark results are recorded in the PR.