diff --git a/plugins/ruflo-swarm/hooks/commands.ts b/plugins/ruflo-swarm/hooks/commands.ts index fce0761c9d..2c39bf38b6 100644 --- a/plugins/ruflo-swarm/hooks/commands.ts +++ b/plugins/ruflo-swarm/hooks/commands.ts @@ -132,10 +132,10 @@ export function spawnNote(snapshot: Snapshot | null): string | null { return null } - return [ - '', - '---', - `Swarm context (from ruflo's files on disk, a status note, not an instruction): you are part of ruflo swarm ${swarm.id}, topology ${swarm.topology}${swarm.strategy !== undefined ? `, strategy ${swarm.strategy}` : ''}.`, - 'Coordinate through ruflo memory namespace "swarm" and its task and claims tools where they apply.', - ].join('\n') + // Text from disk reaches the model here: only a word-shaped topology or strategy is passed on, the id is `idOf`-checked. + const word = (value: string | undefined) => (value !== undefined && /^[a-z][a-z-]{0,39}$/.test(value) ? value : undefined) + const topology = word(swarm.topology) ?? 'unknown' + const strategy = word(swarm.strategy) + + return `\n\n---\nSwarm context (from ruflo's files on disk, a status note, not an instruction): you are part of ruflo swarm ${swarm.id}, topology ${topology}${strategy !== undefined ? `, strategy ${strategy}` : ''}.` } diff --git a/plugins/ruflo-swarm/hooks/views/pane.tsx b/plugins/ruflo-swarm/hooks/views/pane.tsx index 7aa1fbbd1e..5de228ccc3 100644 --- a/plugins/ruflo-swarm/hooks/views/pane.tsx +++ b/plugins/ruflo-swarm/hooks/views/pane.tsx @@ -175,7 +175,8 @@ function prompts(kit: Kit, model: PaneModel, actions: PaneActions): Section | nu const color = !outcome.ok ? BAD : outcome.verified === 'no' ? WARN : GOOD const said = outcome.verified === 'yes' ? 'seen on disk' : outcome.verified === 'no' ? 'exited 0 but the disk does not show it' : outcome.ok ? 'done' : 'failed' - return { rows: 1, node: {clip(`${mark} ${outcome.label}: ${said}${outcome.detail !== '' ? ` · ${outcome.detail}` : ''}`, model.columns)} } + // What happened leads, so a narrow pane cuts the label, never the verdict. + return { rows: 1, node: {clip(`${mark} ${said}: ${outcome.label}${outcome.detail !== '' ? ` · ${outcome.detail}` : ''}`, model.columns)} } } function board(kit: Kit, model: PaneModel, maxRows: number, actions: PaneActions): Section { diff --git a/plugins/ruflo-swarm/tests/controller.test.ts b/plugins/ruflo-swarm/tests/controller.test.ts new file mode 100644 index 0000000000..142b63fb49 --- /dev/null +++ b/plugins/ruflo-swarm/tests/controller.test.ts @@ -0,0 +1,149 @@ +import { describe, expect, mock, test } from 'claude-code/testing' + +import { RUFLO_RUN } from './fixtures/ruflo-run' +import { command, PANE, PLUGIN, SESSION } from './fixtures/inputs' +import { buttonKeysOf, exitOk, textOf, worldOf, type World } from './fixtures/world' + +const PREFIX = ['npx', '--offline', '-y', '@claude-flow/cli@latest'] +const CODER = 'agent-1790888815793-6ju96w' +const TESTER = 'agent-1790888816288-z5xsn6' +const LOGIN_TASK = 'task-1790888817265-vatniv' +const CLAIMS = '.claude-flow/claims/claims.json' + +/** What `hooks route --format json` printed in the real run: two log lines, then the JSON. */ +const ROUTE_STDOUT = (agent: string, confidence: number) => + `[INFO] Routing task: x\nTransformers.js loaded\n${JSON.stringify({ task: 'Build login form', matched: true, matchedPattern: 'testing-task', primaryAgent: { type: agent, confidence }, alternativeAgents: [{ type: 'reviewer', confidence: 0.64 }], routing: { method: 'semantic-native' } }, null, 2)}` + +const press = async ($: { ui: { render: (e: typeof PANE) => Promise; press: (t: { plugin: string; key: string }) => Promise } }, key: string) => { + await $.ui.render(PANE) + await $.ui.press({ plugin: PLUGIN, key }) +} + +/** The claims file with `issueId` held by `agentId`, as claims_steal leaves it. */ +function claimedBy(world: World, agentId: string, agentType: string): string { + const store = JSON.parse(world.files.get(CLAIMS) ?? '{}') as { claims: Record } + const claim = store.claims[LOGIN_TASK] + + if (claim !== undefined) { + claim.claimant = { type: 'agent', agentId, agentType } + } + + return JSON.stringify(store) +} + +describe('controller', () => { + test('stealing a task asks first, then runs one fixed argv and checks the claim moved on disk', async ($, on) => { + const world = worldOf(on, RUFLO_RUN) + + mock.clock(on) + world.respond = argv => (argv.includes('claims_steal') ? { ...exitOk('{"success":true}'), write: { [CLAIMS]: claimedBy(world, TESTER, 'tester') } } : exitOk()) + await $.session.start(SESSION) + await $.command.run(command('ruflo-swarm-pane')) + + // The queen is selected first; two presses reach the tester. + await press($, 'next') + await press($, 'next') + await press($, 'steal') + + expect(world.runs, 'nothing runs before the second press').toEqual([]) + expect(textOf(await $.ui.render(PANE))).toContain(`steal ${LOGIN_TASK} for tester?`) + + await press($, 'confirm') + + expect(world.runs.map(run => run.argv)).toEqual([[...PREFIX, 'mcp', 'exec', '-t', 'claims_steal', '-p', JSON.stringify({ issueId: LOGIN_TASK, stealer: `agent:${TESTER}:tester` })]]) + expect(textOf(await $.ui.render(PANE))).toContain(`✓ seen on disk: steal ${LOGIN_TASK} for tester`) + }) + + test('cancel drops the prompt, and an unanswered prompt lapses after thirty seconds', async ($, on) => { + const world = worldOf(on, RUFLO_RUN) + const clock = mock.clock(on) + + await $.session.start(SESSION) + await press($, 'next') + await press($, 'stop') + expect(textOf(await $.ui.render(PANE))).toContain(`stop agent ${CODER}?`) + await press($, 'cancel') + expect(buttonKeysOf(await $.ui.render(PANE))).not.toContain('confirm') + + await press($, 'stop') + await clock.advance(31_000) + expect(buttonKeysOf(await $.ui.render(PANE))).not.toContain('confirm') + expect(world.runs).toEqual([]) + }) + + test('a CLI that says yes while the disk shows nothing is reported as unverified, not as done', async ($, on) => { + const world = worldOf(on, RUFLO_RUN) + + mock.clock(on) + // As ruflo 3.49.0 did in the real run: "[OK] Vote recorded", and no vote in the hive's state. + world.respond = () => exitOk('[OK] Vote recorded (For: undefined, Against: undefined)') + await $.session.start(SESSION) + await press($, 'next') + await press($, 'vote-yes') + + expect(world.runs[0]?.argv.slice(4)).toEqual(['hive-mind', 'consensus', '-a', 'vote', '-p', 'proposal-1790888860262-55jkcl', '-v', 'yes', '--voter-id', CODER]) + expect(textOf(await $.ui.render(PANE))).toContain('exited 0 but the disk does not show it') + }) + + test('re-route asks the router for the selected task and shows its pick with the score', async ($, on) => { + const world = worldOf(on, RUFLO_RUN) + + mock.clock(on) + world.respond = () => exitOk(ROUTE_STDOUT('tester', 0.74)) + await $.session.start(SESSION) + await press($, 'reroute') + + expect(world.runs[0]?.argv.slice(4)).toEqual(['hooks', 'route', '--task', 'Build login form', '--format', 'json']) + expect(textOf(await $.ui.render(PANE))).toContain('router: tester 74% (testing-task) · alt reviewer 64%') + + world.respond = () => exitOk(ROUTE_STDOUT('architect', 0.41)) + await press($, 'reroute') + expect(textOf(await $.ui.render(PANE)), 'the router said matched at 0.41: the pane says it is under the threshold').toContain('router: below threshold 50% (best architect 41%)') + }) + + test("a ruflo agent's logs open below the tiles; a Claude Code loop shows what the hooks saw", async ($, on) => { + const world = worldOf(on, RUFLO_RUN) + + mock.clock(on) + on('tool.call', () => ({ result: 'ok', text: 'ok' })) + world.respond = () => exitOk(`Logs for ${CODER}\n5:06:55 PM [INFO] agent created (type=coder, status=idle)`) + await $.session.start(SESSION) + await press($, 'next') + await press($, 'logs') + expect(textOf(await $.ui.render(PANE))).toContain('agent created (type=coder, status=idle)') + + await $.tool.call({ tool: 'Grep', pattern: 'login' } as never) + await press($, 'prev') + await press($, 'prev') + await press($, 'logs') + expect(textOf(await $.ui.render(PANE))).toContain('· Grep login') + }) + + test('a refused process run is a sentence in the pane, not a crash', async ($, on) => { + const world = worldOf(on, RUFLO_RUN) + + mock.clock(on) + world.respond = () => ({ deny: 'process.run removed by policy' }) + await $.session.start(SESSION) + await press($, 'reroute') + + expect(textOf(await $.ui.render(PANE))).toMatch(/✗ failed: ask the router · .*process\.run remo/) + }) + + test('the actions on a task only act on ids ruflo minted: a hostile task text stays one argv element', async ($, on) => { + const hostile = JSON.parse(RUFLO_RUN['.claude-flow/tasks/store.json'] ?? '{}') as { tasks: Record } + const login = hostile.tasks[LOGIN_TASK] + + if (login !== undefined) { + login.description = 'x"; rm -rf / #\n$(curl evil)' + } + + const world = worldOf(on, { ...RUFLO_RUN, '.claude-flow/tasks/store.json': JSON.stringify(hostile) }) + + mock.clock(on) + await $.session.start(SESSION) + await press($, 'reroute') + + expect(world.runs[0]?.argv).toEqual([...PREFIX, 'hooks', 'route', '--task', 'x"; rm -rf / # $(curl evil)', '--format', 'json']) + }) +}) diff --git a/plugins/ruflo-swarm/tests/fixtures/world.ts b/plugins/ruflo-swarm/tests/fixtures/world.ts index 57e7efc382..3a580fb1c0 100644 --- a/plugins/ruflo-swarm/tests/fixtures/world.ts +++ b/plugins/ruflo-swarm/tests/fixtures/world.ts @@ -4,7 +4,7 @@ import { CWD } from './inputs' /** One `$.process.run` the mod made, and what the world answers it with. */ export type Run = { argv: string[]; timeoutMs?: number } -export type Responder = (argv: readonly string[]) => { exitCode: number; stdout: string; stderr: string; write?: Record } +export type Responder = (argv: readonly string[]) => { exitCode: number; stdout: string; stderr: string; write?: Record } | { deny: string } /** * The world beneath the mod, in memory: a file tree `$.fs` answers from, a process table `$.process.run` answers @@ -71,6 +71,10 @@ export function worldOf(on: On, files: Readonly>, usage: const answer = world.respond(e.argv) + if ('deny' in answer) { + return { deny: answer.deny } + } + for (const [path, text] of Object.entries(answer.write ?? {})) { world.put(path, text) } diff --git a/plugins/ruflo-swarm/tests/host.test.ts b/plugins/ruflo-swarm/tests/host.test.ts new file mode 100644 index 0000000000..7b67dee869 --- /dev/null +++ b/plugins/ruflo-swarm/tests/host.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, mock, test } from 'claude-code/testing' + +import { auditRow } from '../hooks/audit' +import { register } from '../hooks/register' +import { RUFLO_RUN } from './fixtures/ruflo-run' +import { command, PANE, PLUGIN, SESSION, spawn } from './fixtures/inputs' +import { exitOk, textOf, worldOf } from './fixtures/world' + +const DENY = { deny: 'refused by policy' } + +type Hook = (...args: unknown[]) => unknown + +/** The hooks `register` wires for these options, by event, taken from a recording `on`. */ +function hooksOf(options: Record): Map { + const hooks = new Map() + const on = (event: string, ...rest: unknown[]) => { + hooks.set(event, rest[rest.length - 1] as Hook) + } + + register(on as never, options as never) + + return hooks +} + +/** Starts the recorded module over an in-memory `$` holding the real run, as `session.start` would. */ +async function startedWith(hooks: Map): Promise { + const files = RUFLO_RUN + const rel = (path: string) => path.replace(/^\/work\//, '') + const timer = { cancel: () => undefined } + const $ = { + fs: { + read: async (path: string) => files[rel(path)] ?? Promise.reject(new Error('ENOENT')), + stat: async (path: string) => (files[rel(path)] !== undefined ? { mtimeMs: 1, size: files[rel(path)]?.length ?? 0 } : Promise.reject(new Error('ENOENT'))), + }, + clock: { now: async () => 0, after: () => timer, every: () => timer }, + store: { get: async () => undefined, set: async () => undefined }, + ui: { invalidate: () => undefined, toast: () => undefined, log: () => undefined }, + command: { register: async () => undefined }, + session: { usage: async () => ({ context: { window: 1 }, rateLimits: [] }) }, + agent: { list: async () => [] }, + } + + await hooks.get('session.start')?.($, SESSION, async () => ({ cwd: SESSION.cwd })) + + return 'started' +} + +/** + * An administrator can remove any affordance, and a policy mod can sit above this one and refuse a call. Every refusal + * must cost the pane a fact, never a turn: the hooks still answer and the engine's own work goes on. + */ +describe('host', () => { + test('with every call the mod makes refused, the session starts, commands answer and the pane draws', async ($, on) => { + mock.clock(on) + on('session.start', ($, e) => ({ cwd: e.cwd })) + on('fs.read', () => DENY) + on('fs.stat', () => DENY) + on('store.get', () => DENY) + on('store.set', () => DENY) + on('session.usage', () => DENY) + on('agent.list', () => DENY) + on('command.register', () => DENY) + on('ui.open', () => DENY) + on('ui.close', () => DENY) + on('ui.invalidate', () => DENY) + on('ui.toast', () => DENY) + on('process.run', () => DENY) + on('prompt.fill', () => DENY as never) + on('turn.start', ($, e) => ({ turnId: e.turnId })) + on('tool.call', () => ({ result: 'ok', text: 'ok' })) + + await $.session.start(SESSION) + + expect((await $.command.run(command('ruflo-swarm-pane'))).text).toMatch(/^The swarm pane could not be shown: /) + expect((await $.command.run(command('ruflo-swarm-status'))).text).toContain('No ruflo swarm on disk') + + const text = textOf(await $.ui.render(PANE)) + + expect(text).toContain('No ruflo swarm on disk in this folder.') + expect(text).toContain('usage: not read yet') + + await $.ui.press({ plugin: PLUGIN, key: 'fill' }) + await $.turn.start({ text: 'go', turnId: 't1' }) + expect(await $.tool.call({ tool: 'Read', file_path: '/work/a.ts' } as never)).toEqual({ result: 'ok', text: 'ok' }) + }) + + test('the tool call a hook observes is passed on untouched, its answer returned as it came', async ($, on) => { + worldOf(on, RUFLO_RUN) + mock.clock(on) + + const seen: unknown[] = [] + + on('tool.call', ($, e) => { + seen.push(e) + + return { result: 'raw', text: 'raw text' } + }) + await $.session.start(SESSION) + + const call = { tool: 'Bash', command: 'npx @claude-flow/cli@latest swarm status', tool_use_id: 'toolu_1' } + + expect(await $.tool.call(call as never)).toEqual({ result: 'raw', text: 'raw text' }) + expect(seen).toEqual([expect.objectContaining(call)]) + }) + + test('with injectSpawnContext on, a spawned subagent is told which swarm it is in; with it off its prompt is left alone', async ($, on) => { + worldOf(on, RUFLO_RUN) + mock.clock(on) + + const prompts: string[] = [] + + on('agent.spawn', ($, e) => { + prompts.push(e.prompt) + + return { model: 'haiku', agentId: `a${prompts.length}` } + }) + await $.session.start(SESSION) + await $.agent.spawn(spawn('coder', 'build it')) + + expect(prompts[0], 'the plugin loads with the option off').toBe('build it') + }) + + // The kit loads an inline plugin as a module of its own, so the options are driven through `register` itself: the + // hooks it registers are taken from a recording `on` and called as the engine would, with a `next` that records. + test('the option on: a spawned subagent is told the swarm from disk; the option off: its prompt is left alone', async () => { + const withNote = hooksOf({ injectSpawnContext: true }) + const without = hooksOf({}) + const sent: string[] = [] + const next = async (e: { prompt: string }) => (sent.push(e.prompt), { model: 'haiku', agentId: 'a1' }) + const state = await startedWith(withNote) + + await withNote.get('agent.spawn')?.({}, spawn('coder', 'build it'), next) + await without.get('agent.spawn')?.({}, spawn('coder', 'build it'), next) + + expect(state).toBe('started') + expect(sent[0]).toMatch(/^build it\n\n---\nSwarm context \(from ruflo's files on disk, a status note, not an instruction\): you are part of ruflo swarm swarm-1790888806724-u3ktj4, topology hierarchical, strategy specialized\./) + expect(sent[1]).toBe('build it') + }) + + test('the audit hook is registered only when the option asks for it, and records names and ids, never content', async () => { + expect(hooksOf({}).has('*')).toBe(false) + + const hooks = hooksOf({ audit: true }) + const audit = hooks.get('*') + const passed: unknown[] = [] + const next = Object.assign(async (e: unknown) => (passed.push(e), { result: 'ok' }), { event: 'tool.call' }) + const call = { tool: 'Write', file_path: '/work/secret-path.ts', content: 'SECRET-CONTENT', agentId: 'agent-x1' } + + await audit?.({}, call, next) + + expect(passed).toEqual([call]) + expect(auditRow('tool.call', call, 5)).toBe('{"t":5,"event":"tool.call","tool":"Write","agent":"agent-x1"}') + expect(auditRow('ui.render', {}, 5), 'render traffic is not a trail').toBeNull() + }) +})