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

feat(harness): report the live process, not the install (#3521)

Mathew Beane4c5fdb1fac20
diff --git a/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts b/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts
index 77aa913590..36b98d2f75 100644
--- a/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts
+++ b/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts
@@ -50,7 +50,8 @@ describe('Ruflo capability brain', () => {
expect(auth.riskFlags).toEqual(
expect.arrayContaining(['network', 'credential-pii', 'approval']),
);
- expect(brain.cliCommands).toHaveLength(53);
+ expect(brain.cliCommands).toHaveLength(54);
+ expect(brain.cliCommands).toContain('harness');
});
it('does not confuse registration with runtime health or authorization', () => {
diff --git a/v3/@claude-flow/cli/__tests__/harness-live-probe.test.ts b/v3/@claude-flow/cli/__tests__/harness-live-probe.test.ts
new file mode 100644
index 0000000000..358ef407d2
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/harness-live-probe.test.ts
@@ -0,0 +1,385 @@
+/**
+ * `ruflo harness` live probe (PR #3521 review).
+ *
+ * Each block is a regression test for one review item. The probe runs
+ * against a fake HarnessSys so process tables, lsof output and team files are
+ * exact; the last block runs real processes.
+ */
+import { describe, it, expect } from 'vitest';
+import { spawn, spawnSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ collectLiveHarness,
+ detectHost,
+ insideRoot,
+ isRufloMcp,
+ parsePs,
+ redactCommand,
+ realSys,
+ type HarnessSys,
+ type ProcRow,
+ type RunResult,
+} from '../src/services/live-harness.js';
+
+const ROOT = '/work/pr-3521';
+const CLI = '/opt/ruflo/v3/@claude-flow/cli/bin/cli.js';
+
+interface FakeOpts {
+ ps?: string | RunResult;
+ lsof?: (args: string[]) => RunResult;
+ files?: Record<string, string>;
+ dirs?: Record<string, Array<{ name: string; isDir: boolean }>>;
+ mtimes?: Record<string, number>;
+ alive?: Record<number, 'alive' | 'dead' | 'eperm'>;
+ env?: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+ realpaths?: Record<string, string>;
+ now?: () => number;
+ ppid?: number;
+}
+
+function fakeSys(o: FakeOpts = {}): HarnessSys & { calls: Array<{ cmd: string; args: string[]; timeoutMs: number }> } {
+ const calls: Array<{ cmd: string; args: string[]; timeoutMs: number }> = [];
+ const files = o.files ?? {};
+ const dirs = o.dirs ?? {};
+ return {
+ calls,
+ platform: o.platform ?? 'darwin',
+ env: o.env ?? {},
+ pid: 99999,
+ ppid: o.ppid ?? 500,
+ cwd: () => ROOT,
+ now: o.now ?? (() => Date.parse('2026-09-28T12:00:00Z')),
+ run(cmd, args, timeoutMs) {
+ calls.push({ cmd, args, timeoutMs });
+ if (cmd === 'ps') {
+ if (o.ps === undefined) return { stdout: '', state: 'unavailable', status: null };
+ return typeof o.ps === 'string' ? { stdout: o.ps, state: 'ok', status: 0 } : o.ps;
+ }
+ if (cmd === 'lsof') return o.lsof ? o.lsof(args) : { stdout: '', state: 'unavailable', status: null };
+ return { stdout: '', state: 'unavailable', status: null };
+ },
+ signal0: (pid) => o.alive?.[pid] ?? 'dead',
+ exists: (p) => p in files || p in dirs,
+ readFile: (p) => {
+ if (!(p in files)) throw new Error('ENOENT');
+ return files[p];
+ },
+ readDir: (p) => dirs[p] ?? [],
+ mtimeMs: (p) => o.mtimes?.[p],
+ realpath: (p) => o.realpaths?.[p] ?? p,
+ readlink: () => undefined,
+ };
+}
+
+const ps = (rows: Array<[number, number, string]>) => rows.map(([pid, ppid, cmd]) => `${pid} ${ppid} ${cmd}`).join('\n');
+const lsofCwd = (map: Record<number, string>) => (args: string[]): RunResult => {
+ if (!args.includes('cwd')) return { stdout: '', state: 'ok', status: 1 };
+ const pids = args[args.indexOf('-p') + 1].split(',').map(Number);
+ return { stdout: pids.filter((p) => map[p]).map((p) => `p${p}\nfcwd\nn${map[p]}`).join('\n'), state: 'ok', status: 0 };
+};
+
+describe('MCP detection matches the root exactly (review #4)', () => {
+ it('does not count a server in a sibling directory whose path shares a prefix', () => {
+ const sys = fakeSys({
+ ps: ps([[100, 1, `node ${CLI} mcp start`], [101, 1, `node ${CLI} mcp start`]]),
+ alive: { 100: 'alive', 101: 'alive' },
+ lsof: lsofCwd({ 100: ROOT, 101: `${ROOT}-2` }),
+ });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ expect(r.mcp.count).toBe(1);
+ expect(r.mcp.servers.map((s) => s.pid)).toEqual([100]);
+ });
+
+ it('does not count a process whose argv merely mentions the root', () => {
+ const sys = fakeSys({
+ ps: ps([[200, 1, `/bin/zsh -c echo ruflo mcp start ${ROOT}`], [201, 1, `grep ${CLI} mcp start ${ROOT}`]]),
+ lsof: lsofCwd({ 200: ROOT, 201: ROOT }),
+ });
+ expect(collectLiveHarness(sys, { root: ROOT }).mcp.count).toBe(0);
+ });
+
+ it('counts a server whose cwd is a subdirectory of the root', () => {
+ const sys = fakeSys({ ps: ps([[300, 1, `npx ruflo@latest mcp start`]]), lsof: lsofCwd({ 300: `${ROOT}/packages/a` }) });
+ expect(collectLiveHarness(sys, { root: ROOT }).mcp.count).toBe(1);
+ });
+
+ it('ignores another tool\'s `mcp start` and counts npx→node once', () => {
+ const sys = fakeSys({
+ ps: ps([
+ [400, 1, 'npm exec ruvector mcp start'],
+ [401, 1, 'npx ruflo mcp start'],
+ [402, 401, `node /home/u/.npm/_npx/abc/node_modules/.bin/ruflo mcp start`],
+ ]),
+ lsof: lsofCwd({ 400: ROOT, 401: ROOT, 402: ROOT }),
+ });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ expect(r.mcp.servers.map((s) => s.pid)).toEqual([402]);
+ });
+
+ it('uses one lsof call for every candidate cwd', () => {
+ const sys = fakeSys({
+ ps: ps([[1, 0, `node ${CLI} mcp start`], [2, 0, `node ${CLI} mcp start`], [3, 0, `node ${CLI} mcp start`]]),
+ lsof: lsofCwd({ 1: ROOT, 2: ROOT, 3: '/elsewhere' }),
+ });
+ collectLiveHarness(sys, { root: ROOT });
+ expect(sys.calls.filter((c) => c.cmd === 'lsof')).toHaveLength(1);
+ });
+
+ it('path helpers: boundary match and launcher/identity rules', () => {
+ expect(insideRoot('/a/b', ['/a/b'])).toBe(true);
+ expect(insideRoot('/a/b/c', ['/a/b'])).toBe(true);
+ expect(insideRoot('/a/b-2', ['/a/b'])).toBe(false);
+ expect(isRufloMcp(['sh', '-c', `node ${CLI} mcp start`])).toBe(false);
+ expect(isRufloMcp(['node', CLI, 'mcp', 'start'])).toBe(true);
+ expect(isRufloMcp(['node', CLI, 'mcp', 'status'])).toBe(false);
+ expect(isRufloMcp(['npx', '@claude-flow/cli@latest', 'mcp', 'start'])).toBe(true);
+ });
+});
+
+describe('MCP output never includes full command lines (review #6)', () => {
+ it('reports count, pid and a redacted command without arguments', () => {
+ const secret = 'sk-live-THIS_MUST_NOT_LEAK';
+ const sys = fakeSys({
+ ps: ps([[500, 1, `node ${CLI} mcp start --token ${secret} --api-key=${secret}`]]),
+ lsof: lsofCwd({ 500: ROOT }),
+ });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ const json = JSON.stringify(r);
+ expect(json).not.toContain(secret);
+ expect(json).not.toContain('/opt/ruflo');
+ expect(r.mcp.servers[0]).toEqual({ pid: 500, command: 'cli mcp start (+3 args)' });
+ expect(redactCommand(['npx', 'ruflo', 'mcp', 'start'])).toBe('npx mcp start');
+ });
+});
+
+describe('memory probe covers both databases (review #5)', () => {
+ it('asks lsof about memory.db and agentdb-memory.db (+WAL/SHM) in one call', () => {
+ const swarm = `${ROOT}/.swarm`;
+ const files = Object.fromEntries(
+ ['agentdb-memory.db', 'agentdb-memory.db-wal', 'agentdb-memory.db-shm', 'memory.db'].map((f) => [`${swarm}/${f}`, '']),
+ );
+ let asked: string[] = [];
+ const sys = fakeSys({
+ ps: ps([[1, 0, 'launchd']]),
+ files,
+ lsof: (args) => {
+ asked = args;
+ return { stdout: '700\n701\n700\n99999\n', state: 'ok', status: 0 };
+ },
+ });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ expect(asked).toEqual(expect.arrayContaining(Object.keys(files)));
+ expect(r.memory.openPids).toEqual([700, 701]);
+ expect(r.line).toContain('memory-open=2');
+ expect(sys.calls.filter((c) => c.cmd === 'lsof')).toHaveLength(1);
+ });
+
+ it('reports held-open when only agentdb-memory.db exists', () => {
+ const sys = fakeSys({
+ ps: ps([[1, 0, 'launchd']]),
+ files: { [`${ROOT}/.swarm/agentdb-memory.db`]: '' },
+ lsof: () => ({ stdout: '42\n', state: 'ok', status: 0 }),
+ });
+ expect(collectLiveHarness(sys, { root: ROOT }).memory.openPids).toEqual([42]);
+ });
+});
+
+describe('teams read the team-bus layout with a liveness check (review #3)', () => {
+ const now = Date.parse('2026-09-28T12:00:00Z');
+ const teams = `${ROOT}/.claude-flow/teams`;
+ const recent = new Date(now - 60_000).toISOString();
+ const old = new Date(now - 6 * 3600_000).toISOString();
+ const team = (name: string, extra: Record<string, unknown> = {}) =>
+ JSON.stringify({ id: name, name, status: 'active', createdAt: old, members: { a: { name: 'a', registeredAt: old } }, ...extra });
+
+ it('finds `<name>/team.json` and the legacy flat file', () => {
+ const sys = fakeSys({
+ ps: ps([[1, 0, 'launchd']]),
+ dirs: { [teams]: [{ name: 'bus', isDir: true }, { name: 'flat.json', isDir: false }] },
+ files: {
+ [`${teams}/bus/team.json`]: team('bus', { plan: { steps: [], index: 0, updatedAt: recent } }),
+ [`${teams}/flat.json`]: team('flat', { createdAt: recent }),
+ },
+ });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ expect(r.teams.map((t) => t.name).sort()).toEqual(['bus', 'flat']);
+ expect(r.line).toContain('teams=2');
+ });
+
+ it('a crashed team with no recent activity is stale, not live forever', () => {
+ const sys = fakeSys({
+ ps: ps([[1, 0, 'launchd']]),
+ dirs: { [teams]: [{ name: 'crashed', isDir: true }] },
+ files: { [`${teams}/crashed/team.json`]: team('crashed') },
+ mtimes: { [`${teams}/crashed/team.json`]: now - 6 * 3600_000 },
+ });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ expect(r.teams).toEqual([]);
+ expect(r.staleTeams).toEqual(['crashed']);
+ expect(r.line).toContain('teams=0');
+ expect(r.line).toContain('stale-teams=1');
+ });
+
+ it('a recently written team.json (mtime) counts as live; shutdown never does', () => {
+ const sys = fakeSys({
+ ps: ps([[1, 0, 'launchd']]),
+ dirs: { [teams]: [{ name: 'busy', isDir: true }, { name: 'done', isDir: true }] },
+ files: {
+ [`${teams}/busy/team.json`]: team('busy'),
+ [`${teams}/done/team.json`]: team('done', { status: 'shutdown', shutdownAt: recent }),
+ },
+ mtimes: { [`${teams}/busy/team.json`]: now - 30_000, [`${teams}/done/team.json`]: now },
+ });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ expect(r.teams.map((t) => t.name)).toEqual(['busy']);
+ expect(r.staleTeams).toEqual([]);
+ });
+
+ it('an old team with a running member pid stays live', () => {
+ const sys = fakeSys({
+ ps: ps([[1, 0, 'launchd']]),
+ dirs: { [teams]: [{ name: 't', isDir: true }] },
+ files: { [`${teams}/t/team.json`]: team('t', { members: { a: { pid: 4242, registeredAt: old } } }) },
+ alive: { 4242: 'alive' },
+ });
+ expect(collectLiveHarness(sys, { root: ROOT }).teams).toHaveLength(1);
+ });
+});
+
+describe('daemon pid handling (minor: PID reuse, EPERM)', () => {
+ const pidFile = `${ROOT}/.claude-flow/daemon.pid`;
+
+ it('a recycled pid that is not a daemon reads as stale', () => {
+ const sys = fakeSys({ ps: ps([[800, 1, '/usr/bin/vim notes.txt']]), files: { [pidFile]: '800' }, alive: { 800: 'alive' } });
+ expect(collectLiveHarness(sys, { root: ROOT }).daemon).toMatchObject({ state: 'stale', pid: 800, reason: 'pid reused' });
+ });
+
+ it('a daemon for another workspace reads as stale', () => {
+ const sys = fakeSys({
+ ps: ps([[801, 1, `node ${CLI} daemon start --foreground --workspace /work/other`]]),
+ files: { [pidFile]: '801' },
+ alive: { 801: 'alive' },
+ });
+ expect(collectLiveHarness(sys, { root: ROOT }).daemon.state).toBe('stale');
+ });
+
+ it('our daemon is live and verified', () => {
+ const sys = fakeSys({
+ ps: ps([[802, 1, `node ${CLI} daemon start --foreground --workspace ${ROOT}`]]),
+ files: { [pidFile]: '802' },
+ alive: { 802: 'alive' },
+ });
+ expect(collectLiveHarness(sys, { root: ROOT }).daemon).toEqual({ state: 'live', pid: 802, verified: true });
+ });
+
+ it('EPERM (another user\'s process) is alive, not dead', () => {
+ const sys = fakeSys({ files: { [pidFile]: '803' }, alive: { 803: 'eperm' } });
+ expect(collectLiveHarness(sys, { root: ROOT }).daemon).toMatchObject({ state: 'live', pid: 803 });
+ });
+
+ it('a dead pid is stale', () => {
+ const sys = fakeSys({ ps: ps([[1, 0, 'launchd']]), files: { [pidFile]: '804' } });
+ expect(collectLiveHarness(sys, { root: ROOT }).daemon.state).toBe('stale');
+ });
+});
+
+describe('probe availability and budget (minors: portability, hang budget)', () => {
+ it('reports "probe unavailable" instead of idle when ps/lsof are missing', () => {
+ const sys = fakeSys({ files: { [`${ROOT}/.swarm/memory.db`]: '' } });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ expect(r.status).toBe('unknown');
+ expect(r.line).toContain('mcp=?');
+ expect(r.line).toContain('memory-open=?');
+ expect(r.line).toContain('probe-unavailable=ps:unavailable,lsof:unavailable');
+ });
+
+ it('never spawns ps or lsof on Windows', () => {
+ const sys = fakeSys({ platform: 'win32', ps: 'x', files: { [`${ROOT}/.swarm/memory.db`]: '' } });
+ const r = collectLiveHarness(sys, { root: ROOT });
+ expect(sys.calls).toEqual([]);
+ expect(r.probes).toEqual({ ps: 'unavailable', lsof: 'unavailable' });
+ });
+
+ it('treats a ps that lists nothing (busybox) as unavailable', () => {
+ const r = collectLiveHarness(fakeSys({ ps: '' }), { root: ROOT });
+ expect(r.probes.ps).toBe('unavailable');
+ });
+
+ it('stays inside one overall deadline: later calls are skipped, per-call timeouts shrink', () => {
+ let t = 0;
+ const sys = fakeSys({
+ now: () => t,
+ ps: ps([[1, 0, `node ${CLI} mcp start`]]),
+ files: { [`${ROOT}/.swarm/memory.db`]: '' },
+ lsof: () => ({ stdout: '', state: 'timeout', status: null }),
+ });
+ const run = sys.run.bind(sys);
+ sys.run = (cmd, args, timeoutMs) => {
+ const r = run(cmd, args, timeoutMs);
+ t += timeoutMs; // every call burns its full timeout
+ return r;
+ };
+ const r = collectLiveHarness(sys, { root: ROOT, budgetMs: 2000 });
+ const total = sys.calls.reduce((sum, c) => sum + c.timeoutMs, 0);
+ expect(total).toBeLessThanOrEqual(2000);
+ expect(sys.calls.length).toBeLessThanOrEqual(3);
+ expect(r.elapsedMs).toBeLessThanOrEqual(2000);
+ expect(r.probes.lsof).toBe('timeout');
+ });
+});
+
+describe('root normalisation (minor: macOS /tmp vs /private/tmp)', () => {
+ it('matches a cwd reported under the real path of a symlinked root', () => {
+ const sys = fakeSys({
+ ps: ps([[900, 1, `node ${CLI} mcp start`]]),
+ realpaths: { '/tmp/proj': '/private/tmp/proj' },
+ lsof: lsofCwd({ 900: '/private/tmp/proj' }),
+ });
+ expect(collectLiveHarness(sys, { root: '/tmp/proj' }).mcp.count).toBe(1);
+ });
+});
+
+describe('host detection walks past `sh -c` (minor)', () => {
+ it('finds codex above a shell parent with no env hints', () => {
+ const table = new Map<number, ProcRow>(
+ parsePs(ps([[500, 400, 'sh -c node cli.js harness --hook'], [400, 300, '/opt/homebrew/bin/codex'], [300, 1, '-zsh']])).map((r) => [r.pid, r]),
+ );
+ const { host, parent } = detectHost(fakeSys({ ppid: 500 }), table);
+ expect(host).toBe('codex');
+ expect(parent).toEqual({ pid: 400, name: 'codex' });
+ });
+
+ it('reports the first non-shell ancestor as the parent, not `sh`', () => {
+ const table = new Map<number, ProcRow>(
+ parsePs(ps([[500, 400, '/bin/bash -c x'], [400, 1, '/usr/local/bin/tmux']])).map((r) => [r.pid, r]),
+ );
+ expect(detectHost(fakeSys({ ppid: 500 }), table)).toEqual({ host: 'process:tmux', parent: { pid: 400, name: 'tmux' } });
+ });
+});
+
+describe('real processes', () => {
+ const hasLsof = process.platform !== 'win32' && spawnSync('lsof', ['-v'], { stdio: 'ignore' }).error === undefined;
+
+ it.skipIf(!hasLsof)('counts a server in the root and not one in a sibling directory', async () => {
+ const base = realpathSync(mkdtempSync(join(tmpdir(), 'harness-real-')));
+ const root = join(base, 'pr-3521');
+ const sibling = join(base, 'pr-3521-2');
+ const binDir = join(base, 'node_modules', '@claude-flow', 'cli', 'bin');
+ for (const d of [root, sibling, binDir]) mkdirSync(d, { recursive: true });
+ const fakeCli = join(binDir, 'cli.js');
+ writeFileSync(fakeCli, 'setInterval(() => {}, 1000);\n');
+ const inRoot = spawn(process.execPath, [fakeCli, 'mcp', 'start'], { cwd: root, stdio: 'ignore' });
+ const inSibling = spawn(process.execPath, [fakeCli, 'mcp', 'start'], { cwd: sibling, stdio: 'ignore' });
+ try {
+ await new Promise((r) => setTimeout(r, 300));
+ const r = collectLiveHarness(realSys, { root });
+ expect(r.mcp.servers.map((s) => s.pid)).toEqual([inRoot.pid]);
+ } finally {
+ inRoot.kill();
+ inSibling.kill();
+ }
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/harness-observe-only.test.ts b/v3/@claude-flow/cli/__tests__/harness-observe-only.test.ts
new file mode 100644
index 0000000000..c1fe2969b6
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/harness-observe-only.test.ts
@@ -0,0 +1,146 @@
+/**
+ * `ruflo harness` must not change what it observes (PR #3521 review #1, #2).
+ *
+ * - The CLI class skips the update check, policy migration, helper refresh,
+ * proven-config adoption and daemon autostart for observe-only commands.
+ * - bin/cli.js runs `harness` before the CLI class loads, writes nothing to
+ * disk, and with --hook fails silently when dist/ is missing.
+ * - The opt-in Codex hook points at this install and disables autostart and
+ * the update check.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const calls = vi.hoisted(() => ({ update: 0, policy: 0, helpers: 0, proven: 0, daemon: 0 }));
+
+vi.mock('../src/update/index.js', () => ({
+ runStartupUpdateCheck: async () => { calls.update++; return { checked: false, updatesAvailable: [], updatesApplied: [] }; },
+}));
+vi.mock('../src/services/policy-runtime.js', () => ({
+ autoMigratePolicyStateIfNeeded: async () => { calls.policy++; return { migrated: false }; },
+}));
+vi.mock('../src/init/helper-refresh.js', () => ({
+ autoRefreshHelpersIfStale: async () => { calls.helpers++; return {}; },
+}));
+vi.mock('../src/config/proven-config-refresh.js', () => ({
+ autoAdoptProvenConfigIfStale: async () => { calls.proven++; return { adopted: false }; },
+}));
+vi.mock('../src/services/daemon-autostart.js', () => ({
+ ensureDaemonRunning: () => { calls.daemon++; return { started: false }; },
+}));
+vi.mock('../src/services/live-harness.js', () => ({
+ collectLiveHarness: () => ({ line: 'harness │ idle', mcp: { count: 0, servers: [] }, memory: { openPids: [] }, teams: [], staleTeams: [], session: {} }),
+}));
+
+import { CLI, isObserveOnlyCommand } from '../src/index.js';
+import { codexHookConfig, runHarnessCli } from '../src/commands/harness.js';
+
+const CLI_DIR = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+describe('CLI startup side effects skip observe-only commands', () => {
+ let out: string[];
+ beforeEach(() => {
+ for (const k of Object.keys(calls) as Array<keyof typeof calls>) calls[k] = 0;
+ out = [];
+ vi.spyOn(process.stdout, 'write').mockImplementation((s: string | Uint8Array) => { out.push(String(s)); return true; });
+ vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
+ vi.spyOn(process, 'exit').mockImplementation((code) => { throw new Error(`process.exit: ${code}`); });
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it('`harness --hook` runs no update check, migration, refresh, adoption or autostart', async () => {
+ await new CLI({ interactive: false }).run(['harness', '--hook']);
+ await new Promise((r) => setTimeout(r, 0)); // let a fire-and-forget update check land if one started
+ expect(calls).toEqual({ update: 0, policy: 0, helpers: 0, proven: 0, daemon: 0 });
+ expect(JSON.parse(out.join('')).hookSpecificOutput.additionalContext).toBe('harness │ idle');
+ });
+
+ it('control: an ordinary command still gets the startup side effects', async () => {
+ const cli = new CLI({ interactive: false });
+ (cli as unknown as { parser: { registerCommand(c: unknown): void } }).parser.registerCommand({
+ name: 'noop-3521', description: 'test', action: async () => ({ success: true }),
+ });
+ await cli.run(['noop-3521']);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(calls).toEqual({ update: 1, policy: 1, helpers: 1, proven: 1, daemon: 1 });
+ });
+
+ it('only harness is observe-only', () => {
+ expect(isObserveOnlyCommand('harness')).toBe(true);
+ expect(isObserveOnlyCommand('status')).toBe(false);
+ expect(isObserveOnlyCommand(undefined)).toBe(false);
+ });
+});
+
+describe('runHarnessCli', () => {
+ it('--hook swallows probe errors and prints nothing', () => {
+ const written: string[] = [];
+ const code = runHarnessCli(['--hook'], (t) => written.push(t), () => { throw new Error('boom'); });
+ expect(code).toBe(0);
+ expect(written).toEqual([]);
+ });
+});
+
+describe('opt-in Codex hook', () => {
+ it('points at this install, disables autostart and updates, and stays quiet', () => {
+ const cfg = JSON.parse(codexHookConfig("/opt/it's here/bin/cli.js"));
+ const hook = cfg.hooks.SessionStart[0].hooks[0];
+ expect(hook.command).toBe(`RUFLO_DAEMON_AUTOSTART=0 node '/opt/it'\\''s here/bin/cli.js' harness --hook --no-update 2>/dev/null || true`);
+ expect(hook.command).not.toContain('git rev-parse');
+ expect(hook.timeout).toBe(8);
+ });
+});
+
+describe('bin/cli.js harness fast path', () => {
+ function stage(withDist: boolean): { root: string; bin: string } {
+ const root = mkdtempSync(join(tmpdir(), 'harness-bin-'));
+ mkdirSync(join(root, 'bin'));
+ copyFileSync(join(CLI_DIR, 'bin', 'cli.js'), join(root, 'bin', 'cli.js'));
+ writeFileSync(join(root, 'package.json'), '{"type":"module","version":"0.0.0"}');
+ if (withDist) {
+ mkdirSync(join(root, 'dist', 'src', 'commands'), { recursive: true });
+ // index.js would throw if bin/cli.js fell through to the normal CLI.
+ writeFileSync(join(root, 'dist', 'src', 'index.js'), 'throw new Error("normal CLI startup ran");\n');
+ writeFileSync(
+ join(root, 'dist', 'src', 'commands', 'harness.js'),
+ 'export function runHarnessCli(argv) { process.stdout.write(JSON.stringify({ argv }) + "\\n"); return 0; }\n',
+ );
+ }
+ return { root, bin: join(root, 'bin', 'cli.js') };
+ }
+
+ it('dispatches to runHarnessCli without loading the CLI class', () => {
+ const { bin } = stage(true);
+ const stdout = execFileSync(process.execPath, [bin, 'harness', '--hook', '--no-update'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ expect(JSON.parse(stdout)).toEqual({ argv: ['--hook', '--no-update'] });
+ });
+
+ it('--hook with dist/ missing: exit 0, no stdout, no stderr stack', () => {
+ const { bin } = stage(false);
+ const r = spawnSync(process.execPath, [bin, 'harness', '--hook'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ expect(r.status).toBe(0);
+ expect(r.stdout).toBe('');
+ expect(r.stderr).toBe('');
+ });
+
+ it('without --hook and dist/ missing: one-line error, exit 1', () => {
+ const { bin } = stage(false);
+ const r = spawnSync(process.execPath, [bin, 'harness'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ expect(r.status).toBe(1);
+ expect(r.stderr.trim()).toBe('ruflo harness: the CLI is not built (dist/ is missing)');
+ });
+
+ it('writes nothing to the working directory', () => {
+ const { bin } = stage(true);
+ const cwd = mkdtempSync(join(tmpdir(), 'harness-cwd-'));
+ mkdirSync(join(cwd, '.claude-flow'));
+ writeFileSync(join(cwd, '.claude-flow', 'config.json'), '{}');
+ execFileSync(process.execPath, [bin, 'harness', '--hook'], { cwd, stdio: 'ignore' });
+ expect(readdirSync(cwd).sort()).toEqual(['.claude-flow']);
+ expect(readdirSync(join(cwd, '.claude-flow'))).toEqual(['config.json']);
+ });
+});
diff --git a/v3/@claude-flow/cli/bin/cli.js b/v3/@claude-flow/cli/bin/cli.js
index 7dad89f160..70cb291bb9 100755
--- a/v3/@claude-flow/cli/bin/cli.js
+++ b/v3/@claude-flow/cli/bin/cli.js
@@ -161,7 +161,25 @@ const isMCPMode = !process.stdin.isTTY
&& !explicitNonStdioTransport
&& (process.argv.length === 2 || isExplicitMCP);
-if (isMCPMode) {
+// `harness` observes the running system (it is the SessionStart hook), so it
+// skips normal CLI startup entirely: no daemon autostart, update check, policy
+// migration or config adoption, and no heavy imports. With --hook it fails
+// silently (no stack on stderr) so a missing dist/ can't disturb a session.
+const isHarness = cliArgs[0] === 'harness' && !cliArgs.includes('--help') && !cliArgs.includes('-h');
+
+if (isHarness) {
+ const hook = cliArgs.includes('--hook');
+ try {
+ const { runHarnessCli } = await import('../dist/src/commands/harness.js');
+ process.exitCode = runHarnessCli(cliArgs.slice(1));
+ } catch (error) {
+ if (!hook) {
+ const missing = error && error.code === 'ERR_MODULE_NOT_FOUND';
+ console.error(`ruflo harness: ${missing ? 'the CLI is not built (dist/ is missing)' : (error && error.message) || error}`);
+ }
+ process.exitCode = hook ? 0 : 1;
+ }
+} else if (isMCPMode) {
// Run MCP server mode
const { listMCPTools, callMCPTool, hasTool } = await import('../dist/src/mcp-client.js');
const { isPolicyEnforcementEnabled, loadMcpPolicy, evaluateToolCall } =
diff --git a/v3/@claude-flow/cli/src/commands/harness.ts b/v3/@claude-flow/cli/src/commands/harness.ts
new file mode 100644
index 0000000000..5da137fb7e
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/harness.ts
@@ -0,0 +1,149 @@
+/**
+ * Live harness status.
+ *
+ * This is not `doctor` and not `status`. Those describe install health or
+ * call tool handlers inside this process. `harness` reports what is already
+ * running for this working tree: the host session, a live daemon pid, ruflo
+ * MCP servers whose cwd is this tree, processes holding the memory databases
+ * open, and teams that are still active.
+ *
+ * ruflo harness
+ * ruflo harness --json
+ * ruflo harness --hook # SessionStart payload for Codex (and Claude)
+ * ruflo harness --print-codex-hook # opt-in .codex/hooks.json for this install
+ *
+ * `harness` is observe-only: bin/cli.js runs it through `runHarnessCli`
+ * before the normal CLI starts, so no daemon autostart, update check, policy
+ * migration or config adoption runs, and nothing is written to disk. The CLI
+ * class also exempts it from those side effects (see OBSERVE_ONLY_COMMANDS).
+ */
+
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { collectLiveHarness, type LiveHarness } from '../services/live-harness.js';
+
+export type { LiveHarness } from '../services/live-harness.js';
+export { collectLiveHarness } from '../services/live-harness.js';
+
+type Mode = 'text' | 'json' | 'hook' | 'codex-hook';
+
+function renderText(report: LiveHarness): string {
+ const out = [report.line];
+ if (Object.keys(report.session).length) {
+ out.push(`session ${Object.entries(report.session).map(([k, v]) => `${k}=${v}`).join(' ')}`);
+ }
+ for (const server of report.mcp.servers) out.push(`mcp ${server.pid} ${server.command}`);
+ if (report.memory.openPids?.length) out.push(`memory held by ${report.memory.openPids.join(',')}`);
+ for (const team of report.teams) out.push(`team ${team.name} ${team.status} members=${team.members}`);
+ if (report.staleTeams.length) out.push(`stale teams (no activity, not shut down) ${report.staleTeams.join(',')}`);
+ return out.join('\n') + '\n';
+}
+
+function renderHook(report: LiveHarness): string {
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: report.line },
+ }) + '\n';
+}
+
+function shellQuote(value: string): string {
+ return `'${value.replace(/'/g, `'\\''`)}'`;
+}
+
+/** This install's bin/cli.js, from dist/src/commands/harness.js (or src/commands). */
+export function installedCliPath(moduleUrl: string = import.meta.url): string {
+ return join(dirname(fileURLToPath(moduleUrl)), '..', '..', '..', 'bin', 'cli.js');
+}
+
+/**
+ * A .codex/hooks.json that runs this install's harness on SessionStart. The
+ * path is absolute, so the hook does not depend on the session's git root.
+ * Autostart and the update check are off, and failures stay silent.
+ */
+export function codexHookConfig(cliPath: string = installedCliPath()): string {
+ const command = `RUFLO_DAEMON_AUTOSTART=0 node ${shellQuote(cliPath)} harness --hook --no-update 2>/dev/null || true`;
+ return JSON.stringify({
+ hooks: {
+ SessionStart: [
+ {
+ matcher: 'startup|resume|clear|compact|fork',
+ hooks: [{ type: 'command', command, timeout: 8 }],
+ },
+ ],
+ },
+ }, null, 2) + '\n';
+}
+
+function render(mode: Mode, collect: () => LiveHarness): { text: string; report?: LiveHarness } {
+ if (mode === 'codex-hook') return { text: codexHookConfig() };
+ const report = collect();
+ if (mode === 'hook') return { text: renderHook(report), report };
+ if (mode === 'json') return { text: JSON.stringify(report, null, 2) + '\n', report };
+ return { text: renderText(report), report };
+}
+
+function modeOf(flags: { hook?: unknown; json?: unknown; printCodexHook?: unknown }): Mode {
+ if (flags.printCodexHook) return 'codex-hook';
+ if (flags.hook) return 'hook';
+ if (flags.json) return 'json';
+ return 'text';
+}
+
+/**
+ * Entry used by bin/cli.js before the CLI class loads. Returns the exit code.
+ * With --hook it never fails: on any error it prints nothing and returns 0,
+ * so a SessionStart hook can't break a session.
+ */
+export function runHarnessCli(
+ argv: string[],
+ write: (text: string) => void = (text) => { process.stdout.write(text); },
+ collect: () => LiveHarness = () => collectLiveHarness(),
+): number {
+ const mode = modeOf({
+ hook: argv.includes('--hook'),
+ json: argv.includes('--json'),
+ printCodexHook: argv.includes('--print-codex-hook'),
+ });
+ try {
+ write(render(mode, collect).text);
+ return 0;
+ } catch (error) {
+ if (mode === 'hook') return 0;
+ process.stderr.write(`ruflo harness: ${error instanceof Error ? error.message : String(error)}\n`);
+ return 1;
+ }
+}
+
+export const harnessCommand: Command = {
+ name: 'harness',
+ description: 'Show the running harness for this tree (live pids and open state, not install config)',
+ options: [
+ { name: 'json', description: 'Print the live report as JSON', type: 'boolean', default: false },
+ {
+ name: 'hook',
+ description: 'Print a SessionStart additionalContext payload for Codex or Claude',
+ type: 'boolean',
+ default: false,
+ },
+ {
+ name: 'print-codex-hook',
+ description: 'Print an opt-in .codex/hooks.json that runs this install on SessionStart',
+ type: 'boolean',
+ default: false,
+ },
+ ],
+ examples: [
+ { command: 'ruflo harness', description: 'One line plus any live mcp, memory holders, and teams' },
+ { command: 'ruflo harness --json', description: 'Machine-readable live report' },
+ { command: 'ruflo harness --hook', description: 'SessionStart payload' },
+ { command: 'ruflo harness --print-codex-hook > .codex/hooks.json', description: 'Opt in to the Codex SessionStart hook' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const mode = modeOf(ctx.flags as Record<string, unknown>);
+ const { text, report } = render(mode, () => collectLiveHarness());
+ process.stdout.write(text);
+ return { success: true, data: report };
+ },
+};
+
+export default harnessCommand;
diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.ts
index aa375c3a07..73b6917912 100644
--- a/v3/@claude-flow/cli/src/commands/index.ts
+++ b/v3/@claude-flow/cli/src/commands/index.ts
@@ -54,6 +54,7 @@ const commandLoaders: Record<string, CommandLoader> = {
// P0 Commands
completions: () => import('./completions.js'),
doctor: () => import('./doctor.js'),
+ harness: () => import('./harness.js'),
// Verification (ADR-095, signed witness manifest)
verify: () => import('./verify.js'),
// Analysis Commands
diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.ts
index b36789b2f8..857da6c5ff 100644
--- a/v3/@claude-flow/cli/src/index.ts
+++ b/v3/@claude-flow/cli/src/index.ts
@@ -41,6 +41,13 @@ function getPackageVersion(): string {
export const VERSION = getPackageVersion();
+/** Commands that only observe the running system and must not start or write anything. */
+export const OBSERVE_ONLY_COMMANDS: ReadonlySet<string> = new Set(['harness']);
+
+export function isObserveOnlyCommand(name: string | undefined): boolean {
+ return name !== undefined && OBSERVE_ONLY_COMMANDS.has(name);
+}
+
export interface CLIOptions {
name?: string;
description?: string;
@@ -132,8 +139,14 @@ export class CLI {
this.output.printDebug(`CWD: ${process.cwd()}`);
}
+ // Observe-only commands (e.g. `harness`, run from SessionStart hooks)
+ // report on the running system, so they must not change it: no update
+ // check, no policy migration, no helper refresh, no proven-config
+ // adoption, no daemon autostart.
+ const observeOnly = isObserveOnlyCommand(commandPath[0] ?? positional[0]);
+
// Run startup update check (non-blocking, silent on skip)
- if (!flags.noUpdate && flags.update !== false && commandPath[0] !== 'update' && !(commandPath[0] === 'doctor' && flags.json)) {
+ if (!flags.noUpdate && flags.update !== false && commandPath[0] !== 'update' && !(commandPath[0] === 'doctor' && flags.json) && !observeOnly) {
this.checkForUpdatesOnStartup().catch(() => {/* silent */});
}
@@ -143,7 +156,7 @@ export class CLI {
// command can't exit before the copy lands; the fast path is a single
// stamp read + string compare (sub-ms), and the copy runs at most once per
// version bump. Best-effort + silent — never blocks or fails a command.
- if (commandPath[0] !== 'init' && commandPath[0] !== 'update') {
+ if (commandPath[0] !== 'init' && commandPath[0] !== 'update' && !observeOnly) {
// ADR-324: existing installations acquire a versioned policy state on
// first use. Migration is additive and starts in legacy mode, so older
// AgentDB, MCP, hooks, and swarm workflows keep their exact behavior.
diff --git a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts
index fb019e0033..398dfcdf71 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts
@@ -124,7 +124,7 @@ export const RUFLO_CLI_COMMANDS = [
'ruvector', 'benchmark', 'guidance', 'appliance', 'appliance-advanced',
'transfer-store', 'cleanup', 'autopilot', 'gaia-bench', 'metaharness',
'eject', 'funnel', 'settings', 'auth', 'proxy', 'advisor', 'spinner',
- 'announcements', 'tui',
+ 'announcements', 'tui', 'harness',
] as const;
export interface ImplementationLoopStep {
diff --git a/v3/@claude-flow/cli/src/services/live-harness.ts b/v3/@claude-flow/cli/src/services/live-harness.ts
new file mode 100644
index 0000000000..0908ca5fe3
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/live-harness.ts
@@ -0,0 +1,491 @@
+/**
+ * Live harness probe.
+ *
+ * Reports what is already running for a working tree: the host session, a
+ * live daemon pid, ruflo MCP servers whose cwd is inside the tree, processes
+ * holding the memory databases open, and teams that are still active.
+ *
+ * The probe is observe-only. It never writes to disk, never starts anything,
+ * and never touches the network. It spawns at most one `ps` and two `lsof`
+ * calls, all under one overall deadline, and says "unavailable" instead of
+ * guessing when those tools are missing (Windows, minimal Linux).
+ *
+ * All OS access goes through `HarnessSys` so the probe can be tested without
+ * real processes.
+ */
+
+import { spawnSync } from 'node:child_process';
+import { existsSync, readdirSync, readFileSync, readlinkSync, realpathSync, statSync } from 'node:fs';
+import { basename, dirname, join, sep } from 'node:path';
+
+export type ProbeState = 'ok' | 'unavailable' | 'timeout';
+
+export interface RunResult {
+ stdout: string;
+ state: ProbeState;
+ status: number | null;
+}
+
+export interface HarnessSys {
+ platform: NodeJS.Platform;
+ env: NodeJS.ProcessEnv;
+ pid: number;
+ ppid: number;
+ cwd(): string;
+ now(): number;
+ run(cmd: string, args: string[], timeoutMs: number): RunResult;
+ signal0(pid: number): 'alive' | 'dead' | 'eperm';
+ exists(path: string): boolean;
+ readFile(path: string): string;
+ readDir(path: string): Array<{ name: string; isDir: boolean }>;
+ mtimeMs(path: string): number | undefined;
+ realpath(path: string): string;
+ readlink(path: string): string | undefined;
+}
+
+export interface ProcRow {
+ pid: number;
+ ppid: number;
+ argv: string[];
+}
+
+export interface LiveHarness {
+ root: string;
+ host: string;
+ parent: { pid: number; name: string };
+ session: Record<string, string>;
+ daemon: { state: 'live' | 'down' | 'stale'; pid?: number; verified?: boolean; reason?: string };
+ mcp: { count: number | null; servers: Array<{ pid: number; command: string }> };
+ memory: { files: string[]; openPids: number[] | null };
+ teams: Array<{ name: string; status: string; members: number; lastActivity?: string }>;
+ staleTeams: string[];
+ probes: { ps: ProbeState; lsof: ProbeState };
+ status: 'live' | 'idle' | 'unknown';
+ elapsedMs: number;
+ line: string;
+}
+
+export interface CollectOptions {
+ root?: string;
+ budgetMs?: number;
+ teamTtlMs?: number;
+}
+
+const DEFAULT_BUDGET_MS = 4000;
+const PER_CALL_CAP_MS = 1500;
+const MIN_CALL_MS = 100;
+const DEFAULT_TEAM_TTL_MS = 30 * 60 * 1000;
+const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'fish', 'ksh', 'tcsh', 'csh', 'env', 'timeout', 'npm', 'npx', 'pnpm', 'script']);
+const INTERPRETERS = new Set(['node', 'nodejs', 'bun', 'deno']);
+const MCP_LAUNCHERS = new Set(['node', 'nodejs', 'bun', 'deno', 'npx', 'npm', 'pnpm', 'pnpx', 'yarn', 'ruflo', 'claude-flow']);
+const RUFLO_ID = /(^|\/)(ruflo|claude-flow)(@[\w.-]+)?$|(^|\/)@claude-flow\/cli(@[\w.-]+)?$|\/@claude-flow\/cli\/bin\/cli\.js$|\/ruflo\/bin\/[\w.-]+\.js$/;
+const TEAM_ENDED = new Set(['shutdown', 'stopped']);
+
+export const realSys: HarnessSys = {
+ platform: process.platform,
+ env: process.env,
+ pid: process.pid,
+ ppid: process.ppid,
+ cwd: () => process.cwd(),
+ now: () => Date.now(),
+ run(cmd, args, timeoutMs) {
+ const r = spawnSync(cmd, args, {
+ encoding: 'utf8',
+ timeout: timeoutMs,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ maxBuffer: 16 * 1024 * 1024,
+ windowsHide: true,
+ });
+ const code = (r.error as NodeJS.ErrnoException | undefined)?.code;
+ if (code === 'ETIMEDOUT') return { stdout: r.stdout ?? '', state: 'timeout', status: r.status };
+ if (r.error) return { stdout: '', state: 'unavailable', status: r.status };
+ return { stdout: r.stdout ?? '', state: 'ok', status: r.status };
+ },
+ signal0(pid) {
+ try {
+ process.kill(pid, 0);
+ return 'alive';
+ } catch (error) {
+ // EPERM: the pid exists but belongs to another user.
+ return (error as NodeJS.ErrnoException).code === 'EPERM' ? 'eperm' : 'dead';
+ }
+ },
+ exists: (path) => existsSync(path),
+ readFile: (path) => readFileSync(path, 'utf8'),
+ readDir: (path) => readdirSync(path, { withFileTypes: true }).map((d) => ({ name: d.name, isDir: d.isDirectory() })),
+ mtimeMs(path) {
+ try {
+ return statSync(path).mtimeMs;
+ } catch {
+ return undefined;
+ }
+ },
+ realpath(path) {
+ try {
+ return realpathSync(path);
+ } catch {
+ return path;
+ }
+ },
+ readlink(path) {
+ try {
+ return readlinkSync(path);
+ } catch {
+ return undefined;
+ }
+ },
+};
+
+/** Overall deadline shared by every external call. */
+class Budget {
+ private readonly end: number;
+ constructor(private readonly sys: HarnessSys, totalMs: number) {
+ this.end = sys.now() + totalMs;
+ }
+ run(cmd: string, args: string[]): RunResult {
+ const left = this.end - this.sys.now();
+ if (left < MIN_CALL_MS) return { stdout: '', state: 'timeout', status: null };
+ return this.sys.run(cmd, args, Math.min(PER_CALL_CAP_MS, left));
+ }
+}
+
+/** The host's project dir if it says so, else the nearest `.git` above cwd, else cwd. */
+export function findWorkspaceRoot(sys: HarnessSys): string {
+ const fromEnv = sys.env.GROK_WORKSPACE_ROOT || sys.env.CLAUDE_PROJECT_DIR || sys.env.CODEX_PROJECT_DIR;
+ if (fromEnv) return fromEnv;
+ const start = sys.cwd();
+ let dir = start;
+ for (;;) {
+ if (sys.exists(join(dir, '.git'))) return dir;
+ const parent = dirname(dir);
+ if (parent === dir) return start;
+ dir = parent;
+ }
+}
+
+/** True when `path` is one of `roots` or lies inside one on a path boundary. */
+export function insideRoot(path: string, roots: string[]): boolean {
+ return roots.some((root) => {
+ const base = root.length > 1 && root.endsWith(sep) ? root.slice(0, -1) : root;
+ return path === base || path.startsWith(base + sep);
+ });
+}
+
+export function parsePs(stdout: string): ProcRow[] {
+ const rows: ProcRow[] = [];
+ for (const line of stdout.split('\n')) {
+ const m = /^\s*(\d+)\s+(\d+)\s+(.*\S)\s*$/.exec(line);
+ if (m) rows.push({ pid: Number(m[1]), ppid: Number(m[2]), argv: m[3].split(/\s+/) });
+ }
+ return rows;
+}
+
+/** Name a process by its program, looking past node/bun to the script. */
+export function programName(argv: string[]): string {
+ const first = basename(argv[0] ?? '').replace(/^-/, '');
+ if (INTERPRETERS.has(first) && argv[1] && !argv[1].startsWith('-')) {
+ return basename(argv[1]).replace(/\.(c|m)?js$/, '');
+ }
+ return first;
+}
+
+/** A ruflo MCP server: a launcher, a ruflo identity token, then `mcp [start]`. */
+export function isRufloMcp(argv: string[]): boolean {
+ if (!MCP_LAUNCHERS.has(basename(argv[0] ?? ''))) return false;
+ const at = argv.indexOf('mcp');
+ if (at < 0) return false;
+ const next = argv[at + 1];
+ if (next !== undefined && next !== 'start' && !next.startsWith('-')) return false;
+ return argv.slice(0, at).some((token) => RUFLO_ID.test(token));
+}
+
+/** Program name and subcommand words only; every argument is dropped and counted. */
+export function redactCommand(argv: string[]): string {
+ const words = [programName(argv), 'mcp'];
+ const at = argv.indexOf('mcp');
+ if (argv[at + 1] === 'start') words.push('start');
+ const kept = at + words.length - 1;
+ const dropped = Math.max(0, argv.length - kept);
+ return dropped > 0 ? `${words.join(' ')} (+${dropped} args)` : words.join(' ');
+}
+
+export function detectHost(
+ sys: HarnessSys,
+ table: Map<number, ProcRow> | null,
+): { host: string; parent: { pid: number; name: string } } {
+ const env = sys.env;
+ let parent = { pid: sys.ppid, name: '' };
+ const names: string[] = [];
+ if (table) {
+ // Hooks usually run under `sh -c`; walk past shells and wrappers.
+ let pid = sys.ppid;
+ for (let depth = 0; depth < 8 && pid > 1; depth++) {
+ const row = table.get(pid);
+ if (!row) break;
+ const name = programName(row.argv);
+ if (!SHELLS.has(name)) {
+ if (!parent.name) parent = { pid, name };
+ names.push(name);
+ }
+ pid = row.ppid;
+ }
+ }
+ const seen = (re: RegExp) => names.some((n) => re.test(n));
+ let host: string;
+ if (env.WEFTOS_SESSION || env.WEFT_SESSION || seen(/^weftos/i)) host = 'weftos';
+ else if (env.GROK_SESSION_ID || env.GROK_WORKSPACE_ROOT || seen(/^grok([-_.]|$)/)) host = 'grok';
+ else if (env.CODEX_THREAD_ID || env.CODEX_SANDBOX || env.CODEX_CI || seen(/^codex([-_.]|$)/)) host = 'codex';
+ else if (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT || seen(/^claude([-_.]|$)/)) host = 'claude';
+ else host = parent.name ? `process:${parent.name}` : 'unknown';
+ return { host, parent };
+}
+
+function sessionIds(env: NodeJS.ProcessEnv): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const key of ['GROK_SESSION_ID', 'CODEX_THREAD_ID', 'CLAUDE_SESSION_ID', 'WEFTOS_SESSION', 'WEFT_SESSION']) {
+ const value = env[key];
+ if (value) out[key] = value;
+ }
+ return out;
+}
+
+function daemonState(
+ sys: HarnessSys,
+ root: string,
+ roots: string[],
+ table: Map<number, ProcRow> | null,
+): LiveHarness['daemon'] {
+ const pidFile = join(root, '.claude-flow', 'daemon.pid');
+ if (!sys.exists(pidFile)) return { state: 'down' };
+ let raw: string;
+ try {
+ raw = sys.readFile(pidFile).trim();
+ } catch {
+ return { state: 'down' };
+ }
+ const pid = Number(raw);
+ if (!Number.isInteger(pid) || pid <= 0) return { state: 'stale', reason: 'bad pidfile' };
+ // EPERM means the pid exists under another user; only ESRCH means gone.
+ if (sys.signal0(pid) === 'dead') return { state: 'stale', pid, reason: 'not running' };
+ const row = table?.get(pid);
+ if (!row) return { state: 'live', pid, verified: false };
+ // The pid is alive; make sure it is still our daemon and not a recycled pid.
+ if (!row.argv.includes('daemon')) return { state: 'stale', pid, reason: 'pid reused' };
+ const ws = row.argv.indexOf('--workspace');
+ const workspace = ws >= 0 ? row.argv[ws + 1] : undefined;
+ if (workspace && !roots.includes(workspace) && !roots.includes(sys.realpath(workspace))) {
+ return { state: 'stale', pid, reason: 'pid belongs to another workspace' };
+ }
+ return { state: 'live', pid, verified: true };
+}
+
+/** cwd for each pid: /proc on Linux, then one batched lsof for the rest. */
+function processCwds(
+ sys: HarnessSys,
+ budget: Budget,
+ pids: number[],
+): { cwds: Map<number, string>; lsof: ProbeState | null } {
+ const cwds = new Map<number, string>();
+ if (sys.platform === 'linux') {
+ for (const pid of pids) {
+ const cwd = sys.readlink(`/proc/${pid}/cwd`);
+ if (cwd) cwds.set(pid, cwd);
+ }
+ }
+ const rest = pids.filter((pid) => !cwds.has(pid));
+ if (rest.length === 0) return { cwds, lsof: null };
+ const r = budget.run('lsof', ['-a', '-d', 'cwd', '-p', rest.join(','), '-Fpn']);
+ let current = 0;
+ for (const line of r.stdout.split('\n')) {
+ if (line.startsWith('p')) current = Number(line.slice(1));
+ else if (line.startsWith('n') && current) cwds.set(current, line.slice(1));
+ }
+ return { cwds, lsof: r.state };
+}
+
+function mcpServers(
+ sys: HarnessSys,
+ budget: Budget,
+ roots: string[],
+ rows: ProcRow[],
+): { mcp: LiveHarness['mcp']; lsof: ProbeState | null } {
+ let candidates = rows.filter((row) => row.pid !== sys.pid && isRufloMcp(row.argv));
+ // `npx ruflo mcp start` forks the real server; count the leaf only.
+ const parents = new Set(candidates.map((row) => row.ppid));
+ candidates = candidates.filter((row) => !parents.has(row.pid));
+ if (candidates.length === 0) return { mcp: { count: 0, servers: [] }, lsof: null };
+ const { cwds, lsof } = processCwds(sys, budget, candidates.map((row) => row.pid));
+ if (lsof !== null && lsof !== 'ok' && cwds.size < candidates.length) {
+ return { mcp: { count: null, servers: [] }, lsof };
+ }
+ const servers = candidates
+ .filter((row) => {
+ const cwd = cwds.get(row.pid);
+ return cwd !== undefined && (insideRoot(cwd, roots) || insideRoot(sys.realpath(cwd), roots));
+ })
+ .map((row) => ({ pid: row.pid, command: redactCommand(row.argv) }));
+ return { mcp: { count: servers.length, servers }, lsof };
+}
+
+function memoryHolders(
+ sys: HarnessSys,
+ budget: Budget,
+ root: string,
+): { memory: LiveHarness['memory']; lsof: ProbeState | null } {
+ // memory.db is the sql.js writer; agentdb-memory.db is the native AgentDB store.
+ const files: string[] = [];
+ for (const db of ['memory.db', 'agentdb-memory.db']) {
+ for (const suffix of ['', '-wal', '-shm']) {
+ const path = join(root, '.swarm', db + suffix);
+ if (sys.exists(path)) files.push(path);
+ }
+ }
+ if (files.length === 0) return { memory: { files, openPids: [] }, lsof: null };
+ if (sys.platform === 'win32') return { memory: { files, openPids: null }, lsof: 'unavailable' };
+ const r = budget.run('lsof', ['-t', '--', ...files]);
+ if (r.state !== 'ok') return { memory: { files, openPids: null }, lsof: r.state };
+ const pids = r.stdout
+ .split('\n')
+ .map((row) => Number(row.trim()))
+ .filter((pid) => pid > 0 && pid !== sys.pid);
+ return { memory: { files, openPids: [...new Set(pids)] }, lsof: 'ok' };
+}
+
+interface TeamFile {
+ name?: string;
+ status?: string;
+ shutdownAt?: string;
+ createdAt?: string;
+ updatedAt?: string;
+ members?: Record<string, { pid?: number; registeredAt?: string; lastStopAt?: string; lastSeenAt?: string }>;
+ plan?: { updatedAt?: string };
+}
+
+function lastActivity(sys: HarnessSys, file: string, team: TeamFile): number {
+ const stamps = [team.createdAt, team.updatedAt, team.plan?.updatedAt];
+ for (const member of Object.values(team.members ?? {})) {
+ stamps.push(member?.registeredAt, member?.lastStopAt, member?.lastSeenAt);
+ }
+ const times = stamps.map((s) => (s ? Date.parse(s) : NaN)).filter((t) => Number.isFinite(t));
+ return Math.max(sys.mtimeMs(file) ?? 0, ...times, 0);
+}
+
+/**
+ * Teams under .claude-flow/teams: `<name>/team.json` (the team bus layout)
+ * and the legacy flat `<name>.json`. A team counts as live only if it has not
+ * shut down AND shows activity within the TTL or has a member pid running.
+ */
+function teamsIn(sys: HarnessSys, root: string, ttlMs: number): { live: LiveHarness['teams']; stale: string[] } {
+ const dir = join(root, '.claude-flow', 'teams');
+ const live: LiveHarness['teams'] = [];
+ const stale: string[] = [];
+ if (!sys.exists(dir)) return { live, stale };
+ let entries: Array<{ name: string; isDir: boolean }>;
+ try {
+ entries = sys.readDir(dir);
+ } catch {
+ return { live, stale };
+ }
+ for (const entry of entries) {
+ const file = entry.isDir
+ ? join(dir, entry.name, 'team.json')
+ : entry.name.endsWith('.json') ? join(dir, entry.name) : '';
+ if (!file || !sys.exists(file)) continue;
+ let team: TeamFile;
+ try {
+ team = JSON.parse(sys.readFile(file)) as TeamFile;
+ } catch {
+ continue; // an unreadable team file is not a live team
+ }
+ if (!team || typeof team !== 'object') continue;
+ if (team.shutdownAt || TEAM_ENDED.has(String(team.status))) continue;
+ const name = team.name || entry.name.replace(/\.json$/, '');
+ const last = lastActivity(sys, file, team);
+ const pidAlive = Object.values(team.members ?? {}).some(
+ (m) => Number.isInteger(m?.pid) && (m.pid as number) > 0 && sys.signal0(m.pid as number) !== 'dead',
+ );
+ if (!pidAlive && sys.now() - last > ttlMs) {
+ stale.push(name);
+ continue;
+ }
+ live.push({
+ name,
+ status: team.status || 'unknown',
+ members: team.members ? Object.keys(team.members).length : 0,
+ lastActivity: last ? new Date(last).toISOString() : undefined,
+ });
+ }
+ return { live, stale };
+}
+
+function worst(...states: Array<ProbeState | null>): ProbeState {
+ const rank: Record<ProbeState, number> = { ok: 0, timeout: 1, unavailable: 2 };
+ return states.reduce<ProbeState>((acc, s) => (s !== null && rank[s] > rank[acc] ? s : acc), 'ok');
+}
+
+function teamTtl(sys: HarnessSys, fallback: number): number {
+ const secs = Number(sys.env.RUFLO_HARNESS_TEAM_TTL_SECS);
+ return Number.isFinite(secs) && secs > 0 ? secs * 1000 : fallback;
+}
+
+export function collectLiveHarness(sys: HarnessSys = realSys, opts: CollectOptions = {}): LiveHarness {
+ const start = sys.now();
+ const budget = new Budget(sys, opts.budgetMs ?? DEFAULT_BUDGET_MS);
+ const root = opts.root ?? findWorkspaceRoot(sys);
+ // Both spellings of the root, so macOS /tmp and /private/tmp compare equal.
+ const roots = [...new Set([root, sys.realpath(root)])];
+
+ let ps: ProbeState = 'unavailable';
+ let rows: ProcRow[] = [];
+ if (sys.platform !== 'win32') {
+ const r = budget.run('ps', ['-ax', '-o', 'pid=,ppid=,command=']);
+ rows = r.state === 'ok' ? parsePs(r.stdout) : [];
+ // busybox ps rejects -ax: "ran but listed nothing" is unavailable, not idle.
+ ps = r.state === 'ok' && rows.length === 0 ? 'unavailable' : r.state;
+ }
+ const table = ps === 'ok' ? new Map(rows.map((row) => [row.pid, row])) : null;
+
+ const { host, parent } = detectHost(sys, table);
+ const daemon = daemonState(sys, root, roots, table);
+ const mcpProbe = ps === 'ok'
+ ? mcpServers(sys, budget, roots, rows)
+ : { mcp: { count: null, servers: [] } as LiveHarness['mcp'], lsof: null };
+ const memProbe = memoryHolders(sys, budget, root);
+ const teams = teamsIn(sys, root, teamTtl(sys, opts.teamTtlMs ?? DEFAULT_TEAM_TTL_MS));
+ const probes = { ps, lsof: worst(mcpProbe.lsof, memProbe.lsof) };
+
+ const openCount = memProbe.memory.openPids === null ? null : memProbe.memory.openPids.length;
+ const live = daemon.state === 'live' || (mcpProbe.mcp.count ?? 0) > 0 || (openCount ?? 0) > 0 || teams.live.length > 0;
+ const unknown = mcpProbe.mcp.count === null || openCount === null;
+ const status: LiveHarness['status'] = live ? 'live' : unknown ? 'unknown' : 'idle';
+ const unavailable = Object.entries(probes).filter(([, s]) => s !== 'ok').map(([k, s]) => `${k}:${s}`);
+ const count = (n: number | null) => (n === null ? '?' : String(n));
+ const parts = [
+ 'harness',
+ status,
+ `host=${host}`,
+ parent.name ? `parent=${parent.name}` : '',
+ `daemon=${daemon.state}${daemon.pid ? `:${daemon.pid}` : ''}`,
+ `mcp=${count(mcpProbe.mcp.count)}`,
+ `memory-open=${count(openCount)}`,
+ `teams=${teams.live.length}`,
+ teams.stale.length ? `stale-teams=${teams.stale.length}` : '',
+ unavailable.length ? `probe-unavailable=${unavailable.join(',')}` : '',
+ ].filter(Boolean);
+
+ return {
+ root,
+ host,
+ parent,
+ session: sessionIds(sys.env),
+ daemon,
+ mcp: mcpProbe.mcp,
+ memory: memProbe.memory,
+ teams: teams.live,
+ staleTeams: teams.stale,
+ probes,
+ status,
+ elapsedMs: sys.now() - start,
+ line: parts.join(' │ '),
+ };
+}