Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

fix(ruflo-ruos): merge hosts.json, detect a killed runner, never skip bytes on a truncated poll

ruv8ab1703158f8
diff --git a/plugins/ruflo-ruos/scripts/cli.mjs b/plugins/ruflo-ruos/scripts/cli.mjs
index 0290a36332..601ba6852c 100755
--- a/plugins/ruflo-ruos/scripts/cli.mjs
+++ b/plugins/ruflo-ruos/scripts/cli.mjs
@@ -200,7 +200,8 @@ async function record(args, env) {
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.snapshotHosts([d]);
+ ledger.setHostAgent(d.id, agentId, true);
ledger.event({ type: 'run.started', runId, agentId, desktopId: d.id, desktopName: d.displayName ?? d.name });
} else if (phase === 'output') {
const b64 = String(args.b64 ?? '');
@@ -214,6 +215,7 @@ async function record(args, env) {
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);
+ ledger.setHostAgent(null, agentId, false);
} else {
throw new RuosError('invalid-input', 'record phase must be start|output|end');
}
diff --git a/plugins/ruflo-ruos/scripts/lib/adapter.mjs b/plugins/ruflo-ruos/scripts/lib/adapter.mjs
index 77c03b926f..c9164f18ac 100644
--- a/plugins/ruflo-ruos/scripts/lib/adapter.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/adapter.mjs
@@ -76,7 +76,7 @@ export class RuosHostAdapter {
async discover() {
const desktops = await this.fleet.listDesktops();
- this.ledger.snapshotHosts(desktops, {});
+ this.ledger.snapshotHosts(desktops);
return desktops;
}
@@ -157,12 +157,12 @@ export class RuosHostAdapter {
const agentType = assertAgentId(o.agentType ?? 'coder');
const timeoutSecs = assertInt(o.timeoutSecs ?? 900, 30, 6 * 3600, 'timeoutSecs');
+ let desktop = await this.resolve(o.desktop);
+ // The 23:00 auto-stop applies to cloud desktops only, not enrolled devices.
const win = checkWindow(t0, timeoutSecs);
- if (!win.ok && !o.ignoreAutoStop) {
+ if (desktop.flyMachineId && !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} */
@@ -172,7 +172,8 @@ export class RuosHostAdapter {
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] });
+ this.ledger.snapshotHosts([desktop]);
+ this.ledger.setHostAgent(desktop.id, agentId, true);
let bytes = 0;
/** @type {number|null} */ let firstOutputMs = null;
@@ -219,6 +220,14 @@ export class RuosHostAdapter {
this.ledger.event({ type: 'run.output', runId, agentId, desktopId: desktop.id, bytes: p.chunk.length });
delay = 1000;
}
+ if (p.exitCode === null && !p.alive && p.chunk.length === 0) {
+ // Re-check once: exit.code is written just after the runner exits.
+ const again = parsePoll((await this.transport.exec(desktop, buildPoll(runId, offset), 30)).stdout);
+ if (again !== 'norun' && again.exitCode === null && !again.alive) {
+ throw new RuosError('remote-error', 'runner died without an exit code (killed on the desktop?)');
+ }
+ continue;
+ }
if (p.exitCode !== null && offset >= p.size) {
exitCode = p.exitCode;
status = exitCode === 0 ? 'completed' : 'failed';
@@ -232,14 +241,14 @@ export class RuosHostAdapter {
} 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);
+ await this.finish(desktop.id, 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);
+ await this.finish(desktop.id, 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],
@@ -247,6 +256,7 @@ export class RuosHostAdapter {
}
/**
+ * @param {string} desktopId
* @param {string} agentId
* @param {string} agentType
* @param {string} runId
@@ -254,7 +264,8 @@ export class RuosHostAdapter {
* @param {number|null} exitCode
* @param {number} bytes
*/
- async finish(agentId, agentType, runId, status, exitCode, bytes) {
+ async finish(desktopId, agentId, agentType, runId, status, exitCode, bytes) {
+ this.ledger.setHostAgent(desktopId, agentId, false);
await this.ledger.updateAgent(agentId, 'idle', { runId, status, exitCode, bytes });
await this.ledger.release(runId, agentId, agentType);
}
diff --git a/plugins/ruflo-ruos/scripts/lib/command-builder.mjs b/plugins/ruflo-ruos/scripts/lib/command-builder.mjs
index 605967f8e8..e76d246fc9 100644
--- a/plugins/ruflo-ruos/scripts/lib/command-builder.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/command-builder.mjs
@@ -106,7 +106,8 @@ export function buildLaunch(spec) {
/**
* Report exit state and size, then return one base64 slice of the log from
- * byte `offset`. Output: `RUOS_POLL:<exit|->:<size>:<base64>`.
+ * byte `offset`. Output: `RUOS_POLL:<exit|->:<size>:<alive 0|1>:<base64>`.
+ * `alive` lets the adapter detect a runner killed before it wrote exit.code.
* @param {string} runId
* @param {number} offset
* @param {number=} maxBytes
@@ -118,7 +119,8 @@ export function buildPoll(runId, offset, maxBytes = POLL_SLICE_BYTES) {
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`,
+ ` ; p=$(sed -n 's/^RUOS_PID://p' pid 2>/dev/null) ; a=0 ; case "$p" in ''|*[!0-9]*) ;; *) kill -0 "$p" 2>/dev/null && a=1 ;; esac` +
+ ` ; printf 'RUOS_POLL:%s:%s:%s:' "$e" "$s" "$a" ; tail -c +${off + 1} out.log 2>/dev/null | head -c ${max} | base64 -w0 ; echo`,
);
}
@@ -179,6 +181,7 @@ export function buildProbe() {
* @typedef {object} PollResult
* @property {number|null} exitCode null while running
* @property {number} size total log size on the desktop
+ * @property {boolean} alive runner process group still exists
* @property {Buffer} chunk
*/
@@ -188,12 +191,17 @@ export function buildProbe() {
*/
export function parsePoll(stdout) {
if (stdout.includes('RUOS_NORUN')) return 'norun';
- const m = /RUOS_POLL:(-|\d+):(\d+):([A-Za-z0-9+/=]*)/.exec(stdout);
+ const m = /RUOS_POLL:(-|\d+):(\d+):([01]):([A-Za-z0-9+/=]*)/.exec(stdout);
if (!m) throw new RuosError('remote-error', 'unparseable poll output');
+ // If the transport truncated the result mid-quantum, decode only whole
+ // quanta: the offset then advances by exactly what was received and the
+ // next poll resumes from there, so no byte is skipped.
+ const whole = m[4].slice(0, m[4].length - (m[4].length % 4));
return {
exitCode: m[1] === '-' ? null : Number(m[1]),
size: Number(m[2]),
- chunk: Buffer.from(m[3], 'base64'),
+ alive: m[3] === '1',
+ chunk: Buffer.from(whole, 'base64'),
};
}
diff --git a/plugins/ruflo-ruos/scripts/lib/ledger.mjs b/plugins/ruflo-ruos/scripts/lib/ledger.mjs
index a9da766556..aec5e6eab2 100644
--- a/plugins/ruflo-ruos/scripts/lib/ledger.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/ledger.mjs
@@ -16,7 +16,7 @@
* 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 { appendFileSync, mkdirSync, writeFileSync, renameSync, existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
@@ -34,7 +34,8 @@ import { pathToFileURL } from 'node:url';
* @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 {(desktops: import('./types.mjs').Desktop[]) => void} snapshotHosts merge host state, keep agent placements
+ * @property {(desktopId: string|null, agentId: string, present: boolean) => void} setHostAgent null desktopId + present=false removes the agent from every host
* @property {(runId: string, chunk: Buffer) => void} appendOutput
* @property {string[]} warnings
*/
@@ -115,6 +116,25 @@ export function createLedger({ cwd, callTool, now = () => new Date() }) {
}
};
+ /**
+ * Read-merge-write hosts.json so a discovery never drops agent placements
+ * and a run never drops the other hosts.
+ * @param {(hosts: Map<string, any>) => void} mutate
+ */
+ const writeHosts = (mutate) => {
+ ensure();
+ const file = join(dir, 'hosts.json');
+ /** @type {Map<string, any>} */
+ const hosts = new Map();
+ try {
+ for (const h of JSON.parse(readFileSync(file, 'utf8')).hosts ?? []) hosts.set(h.desktopId, h);
+ } catch { /* first write or unreadable: start fresh */ }
+ mutate(hosts);
+ const tmp = join(dir, `hosts.json.${process.pid}.tmp`);
+ writeFileSync(tmp, JSON.stringify({ updatedAt: now().toISOString(), hosts: [...hosts.values()] }, null, 2), { mode: 0o600 });
+ renameSync(tmp, file);
+ };
+
/** @type {Ledger} */
const ledger = {
get swarmLedger() { return available ? 'cli' : 'unavailable'; },
@@ -145,22 +165,31 @@ export function createLedger({ cwd, callTool, now = () => new Date() }) {
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'));
+ snapshotHosts(desktops) {
+ writeHosts((hosts) => {
+ for (const d of desktops) {
+ const prev = hosts.get(d.id);
+ hosts.set(d.id, {
+ desktopId: d.id,
+ name: d.displayName ?? d.name,
+ state: d.state,
+ heartbeatStatus: d.heartbeatStatus,
+ heartbeatAt: d.heartbeatAt,
+ agents: prev ? prev.agents : [],
+ });
+ }
+ });
+ },
+ setHostAgent(desktopId, agentId, present) {
+ writeHosts((hosts) => {
+ if (desktopId === null) {
+ for (const [id, h] of hosts) hosts.set(id, { ...h, agents: h.agents.filter((/** @type {string} */ a) => a !== agentId) });
+ return;
+ }
+ const h = hosts.get(desktopId) ?? { desktopId, name: desktopId, state: null, heartbeatStatus: null, heartbeatAt: null, agents: [] };
+ const rest = h.agents.filter((/** @type {string} */ a) => a !== agentId);
+ hosts.set(desktopId, { ...h, agents: present ? [...rest, agentId] : rest });
+ });
},
appendOutput(runId, chunk) {
ensure();
diff --git a/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md b/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md
index 2ef7a66515..68da21db9c 100644
--- a/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md
+++ b/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md
@@ -36,7 +36,7 @@ Transport rules — non-negotiable:
`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
+ `RUOS_POLL:<exit|->:<size>:<alive 0|1>:<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.
diff --git a/plugins/ruflo-ruos/tests/adapter.test.mjs b/plugins/ruflo-ruos/tests/adapter.test.mjs
index 9be9074ddb..3ff91c1750 100644
--- a/plugins/ruflo-ruos/tests/adapter.test.mjs
+++ b/plugins/ruflo-ruos/tests/adapter.test.mjs
@@ -37,7 +37,7 @@ 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 transport = over.transport ?? remote([`RUOS_POLL:-:6:1:${b64('hello ')}`, 'RUOS_POLL:-:6:1:', `RUOS_POLL:0:12:0:${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 };
@@ -56,7 +56,8 @@ test('happy path: launch, stream, ledger + claims, keepawake', async () => {
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']);
+ assert.deepEqual(names.filter((n) => n !== 'snapshotHosts'), ['claim', 'registerAgent', 'setHostAgent', 'setHostAgent', 'updateAgent', 'release']);
+ assert.deepEqual(ledger.calls.filter((c) => c[0] === 'setHostAgent').map((c) => c[1][2]), [true, false], 'placed, then removed');
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']);
@@ -83,7 +84,7 @@ test('--start wakes the desktop and waits for a fresh heartbeat (not `ready`)',
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 transport = remote([`RUOS_POLL:0:2:0:${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');
@@ -96,7 +97,7 @@ test('desktop auto-stopped mid-run is reported as auto-stopped and released', as
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 });
+ const adapter = new RuosHostAdapter({ fleet, transport: remote([`RUOS_POLL:-:2:1:${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');
@@ -134,7 +135,7 @@ test('missing runner on the desktop is a clear error', async () => {
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 transport = remote([`RUOS_POLL:0: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);
@@ -143,14 +144,14 @@ test('a run that would cross the 23:00 Toronto auto-stop is refused unless overr
});
test('run timeout stops the remote process group', async () => {
- const { adapter, transport } = setup({ transport: remote(['RUOS_POLL:-:0:']) });
+ const { adapter, transport } = setup({ transport: remote(['RUOS_POLL:-:0:1:']) });
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 { adapter, ledger } = setup({ transport: remote([`RUOS_POLL:-:1:1:${b64('x')}`, 'RUOS_POLL:-:1:1:']) });
const p = adapter.run({ ...base, signal: ac.signal, onOutput: () => ac.abort() });
const out = await p;
assert.equal(out.status, 'stopped');
@@ -181,3 +182,36 @@ test('isUp uses heartbeat freshness, not `ready`', () => {
assert.equal(isUp(desktop({ heartbeatStatus: 'asleep', heartbeatAt: now / 1000 }), now), false);
assert.equal(isUp(desktop({ heartbeatAt: null, ready: true }), now), false);
});
+
+test('runner killed without an exit code is detected, not waited out', async () => {
+ const { adapter, ledger } = setup({ transport: remote(['RUOS_POLL:-:0:0:']) });
+ await assert.rejects(adapter.run(base), /died without an exit code/);
+ assert.equal(ledger.events.at(-1).type, 'run.failed');
+});
+
+test('enrolled devices (no Fly id) are not subject to the cloud auto-stop window', async () => {
+ const clock = fakeClock(Date.parse('2026-10-02T02:45:00Z'));
+ const fleet = fakeFleet([desktop({ flyMachineId: null, heartbeatAt: Math.floor(clock.now() / 1000) })]);
+ const adapter = new RuosHostAdapter({ fleet, transport: remote(['RUOS_POLL:0:0:0:']), ledger: /** @type {any} */ (fakeLedger()), now: clock.now, sleep: clock.sleep });
+ assert.equal((await adapter.run({ ...base, timeoutSecs: 3600 })).status, 'completed');
+});
+
+test('a poll truncated mid-base64-quantum loses no bytes', async () => {
+ const full = Buffer.from('abcdefghij').toString('base64'); // 16 chars
+ const cut = full.slice(0, 7); // transport truncated: 1 whole quantum + 3 chars
+ let polls = 0;
+ const t = fakeTransport((cmd) => {
+ if (cmd.includes('RUOS_PREPARED')) return ok('RUOS_PREPARED');
+ if (cmd.startsWith("printf '%s'")) return ok('');
+ if (cmd.includes('RUOS_NO_RUNNER')) return ok(`RUOS_SHA:${SHA}\nRUOS_PID:7\n`);
+ const off = Number(/tail -c \+(\d+)/.exec(cmd)?.[1]) - 1;
+ polls++;
+ if (polls === 1) return ok(`RUOS_POLL:-:10:1:${cut}`);
+ return ok(`RUOS_POLL:0:10:0:${Buffer.from('abcdefghij'.slice(off)).toString('base64')}`);
+ });
+ const { adapter } = setup({ transport: t });
+ /** @type {string[]} */ const seen = [];
+ const out = await adapter.run({ ...base, onOutput: (c) => seen.push(c.toString()) });
+ assert.equal(seen.join(''), 'abcdefghij');
+ assert.equal(out.bytes, 10);
+});
diff --git a/plugins/ruflo-ruos/tests/command-builder.test.mjs b/plugins/ruflo-ruos/tests/command-builder.test.mjs
index acc98c73e4..e776305372 100644
--- a/plugins/ruflo-ruos/tests/command-builder.test.mjs
+++ b/plugins/ruflo-ruos/tests/command-builder.test.mjs
@@ -95,9 +95,9 @@ test('launch/poll/stop/probe are single fixed-template lines', () => {
test('parsePoll / parseLaunch', () => {
assert.equal(parsePoll('RUOS_NORUN\n'), 'norun');
- const p = parsePoll(`RUOS_POLL:0:5:${Buffer.from('hello').toString('base64')}\n`);
+ const p = parsePoll(`RUOS_POLL:0:5:0:${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');
+ const r = parsePoll('RUOS_POLL:-:0:1:\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`);
diff --git a/plugins/ruflo-ruos/tests/fakes.mjs b/plugins/ruflo-ruos/tests/fakes.mjs
index 1931955ea4..4a1ea1e52b 100644
--- a/plugins/ruflo-ruos/tests/fakes.mjs
+++ b/plugins/ruflo-ruos/tests/fakes.mjs
@@ -86,6 +86,7 @@ export function fakeLedger() {
release: async (/** @type {unknown[]} */ ...a) => { calls.push(['release', a]); },
event: (/** @type {any} */ e) => { events.push(e); },
snapshotHosts: (/** @type {unknown[]} */ ...a) => { calls.push(['snapshotHosts', a]); },
+ setHostAgent: (/** @type {unknown[]} */ ...a) => { calls.push(['setHostAgent', 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.mjs
index ee06624eff..6a915cefb6 100644
--- a/plugins/ruflo-ruos/tests/ledger-cli.test.mjs
+++ b/plugins/ruflo-ruos/tests/ledger-cli.test.mjs
@@ -23,7 +23,8 @@ test('ledger records through ruflo tools (mocked callTool) and owns only .claude
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'] });
+ ledger.snapshotHosts([desktop()]);
+ ledger.setHostAgent(DESKTOP_ID, 'a1', true);
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']);
@@ -36,6 +37,21 @@ test('ledger records through ruflo tools (mocked callTool) and owns only .claude
assert.ok(!existsSync(join(cwd, '.claude-flow/agents')), 'never writes ruflo stores directly');
});
+test('hosts.json merges: discovery keeps placements, runs keep other hosts', () => {
+ const cwd = tmp();
+ const ledger = createLedger({ cwd, callTool: null });
+ const other = desktop({ id: 'c'.repeat(32), displayName: 'Other' });
+ ledger.snapshotHosts([desktop(), other]);
+ ledger.setHostAgent(DESKTOP_ID, 'a1', true);
+ ledger.snapshotHosts([desktop({ state: 'started' })]); // single-host refresh mid-run
+ ledger.snapshotHosts([desktop(), other]); // full discovery mid-run
+ const read = () => JSON.parse(readFileSync(join(cwd, '.claude-flow/ruos/hosts.json'), 'utf8')).hosts;
+ assert.equal(read().length, 2);
+ assert.deepEqual(read().find((/** @type {any} */ h) => h.desktopId === DESKTOP_ID).agents, ['a1']);
+ ledger.setHostAgent(null, 'a1', false);
+ assert.deepEqual(read().find((/** @type {any} */ h) => h.desktopId === DESKTOP_ID).agents, []);
+});
+
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');
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.md
index d113ee7250..723cb3da7f 100644
--- a/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md
+++ b/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md
@@ -46,7 +46,7 @@ Every shell string sent to a desktop comes from one audited module, `command-bui
- 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.
+- Output returns as `RUOS_POLL:<exit>:<size>:<alive>:<base64 slice>`, so arbitrary bytes survive the JSON tool result. Only whole base64 quanta are decoded, so a truncated result never skips bytes. The `alive` flag (`kill -0` on the pid) detects a runner killed before it wrote its exit code.
- 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.
@@ -105,6 +105,7 @@ Each failure surfaces as a typed `RuosError` code:
| `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` |
+| Runner killed without an exit code | Poll shows `alive=0` and no exit code, twice | `remote-error` |
On every failure the agent is set `idle` and the claim is released.