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(cli): flush piped stdout before process.exit (#3851)

ruv275ec2905d00
diff --git a/v3/@claude-flow/cli/__tests__/cli-piped-stdout-3851.test.ts b/v3/@claude-flow/cli/__tests__/cli-piped-stdout-3851.test.ts
new file mode 100644
index 0000000000..0ce0ef3e78
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/cli-piped-stdout-3851.test.ts
@@ -0,0 +1,75 @@
+/**
+ * #3851: `ruflo <cmd> | consumer` lost everything after the first pipe buffer
+ * (64 KiB) because the bin wrappers call process.exit(0) right after
+ * cli.run(), and stdout writes to a pipe are asynchronous on POSIX.
+ *
+ * Runs the real CLI class and the same `run().then(process.exit(0))` tail the
+ * bin wrappers use, with stdout a pipe and a deliberately slow reader.
+ */
+import { describe, it, expect } from 'vitest';
+import { spawn } from 'node:child_process';
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { createRequire } from 'node:module';
+import { pathToFileURL } from 'node:url';
+
+const cliDir = resolve(__dirname, '..');
+const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href;
+const BYTES = 2 * 1024 * 1024;
+
+function runPiped(exitStyle: 'zero' | 'fail'): Promise<{ out: Buffer; code: number | null }> {
+ const dir = mkdtempSync(join(tmpdir(), 'cli-3851-'));
+ const script = join(dir, 'run.ts');
+ writeFileSync(script, `
+import { CLI } from ${JSON.stringify(join(cliDir, 'src', 'index.ts'))};
+import { commandParser } from ${JSON.stringify(join(cliDir, 'src', 'parser.ts'))};
+commandParser.registerCommand({
+ name: 'bigout-3851', description: 'test',
+ action: async () => {
+ const line = JSON.stringify({ k: 'x'.repeat(1000) }) + '\\n';
+ let n = 0;
+ while (n < ${BYTES}) { process.stdout.write(line); n += line.length; }
+ return ${exitStyle === 'fail' ? '{ success: false, exitCode: 3 }' : '{ success: true }'};
+ },
+});
+new CLI().run(['bigout-3851'])
+ .then(() => process.exit(0))
+ .catch(() => process.exit(1));
+`);
+ return new Promise((res, rej) => {
+ const child = spawn(process.execPath, ['--import', tsxLoader, script], { cwd: cliDir, stdio: ['ignore', 'pipe', 'ignore'] });
+ const chunks: Buffer[] = [];
+ // slow reader: pause so the pipe buffer fills while the child is exiting
+ child.stdout!.pause();
+ setTimeout(() => {
+ child.stdout!.on('data', (c: Buffer) => chunks.push(c));
+ child.stdout!.resume();
+ }, 1500);
+ child.on('error', rej);
+ child.on('close', (code) => {
+ rmSync(dir, { recursive: true, force: true });
+ res({ out: Buffer.concat(chunks), code });
+ });
+ });
+}
+
+describe('#3851 piped stdout is not truncated by process.exit', () => {
+ it('delivers all output on a clean exit', async () => {
+ const { out, code } = await runPiped('zero');
+ expect(code).toBe(0);
+ expect(out.length).toBeGreaterThanOrEqual(BYTES);
+ for (const l of out.toString().trim().split('\n').slice(0, 3)) JSON.parse(l);
+ // last line must be a complete JSON document, i.e. nothing was cut off
+ const lines = out.toString().trimEnd().split('\n');
+ expect(() => JSON.parse(lines[lines.length - 1])).not.toThrow();
+ }, 60_000);
+
+ it('delivers all output when the command fails (process.exit(exitCode) in CLI.run)', async () => {
+ const { out, code } = await runPiped('fail');
+ expect(code).toBe(3);
+ const lines = out.toString().trimEnd().split('\n');
+ expect(out.length).toBeGreaterThanOrEqual(BYTES);
+ expect(() => JSON.parse(lines[lines.length - 1])).not.toThrow();
+ }, 60_000);
+});
diff --git a/v3/@claude-flow/cli/src/blocking-stdio.ts b/v3/@claude-flow/cli/src/blocking-stdio.ts
new file mode 100644
index 0000000000..e039af8ed2
--- /dev/null
+++ b/v3/@claude-flow/cli/src/blocking-stdio.ts
@@ -0,0 +1,22 @@
+/**
+ * #3851: stdout/stderr writes to a pipe are asynchronous on POSIX, so the
+ * `process.exit()` calls that follow a command (bin wrappers, CLI.run error
+ * paths, commands that exit themselves) discard whatever the consumer has not
+ * read yet, i.e. everything past the pipe buffer (64 KiB). Switching the pipe
+ * handles to blocking mode makes every write complete before it returns, so
+ * every exit path is safe. Same technique as the MCP stdio server.
+ * Files and TTYs are already synchronous and are left alone.
+ */
+export function ensureBlockingStdio(): void {
+ for (const stream of [process.stdout, process.stderr]) {
+ const s = stream as NodeJS.WriteStream & {
+ _handle?: { setBlocking?: (blocking: boolean) => void };
+ };
+ if (s.isTTY) continue;
+ try {
+ s._handle?.setBlocking?.(true);
+ } catch {
+ // best effort: never fail the CLI because stdio could not be switched
+ }
+ }
+}
diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.ts
index 46d183a339..4728becc99 100644
--- a/v3/@claude-flow/cli/src/index.ts
+++ b/v3/@claude-flow/cli/src/index.ts
@@ -22,6 +22,7 @@ import { OutputFormatter, output } from './output.js';
import { commands, commandsByCategory, getCommandsByCategory, commandRegistry, getCommand, getCommandAsync, getCommandNames, getLazyCommandNames, hasCommand } from './commands/index.js';
import { suggestCommand } from './suggest.js';
import { runStartupUpdateCheck } from './update/index.js';
+import { ensureBlockingStdio } from './blocking-stdio.js';
// Read version from package.json at runtime
function getPackageVersion(): string {
@@ -82,6 +83,8 @@ export class CLI {
* Run the CLI with given arguments
*/
async run(args: string[] = process.argv.slice(2)): Promise<void> {
+ // #3851: keep piped output intact across the process.exit() calls below
+ ensureBlockingStdio();
try {
// #1791.2 — If the user invoked a lazy command (e.g. `hive-mind task`),
// pre-load it BEFORE parsing so the parser can build scoped flag